@maincode-ai/matilda-code 0.19.7 → 0.19.9
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-JAZ2R5P5.js → agent-HKORTAHR.js} +1 -1
- package/chunks/{agent-headless-HUDZQCLT.js → agent-headless-F7NN2K2V.js} +1 -1
- package/chunks/askUserQuestion-MFLZ7MGJ.js +25 -0
- package/chunks/{chunk-DF4ZZ3BH.js → chunk-2GMJHSBF.js} +1 -1
- package/chunks/{chunk-YCINFF22.js → chunk-GN7ECS3T.js} +1 -1
- package/chunks/{chunk-UOF5DCHP.js → chunk-H5PGSQP2.js} +5 -5
- package/chunks/{chunk-4EZRS6DY.js → chunk-LNTXZVVL.js} +1 -1
- package/chunks/{chunk-4ROBKRWY.js → chunk-PKETH5KK.js} +2 -2
- package/chunks/{chunk-MHGRKMUG.js → chunk-TDVEFJRU.js} +1 -1
- package/chunks/{computer-use-BCNVOJO6.js → computer-use-BBMGDR5Q.js} +1 -1
- package/chunks/{contextCommand-7XW5T2FM.js → contextCommand-HGBI6TH7.js} +1 -1
- package/chunks/{edit-O5534MIA.js → edit-RF2YFGIO.js} +1 -1
- package/chunks/{enter-worktree-NWECAVR5.js → enter-worktree-VQHP27VO.js} +1 -1
- package/chunks/{enterPlanMode-Z5CC6RK4.js → enterPlanMode-6FANAN7K.js} +1 -1
- package/chunks/{exit-worktree-5QTROW2K.js → exit-worktree-JNQ5QJ3V.js} +1 -1
- package/chunks/{exitPlanMode-VT42OYWF.js → exitPlanMode-VTB3FQTP.js} +1 -1
- package/chunks/{geminiContentGenerator-DROE6XUC.js → geminiContentGenerator-UJMSJR23.js} +1 -1
- package/chunks/{glob-FWADRNRL.js → glob-A3AI5R62.js} +1 -1
- package/chunks/{grep-OFTEAZOC.js → grep-IH2T7KTD.js} +1 -1
- package/chunks/{matildaAgentContentGenerator-J3PXQMRW.js → matildaAgentContentGenerator-QKMXPB2A.js} +1 -1
- package/chunks/{matildaContentGenerator-6WVY252A.js → matildaContentGenerator-O2TF3IDJ.js} +1 -1
- package/chunks/{monitor-W2IPT7L4.js → monitor-4DTQSZEC.js} +1 -1
- package/chunks/{notebook-edit-E2RFMINC.js → notebook-edit-CZRTFD7U.js} +1 -1
- package/chunks/{openaiContentGenerator-PGCPCIUM.js → openaiContentGenerator-AZI4WQN4.js} +1 -1
- package/chunks/{ripGrep-CKRSCA2H.js → ripGrep-BZMM5FLN.js} +1 -1
- package/chunks/{scheduler-AQ72BFMX.js → scheduler-5LM4YZEI.js} +1 -1
- package/chunks/{serve-VAU7AZ4D.js → serve-7IPJHK45.js} +1 -1
- package/chunks/{shell-LMX4PBFS.js → shell-5O45TMEX.js} +1 -1
- package/chunks/{src-3ZEKD73Z.js → src-6MF6HV7Q.js} +1 -1
- package/chunks/{team-create-YCCOH5ZI.js → team-create-TRYOTUXF.js} +1 -1
- package/chunks/{web-search-LUARHW3X.js → web-search-6RI3HXMN.js} +1 -1
- package/chunks/{workflow-7JKMNIOX.js → workflow-TTK6ZMKW.js} +2 -2
- package/chunks/{write-file-QR6KKYVC.js → write-file-HOM26KX6.js} +1 -1
- package/cli.js +7 -7
- package/package.json +2 -2
- package/chunks/askUserQuestion-V5YLTC4J.js +0 -25
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 GLe,A as $X,C as VX,D as KX,E as E3,F as XF,G as Cd,H as zX,I as NE,J as XX,K as ZX,L as _E,La as yr,M as eZ,N as I3,O as y3,P as Wo,Q as D3,Qa as Dl,R as DT,Ra as Ja,S as tZ,Sa as nN,T as nZ,U as oZ,V as rZ,W as on,X as sZ,Y as iZ,Z as ZF,_ as aZ,_a as hZ,a as pT,aa as Gc,ab as $p,b as wi,ba as eN,bb as CZ,c as OX,ca as WLe,cb as Bl,d as Zs,da as jLe,db as yB,e as Wi,ea as tN,eb as _g,f as ji,fa as BT,fb as Rn,g as sr,ga as Jp,gb as EZ,h as f3,hb as IZ,i as p3,ib as oN,j as PX,k as UX,l as Ng,m as HX,ma as pZ,n as ws,o as hd,p as WX,q as CT,r as ET,s as IT,t as qX,u as h3,v as FE,w as JX,x as yT,y as zF,z as C3}from"./chunks/chunk-4ROBKRWY.js";import{a as pe,b as rN,c as DZ,d as BZ,e as SZ}from"./chunks/chunk-MHGRKMUG.js";import{a as rt,b as Ue,c as VF,d as EB,e as GX,h as hT,j as KF,k as IB,l as m,m as jX,n as YX}from"./chunks/chunk-DF4ZZ3BH.js";import{a as yZ}from"./chunks/chunk-7ZATDBWL.js";import{a as dZ,c as x3,d as gZ,e as mZ,g as fZ}from"./chunks/chunk-GC2F575A.js";import{a as lZ,c as ST,d as B3,e as S3}from"./chunks/chunk-3HUM74NZ.js";import{a as cZ,b as uZ,c as AZ,e as Fe}from"./chunks/chunk-JSFA3NEP.js";import{$b as K7,$c as cz,$d as TF,$h as fd,$k as jF,Ab as J7,Ai as kF,Aj as A3,Ba as U7,Bj as cX,Bk as BX,Cc as oz,Cd as Bz,Cg as RF,Cj as uX,Db as $7,Di as yl,Ed as Sz,Ee as of,Ef as uB,Fd as bF,Gd as cB,Hd as xz,Hj as PF,Ij as AX,J as B7,Jc as rz,Jg as Wz,Ji as oX,Jj as dX,Kg as jz,Kj as gX,La as uT,Li as rX,Lj as UF,Ma as Xs,Mj as ME,Nc as SF,Ne as Rz,Ng as uA,Ni as sX,Nj as HF,Od as bz,Og as l3,Oi as FF,Oj as jp,Pd as OLe,Pg as Yz,Pi as NF,Pj as mX,Q as k7,Qd as wz,Qf as Uz,Qh as Xz,Qj as mB,R as Mg,Ra as CF,Rd as rr,Re as Il,Rj as Hc,Sa as H7,Sj as pd,Td as Tz,Tj as fX,Tk as SX,Ud as Qz,Uk as xX,V as r3,Ve as Mz,Vj as pX,Vk as m3,We as kz,Wk as WF,Xc as sz,Xk as bX,Yc as iz,Yh as Zz,Yk as wX,Zc as az,Zi as iX,Zk as TX,_b as V7,_c as lz,_d as wF,_f as vE,_g as qz,aa as F7,ac as z7,ad as uz,bc as s3,bh as Jz,ca as pF,cc as BF,cd as Az,ce as Fg,cj as _F,db as G7,dc as X7,dj as aX,eb as W7,ec as LLe,ej as lX,ek as fT,f as tB,fa as N7,fb as j7,fc as i3,ff as Fz,fj as dB,fl as qp,g as xE,ga as _7,gb as kg,gd as lB,gh as MF,gk as hX,gl as QX,h as LK,ha as L7,hb as Y7,hc as Z7,hd as dz,hf as Nz,hg as vF,hi as eX,hj as Gi,hk as fB,hl as vX,ia as O7,id as gz,ih as c3,ik as CX,il as hB,j as uF,jc as ez,je as AT,jf as _z,jj as mT,kb as q7,kf as Lz,kk as Yp,kl as RX,ld as mz,lh as $z,li as ULe,lk as pB,md as fz,mh as Vz,mi as tX,nd as pz,nh as Kz,nl as MX,oa as hF,oh as gT,oj as Wp,ok as EX,ol as kX,pa as P7,pj as RE,pl as FX,ql as NX,rd as hz,rf as Gp,rg as dT,rk as GF,rl as _X,sd as Cz,sg as Hz,sj as LF,sk as IX,sl as LX,tf as QF,tj as gB,tk as yX,tl as YF,ud as Ez,ui as HLe,uk as DX,ul as qF,vd as Iz,vf as Oz,vh as zz,vk as d3,vl as CB,w as D7,wc as tz,wd as yz,wf as Pz,wg as Gz,wk as g3,wl as JF,xc as a3,xi as nX,xk as kE,xl as $F,y as AF,yb as yF,yd as Dz,yg as md,yh as u3,yi as AB,z as aB,zb as DF,zc as nz,zd as xF,ze as vz,zj as OF}from"./chunks/chunk-UOF5DCHP.js";import{a as bi}from"./chunks/chunk-TZIDSCTF.js";import"./chunks/chunk-FUNLOUYI.js";import"./chunks/chunk-R3H6IWFK.js";import{u as PLe}from"./chunks/chunk-OMZ5SGMK.js";import{a as QE}from"./chunks/chunk-KP6BLFQS.js";import"./chunks/chunk-RBG4ERTN.js";import"./chunks/chunk-TXMXCR7D.js";import"./chunks/chunk-YULUB745.js";import"./chunks/chunk-LQWORCPO.js";import"./chunks/chunk-TISQNFB5.js";import{b as S7,c as cA,d as x7,e as b7,g as n3,h as dF,j as gF,k as w7,m as T7,n as Q7,s as M7,u as nf,v as fF}from"./chunks/chunk-XXZH7C44.js";import"./chunks/chunk-47XR7IMP.js";import"./chunks/chunk-QEI3OETI.js";import"./chunks/chunk-QKYGQLWC.js";import{c as EF,f as IF}from"./chunks/chunk-MNGFXISD.js";import{b as mF,d as v7,h as R7,i as o3}from"./chunks/chunk-4R2OFVPK.js";import"./chunks/chunk-RNKDFE2S.js";import"./chunks/chunk-EMWHQSMS.js";import{c as TE}from"./chunks/chunk-GTR4V2PV.js";import{b as h7,d as C7,e as t3,i as E7,k as I7}from"./chunks/chunk-S4K76QPI.js";import{A as xi,d as i7,i as ZG,j as d7,s as g7,v as e3,w as m7,z as lF}from"./chunks/chunk-4EZRS6DY.js";import{c as c7,d as u7}from"./chunks/chunk-4F4DA5UI.js";import{c as a7,q as l7}from"./chunks/chunk-2XZIKUB6.js";import{h as A7,q as XG}from"./chunks/chunk-XYA3SFGC.js";import{b as Hi}from"./chunks/chunk-4J6DC24J.js";import"./chunks/chunk-LJR4RZZ2.js";import"./chunks/chunk-U347OO7S.js";import{g as Up,h as cF,i as iB,j as f7,l as p7}from"./chunks/chunk-CLUEFPSU.js";import"./chunks/chunk-7VGUNT5L.js";import{Bb as WK,Cc as Rg,Eb as jK,Gc as iF,Hb as oB,Hc as e7,Ib as YK,Jb as VG,Lc as t7,Qb as qK,Tc as zG,Vb as KG,Wb as sF,Xb as lT,Xc as aF,Yc as cT,Zb as JK,Zc as n7,cc as $K,db as JG,e as rF,gb as PK,h as Ir,hb as UK,hd as o7,ib as HK,jb as GK,jc as bE,jd as wE,kb as $G,lc as VK,nd as r7,pc as rB,qc as KK,r as qG,s as OK,sd as sB,t as Su,td as s7}from"./chunks/chunk-CFBZKYFB.js";import"./chunks/chunk-WVY2P6WH.js";import"./chunks/chunk-UIRBHC5X.js";import{h as Pp,j as zK,s as XK,w as ZK}from"./chunks/chunk-UY2R3ZQ4.js";import"./chunks/chunk-NDR7ZFUA.js";import{e as _K,l as Bu,p as Kt,q as nB}from"./chunks/chunk-5U3A6KMU.js";import{c as Hp,q as tf,v as y7}from"./chunks/chunk-LLQVLTPB.js";import"./chunks/chunk-XKDGRW3K.js";import"./chunks/chunk-ESSYHTAZ.js";import{b as FK,e as NK}from"./chunks/chunk-IOCF4XSR.js";import{B as iT,C as aT,F as Op,L as Mt,M as kK,U as oF,Y as He,a as gd,c as os,d as YG,f as TK,h as eF,i as Uc,j as El,k as QK,m as vK,n as RK,p as MK,x as tF,z as nF}from"./chunks/chunk-QWBNNEV2.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 Je,d as Se,e as NLe,f as k,g as _Le}from"./chunks/chunk-OWGSC52X.js";var KZ=Se((dSt,AN)=>{p();AN.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];process.platform!=="win32"&&AN.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&AN.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var tee=Se((mSt,RB)=>{p();var rs=globalThis.process,PE=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"};PE(rs)?(zZ=Je("assert"),QB=KZ(),XZ=/^win/i.test(rs.platform),TT=Je("events"),typeof TT!="function"&&(TT=TT.EventEmitter),rs.__signal_exit_emitter__?Ia=rs.__signal_exit_emitter__:(Ia=rs.__signal_exit_emitter__=new TT,Ia.count=0,Ia.emitted={}),Ia.infinite||(Ia.setMaxListeners(1/0),Ia.infinite=!0),RB.exports=function(e,t){if(!PE(globalThis.process))return function(){};zZ.equal(typeof e,"function","a callback must be provided for exit handler"),vB===!1&&_3();var n="exit";t&&t.alwaysLast&&(n="afterexit");var o=function(){Ia.removeListener(n,e),Ia.listeners("exit").length===0&&Ia.listeners("afterexit").length===0&&dN()};return Ia.on(n,e),o},dN=function(){!vB||!PE(globalThis.process)||(vB=!1,QB.forEach(function(t){try{rs.removeListener(t,gN[t])}catch{}}),rs.emit=mN,rs.reallyExit=L3,Ia.count-=1)},RB.exports.unload=dN,UE=function(t,n,o){Ia.emitted[t]||(Ia.emitted[t]=!0,Ia.emit(t,n,o))},gN={},QB.forEach(function(e){gN[e]=function(){if(PE(globalThis.process)){var n=rs.listeners(e);n.length===Ia.count&&(dN(),UE("exit",null,e),UE("afterexit",null,e),XZ&&e==="SIGHUP"&&(e="SIGINT"),rs.kill(rs.pid,e))}}}),RB.exports.signals=function(){return QB},vB=!1,_3=function(){vB||!PE(globalThis.process)||(vB=!0,Ia.count+=1,QB=QB.filter(function(t){try{return rs.on(t,gN[t]),!0}catch{return!1}}),rs.emit=eee,rs.reallyExit=ZZ)},RB.exports.load=_3,L3=rs.reallyExit,ZZ=function(t){PE(globalThis.process)&&(rs.exitCode=t||0,UE("exit",rs.exitCode,null),UE("afterexit",rs.exitCode,null),L3.call(rs,rs.exitCode))},mN=rs.emit,eee=function(t,n){if(t==="exit"&&PE(globalThis.process)){n!==void 0&&(rs.exitCode=n);var o=mN.apply(this,arguments);return UE("exit",rs.exitCode,null),UE("afterexit",rs.exitCode,null),o}else return mN.apply(this,arguments)}):RB.exports=function(){return function(){}};var zZ,QB,XZ,TT,Ia,dN,UE,gN,vB,_3,L3,ZZ,mN,eee});var see=Se(Xp=>{"use strict";p();Xp.ConcurrentRoot=1;Xp.ContinuousEventPriority=8;Xp.DefaultEventPriority=32;Xp.DiscreteEventPriority=2;Xp.IdleEventPriority=268435456;Xp.LegacyRoot=0;Xp.NoEventPriority=0});var fN=Se((ySt,iee)=>{"use strict";p();iee.exports=see()});var ete=Se(is=>{"use strict";p();function n8(e,t){var n=e.length;e.push(t);e:for(;0<n;){var o=n-1>>>1,r=e[o];if(0<xN(r,t))e[o]=t,e[n]=r,n=o;else break e}}function Lg(e){return e.length===0?null:e[0]}function wN(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>xN(a,n))l<r&&0>xN(c,a)?(e[o]=c,e[l]=n,o=l):(e[o]=a,e[i]=n,o=i);else if(l<r&&0>xN(c,n))e[o]=c,e[l]=n,o=l;else break e}}return t}function xN(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"?(Yee=performance,is.unstable_now=function(){return Yee.now()}):(Z3=Date,qee=Z3.now(),is.unstable_now=function(){return Z3.now()-qee});var Yee,Z3,qee,lf=[],Zp=[],jOe=1,gA=null,bl=3,o8=!1,MT=!1,kT=!1,r8=!1,Vee=typeof setTimeout=="function"?setTimeout:null,Kee=typeof clearTimeout=="function"?clearTimeout:null,Jee=typeof setImmediate<"u"?setImmediate:null;function bN(e){for(var t=Lg(Zp);t!==null;){if(t.callback===null)wN(Zp);else if(t.startTime<=e)wN(Zp),t.sortIndex=t.expirationTime,n8(lf,t);else break;t=Lg(Zp)}}function s8(e){if(kT=!1,bN(e),!MT)if(Lg(lf)!==null)MT=!0,LB||(LB=!0,_B());else{var t=Lg(Zp);t!==null&&i8(s8,t.startTime-e)}}var LB=!1,FT=-1,zee=5,Xee=-1;function Zee(){return r8?!0:!(is.unstable_now()-Xee<zee)}function e8(){if(r8=!1,LB){var e=is.unstable_now();Xee=e;var t=!0;try{e:{MT=!1,kT&&(kT=!1,Kee(FT),FT=-1),o8=!0;var n=bl;try{t:{for(bN(e),gA=Lg(lf);gA!==null&&!(gA.expirationTime>e&&Zee());){var o=gA.callback;if(typeof o=="function"){gA.callback=null,bl=gA.priorityLevel;var r=o(gA.expirationTime<=e);if(e=is.unstable_now(),typeof r=="function"){gA.callback=r,bN(e),t=!0;break t}gA===Lg(lf)&&wN(lf),bN(e)}else wN(lf);gA=Lg(lf)}if(gA!==null)t=!0;else{var s=Lg(Zp);s!==null&&i8(s8,s.startTime-e),t=!1}}break e}finally{gA=null,bl=n,o8=!1}t=void 0}}finally{t?_B():LB=!1}}}var _B;typeof Jee=="function"?_B=function(){Jee(e8)}:typeof MessageChannel<"u"?(t8=new MessageChannel,$ee=t8.port2,t8.port1.onmessage=e8,_B=function(){$ee.postMessage(null)}):_B=function(){Vee(e8,0)};var t8,$ee;function i8(e,t){FT=Vee(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"):zee=0<e?Math.floor(1e3/e):5};is.unstable_getCurrentPriorityLevel=function(){return bl};is.unstable_next=function(e){switch(bl){case 1:case 2:case 3:var t=3;break;default:t=bl}var n=bl;bl=t;try{return e()}finally{bl=n}};is.unstable_requestPaint=function(){r8=!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=bl;bl=e;try{return t()}finally{bl=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:jOe++,callback:t,priorityLevel:e,startTime:n,expirationTime:r,sortIndex:-1},n>o?(e.sortIndex=n,n8(Zp,e),Lg(lf)===null&&e===Lg(Zp)&&(kT?(Kee(FT),FT=-1):kT=!0,i8(s8,n-o))):(e.sortIndex=r,n8(lf,e),MT||o8||(MT=!0,LB||(LB=!0,_B()))),e};is.unstable_shouldYield=Zee;is.unstable_wrapCallback=function(e){var t=bl;return function(){var n=bl;bl=t;try{return e.apply(this,arguments)}finally{bl=n}}}});var a8=Se((Bxt,tte)=>{"use strict";p();tte.exports=ete()});var nte=Se((xxt,NT)=>{"use strict";p();NT.exports=function(e){function t(A,g,B,w){return new xk(A,g,B,w)}function n(){}function o(A){var g="https://react.dev/errors/"+A;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 #"+A+"; visit "+g+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function r(A){var g=A,B=A;if(A.alternate)for(;g.return;)g=g.return;else{A=g;do g=A,(g.flags&4098)!==0&&(B=g.return),A=g.return;while(A)}return g.tag===3?B:null}function s(A){if(r(A)!==A)throw Error(o(188))}function i(A){var g=A.alternate;if(!g){if(g=r(A),g===null)throw Error(o(188));return g!==A?null:A}for(var B=A,w=g;;){var v=B.return;if(v===null)break;var F=v.alternate;if(F===null){if(w=v.return,w!==null){B=w;continue}break}if(v.child===F.child){for(F=v.child;F;){if(F===B)return s(v),A;if(F===w)return s(v),g;F=F.sibling}throw Error(o(188))}if(B.return!==w.return)B=v,w=F;else{for(var oe=!1,De=v.child;De;){if(De===B){oe=!0,B=v,w=F;break}if(De===w){oe=!0,w=v,B=F;break}De=De.sibling}if(!oe){for(De=F.child;De;){if(De===B){oe=!0,B=F,w=v;break}if(De===w){oe=!0,w=F,B=v;break}De=De.sibling}if(!oe)throw Error(o(189))}}if(B.alternate!==w)throw Error(o(190))}if(B.tag!==3)throw Error(o(188));return B.stateNode.current===B?A:g}function a(A){var g=A.tag;if(g===5||g===26||g===27||g===6)return A;for(A=A.child;A!==null;){if(g=a(A),g!==null)return g;A=A.sibling}return null}function l(A){var g=A.tag;if(g===5||g===26||g===27||g===6)return A;for(A=A.child;A!==null;){if(A.tag!==4&&(g=l(A),g!==null))return g;A=A.sibling}return null}function c(A){return A===null||typeof A!="object"?null:(A=_c&&A[_c]||A["@@iterator"],typeof A=="function"?A:null)}function u(A){if(A==null)return null;if(typeof A=="function")return A.$$typeof===Ii?null:A.displayName||A.name||null;if(typeof A=="string")return A;switch(A){case Tp:return"Fragment";case Pe:return"Profiler";case Qk:return"StrictMode";case Zn:return"Suspense";case Cr:return"SuspenseList";case Lo:return"Activity"}if(typeof A=="object")switch(A.$$typeof){case wp:return"Portal";case gt:return A.displayName||"Context";case ut:return(A._context.displayName||"Context")+".Consumer";case Lt:var g=A.render;return A=A.displayName,A||(A=g.displayName||g.name||"",A=A!==""?"ForwardRef("+A+")":"ForwardRef"),A;case _o:return g=A.displayName||null,g!==null?g:u(A.type)||"Memo";case eo:g=A._payload,A=A._init;try{return u(A(g))}catch{}}return null}function d(A){return{current:A}}function h(A){0>OD||(A.current=DG[OD],DG[OD]=null,OD--)}function f(A,g){OD++,DG[OD]=A.current,A.current=g}function y(A){return A>>>=0,A===0?32:31-(ELe(A)/ILe|0)|0}function I(A){var g=A&42;if(g!==0)return g;switch(A&-A){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 A&261888;case 262144:case 524288:case 1048576:case 2097152:return A&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return A&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return A}}function S(A,g,B){var w=A.pendingLanes;if(w===0)return 0;var v=0,F=A.suspendedLanes,oe=A.pingedLanes;A=A.warmLanes;var De=w&134217727;return De!==0?(w=De&~F,w!==0?v=I(w):(oe&=De,oe!==0?v=I(oe):B||(B=De&~A,B!==0&&(v=I(B))))):(De=w&~F,De!==0?v=I(De):oe!==0?v=I(oe):B||(B=w&~A,B!==0&&(v=I(B)))),v===0?0:g!==0&&g!==v&&(g&F)===0&&(F=v&-v,B=g&-g,F>=B||F===32&&(B&4194048)!==0)?g:v}function x(A,g){return(A.pendingLanes&~(A.suspendedLanes&~A.pingedLanes)&g)===0}function b(A,g){switch(A){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 A=Nk;return Nk<<=1,(Nk&62914560)===0&&(Nk=4194304),A}function R(A){for(var g=[],B=0;31>B;B++)g.push(A);return g}function Q(A,g){A.pendingLanes|=g,g!==268435456&&(A.suspendedLanes=0,A.pingedLanes=0,A.warmLanes=0)}function L(A,g,B,w,v,F){var oe=A.pendingLanes;A.pendingLanes=B,A.suspendedLanes=0,A.pingedLanes=0,A.warmLanes=0,A.expiredLanes&=B,A.entangledLanes&=B,A.errorRecoveryDisabledLanes&=B,A.shellSuspendCounter=0;var De=A.entanglements,ze=A.expirationTimes,lt=A.hiddenUpdates;for(B=oe&~B;0<B;){var xt=31-hu(B),ht=1<<xt;De[xt]=0,ze[xt]=-1;var Rt=lt[xt];if(Rt!==null)for(lt[xt]=null,xt=0;xt<Rt.length;xt++){var Yn=Rt[xt];Yn!==null&&(Yn.lane&=-536870913)}B&=~ht}w!==0&&O(A,w,0),F!==0&&v===0&&A.tag!==0&&(A.suspendedLanes|=F&~(oe&~g))}function O(A,g,B){A.pendingLanes|=g,A.suspendedLanes&=~g;var w=31-hu(g);A.entangledLanes|=g,A.entanglements[w]=A.entanglements[w]|1073741824|B&261930}function Y(A,g){var B=A.entangledLanes|=g;for(A=A.entanglements;B;){var w=31-hu(B),v=1<<w;v&g|A[w]&g&&(A[w]|=g),B&=~v}}function W(A,g){var B=g&-g;return B=(B&42)!==0?1:P(B),(B&(A.suspendedLanes|g))!==0?0:B}function P(A){switch(A){case 2:A=1;break;case 8:A=4;break;case 32:A=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:A=128;break;case 268435456:A=134217728;break;default:A=0}return A}function j(A){return A&=-A,2<A?8<A?(A&134217727)!==0?32:268435456:8:2}function _(A){if(typeof xLe=="function"&&bLe(A),Cu&&typeof Cu.setStrictMode=="function")try{Cu.setStrictMode($w,A)}catch{}}function N(A,g){return A===g&&(A!==0||1/A===1/g)||A!==A&&g!==g}function G(A){if(xG===void 0)try{throw Error()}catch(B){var g=B.stack.trim().match(/\n( *(at )?)/);xG=g&&g[1]||"",EK=-1<B.stack.indexOf(`
|
|
4
|
+
import{$ as GLe,A as $X,C as VX,D as KX,E as E3,F as XF,G as Cd,H as zX,I as NE,J as XX,K as ZX,L as _E,La as yr,M as eZ,N as I3,O as y3,P as Wo,Q as D3,Qa as Dl,R as DT,Ra as Ja,S as tZ,Sa as nN,T as nZ,U as oZ,V as rZ,W as on,X as sZ,Y as iZ,Z as ZF,_ as aZ,_a as hZ,a as pT,aa as Gc,ab as $p,b as wi,ba as eN,bb as CZ,c as OX,ca as WLe,cb as Bl,d as Zs,da as jLe,db as yB,e as Wi,ea as tN,eb as _g,f as ji,fa as BT,fb as Rn,g as sr,ga as Jp,gb as EZ,h as f3,hb as IZ,i as p3,ib as oN,j as PX,k as UX,l as Ng,m as HX,ma as pZ,n as ws,o as hd,p as WX,q as CT,r as ET,s as IT,t as qX,u as h3,v as FE,w as JX,x as yT,y as zF,z as C3}from"./chunks/chunk-PKETH5KK.js";import{a as pe,b as rN,c as DZ,d as BZ,e as SZ}from"./chunks/chunk-TDVEFJRU.js";import{a as rt,b as Ue,c as VF,d as EB,e as GX,h as hT,j as KF,k as IB,l as m,m as jX,n as YX}from"./chunks/chunk-2GMJHSBF.js";import{a as yZ}from"./chunks/chunk-7ZATDBWL.js";import{a as dZ,c as x3,d as gZ,e as mZ,g as fZ}from"./chunks/chunk-GC2F575A.js";import{a as lZ,c as ST,d as B3,e as S3}from"./chunks/chunk-3HUM74NZ.js";import{a as cZ,b as uZ,c as AZ,e as Fe}from"./chunks/chunk-JSFA3NEP.js";import{$b as K7,$c as cz,$d as TF,$h as fd,$k as jF,Ab as J7,Ai as kF,Aj as A3,Ba as U7,Bj as cX,Bk as BX,Cc as oz,Cd as Bz,Cg as RF,Cj as uX,Db as $7,Di as yl,Ed as Sz,Ee as of,Ef as uB,Fd as bF,Gd as cB,Hd as xz,Hj as PF,Ij as AX,J as B7,Jc as rz,Jg as Wz,Ji as oX,Jj as dX,Kg as jz,Kj as gX,La as uT,Li as rX,Lj as UF,Ma as Xs,Mj as ME,Nc as SF,Ne as Rz,Ng as uA,Ni as sX,Nj as HF,Od as bz,Og as l3,Oi as FF,Oj as jp,Pd as OLe,Pg as Yz,Pi as NF,Pj as mX,Q as k7,Qd as wz,Qf as Uz,Qh as Xz,Qj as mB,R as Mg,Ra as CF,Rd as rr,Re as Il,Rj as Hc,Sa as H7,Sj as pd,Td as Tz,Tj as fX,Tk as SX,Ud as Qz,Uk as xX,V as r3,Ve as Mz,Vj as pX,Vk as m3,We as kz,Wk as WF,Xc as sz,Xk as bX,Yc as iz,Yh as Zz,Yk as wX,Zc as az,Zi as iX,Zk as TX,_b as V7,_c as lz,_d as wF,_f as vE,_g as qz,aa as F7,ac as z7,ad as uz,bc as s3,bh as Jz,ca as pF,cc as BF,cd as Az,ce as Fg,cj as _F,db as G7,dc as X7,dj as aX,eb as W7,ec as LLe,ej as lX,ek as fT,f as tB,fa as N7,fb as j7,fc as i3,ff as Fz,fj as dB,fl as qp,g as xE,ga as _7,gb as kg,gd as lB,gh as MF,gk as hX,gl as QX,h as LK,ha as L7,hb as Y7,hc as Z7,hd as dz,hf as Nz,hg as vF,hi as eX,hj as Gi,hk as fB,hl as vX,ia as O7,id as gz,ih as c3,ik as CX,il as hB,j as uF,jc as ez,je as AT,jf as _z,jj as mT,kb as q7,kf as Lz,kk as Yp,kl as RX,ld as mz,lh as $z,li as ULe,lk as pB,md as fz,mh as Vz,mi as tX,nd as pz,nh as Kz,nl as MX,oa as hF,oh as gT,oj as Wp,ok as EX,ol as kX,pa as P7,pj as RE,pl as FX,ql as NX,rd as hz,rf as Gp,rg as dT,rk as GF,rl as _X,sd as Cz,sg as Hz,sj as LF,sk as IX,sl as LX,tf as QF,tj as gB,tk as yX,tl as YF,ud as Ez,ui as HLe,uk as DX,ul as qF,vd as Iz,vf as Oz,vh as zz,vk as d3,vl as CB,w as D7,wc as tz,wd as yz,wf as Pz,wg as Gz,wk as g3,wl as JF,xc as a3,xi as nX,xk as kE,xl as $F,y as AF,yb as yF,yd as Dz,yg as md,yh as u3,yi as AB,z as aB,zb as DF,zc as nz,zd as xF,ze as vz,zj as OF}from"./chunks/chunk-H5PGSQP2.js";import{a as bi}from"./chunks/chunk-TZIDSCTF.js";import"./chunks/chunk-FUNLOUYI.js";import"./chunks/chunk-R3H6IWFK.js";import{u as PLe}from"./chunks/chunk-OMZ5SGMK.js";import{a as QE}from"./chunks/chunk-KP6BLFQS.js";import"./chunks/chunk-RBG4ERTN.js";import"./chunks/chunk-TXMXCR7D.js";import"./chunks/chunk-YULUB745.js";import"./chunks/chunk-LQWORCPO.js";import"./chunks/chunk-TISQNFB5.js";import{b as S7,c as cA,d as x7,e as b7,g as n3,h as dF,j as gF,k as w7,m as T7,n as Q7,s as M7,u as nf,v as fF}from"./chunks/chunk-XXZH7C44.js";import"./chunks/chunk-47XR7IMP.js";import"./chunks/chunk-QEI3OETI.js";import"./chunks/chunk-QKYGQLWC.js";import{c as EF,f as IF}from"./chunks/chunk-MNGFXISD.js";import{b as mF,d as v7,h as R7,i as o3}from"./chunks/chunk-4R2OFVPK.js";import"./chunks/chunk-RNKDFE2S.js";import"./chunks/chunk-EMWHQSMS.js";import{c as TE}from"./chunks/chunk-GTR4V2PV.js";import{b as h7,d as C7,e as t3,i as E7,k as I7}from"./chunks/chunk-S4K76QPI.js";import{A as xi,d as i7,i as ZG,j as d7,s as g7,v as e3,w as m7,z as lF}from"./chunks/chunk-LNTXZVVL.js";import{c as c7,d as u7}from"./chunks/chunk-4F4DA5UI.js";import{c as a7,q as l7}from"./chunks/chunk-2XZIKUB6.js";import{h as A7,q as XG}from"./chunks/chunk-XYA3SFGC.js";import{b as Hi}from"./chunks/chunk-4J6DC24J.js";import"./chunks/chunk-LJR4RZZ2.js";import"./chunks/chunk-U347OO7S.js";import{g as Up,h as cF,i as iB,j as f7,l as p7}from"./chunks/chunk-CLUEFPSU.js";import"./chunks/chunk-7VGUNT5L.js";import{Bb as WK,Cc as Rg,Eb as jK,Gc as iF,Hb as oB,Hc as e7,Ib as YK,Jb as VG,Lc as t7,Qb as qK,Tc as zG,Vb as KG,Wb as sF,Xb as lT,Xc as aF,Yc as cT,Zb as JK,Zc as n7,cc as $K,db as JG,e as rF,gb as PK,h as Ir,hb as UK,hd as o7,ib as HK,jb as GK,jc as bE,jd as wE,kb as $G,lc as VK,nd as r7,pc as rB,qc as KK,r as qG,s as OK,sd as sB,t as Su,td as s7}from"./chunks/chunk-CFBZKYFB.js";import"./chunks/chunk-WVY2P6WH.js";import"./chunks/chunk-UIRBHC5X.js";import{h as Pp,j as zK,s as XK,w as ZK}from"./chunks/chunk-UY2R3ZQ4.js";import"./chunks/chunk-NDR7ZFUA.js";import{e as _K,l as Bu,p as Kt,q as nB}from"./chunks/chunk-5U3A6KMU.js";import{c as Hp,q as tf,v as y7}from"./chunks/chunk-LLQVLTPB.js";import"./chunks/chunk-XKDGRW3K.js";import"./chunks/chunk-ESSYHTAZ.js";import{b as FK,e as NK}from"./chunks/chunk-IOCF4XSR.js";import{B as iT,C as aT,F as Op,L as Mt,M as kK,U as oF,Y as He,a as gd,c as os,d as YG,f as TK,h as eF,i as Uc,j as El,k as QK,m as vK,n as RK,p as MK,x as tF,z as nF}from"./chunks/chunk-QWBNNEV2.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 Je,d as Se,e as NLe,f as k,g as _Le}from"./chunks/chunk-OWGSC52X.js";var KZ=Se((dSt,AN)=>{p();AN.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];process.platform!=="win32"&&AN.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&AN.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var tee=Se((mSt,RB)=>{p();var rs=globalThis.process,PE=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"};PE(rs)?(zZ=Je("assert"),QB=KZ(),XZ=/^win/i.test(rs.platform),TT=Je("events"),typeof TT!="function"&&(TT=TT.EventEmitter),rs.__signal_exit_emitter__?Ia=rs.__signal_exit_emitter__:(Ia=rs.__signal_exit_emitter__=new TT,Ia.count=0,Ia.emitted={}),Ia.infinite||(Ia.setMaxListeners(1/0),Ia.infinite=!0),RB.exports=function(e,t){if(!PE(globalThis.process))return function(){};zZ.equal(typeof e,"function","a callback must be provided for exit handler"),vB===!1&&_3();var n="exit";t&&t.alwaysLast&&(n="afterexit");var o=function(){Ia.removeListener(n,e),Ia.listeners("exit").length===0&&Ia.listeners("afterexit").length===0&&dN()};return Ia.on(n,e),o},dN=function(){!vB||!PE(globalThis.process)||(vB=!1,QB.forEach(function(t){try{rs.removeListener(t,gN[t])}catch{}}),rs.emit=mN,rs.reallyExit=L3,Ia.count-=1)},RB.exports.unload=dN,UE=function(t,n,o){Ia.emitted[t]||(Ia.emitted[t]=!0,Ia.emit(t,n,o))},gN={},QB.forEach(function(e){gN[e]=function(){if(PE(globalThis.process)){var n=rs.listeners(e);n.length===Ia.count&&(dN(),UE("exit",null,e),UE("afterexit",null,e),XZ&&e==="SIGHUP"&&(e="SIGINT"),rs.kill(rs.pid,e))}}}),RB.exports.signals=function(){return QB},vB=!1,_3=function(){vB||!PE(globalThis.process)||(vB=!0,Ia.count+=1,QB=QB.filter(function(t){try{return rs.on(t,gN[t]),!0}catch{return!1}}),rs.emit=eee,rs.reallyExit=ZZ)},RB.exports.load=_3,L3=rs.reallyExit,ZZ=function(t){PE(globalThis.process)&&(rs.exitCode=t||0,UE("exit",rs.exitCode,null),UE("afterexit",rs.exitCode,null),L3.call(rs,rs.exitCode))},mN=rs.emit,eee=function(t,n){if(t==="exit"&&PE(globalThis.process)){n!==void 0&&(rs.exitCode=n);var o=mN.apply(this,arguments);return UE("exit",rs.exitCode,null),UE("afterexit",rs.exitCode,null),o}else return mN.apply(this,arguments)}):RB.exports=function(){return function(){}};var zZ,QB,XZ,TT,Ia,dN,UE,gN,vB,_3,L3,ZZ,mN,eee});var see=Se(Xp=>{"use strict";p();Xp.ConcurrentRoot=1;Xp.ContinuousEventPriority=8;Xp.DefaultEventPriority=32;Xp.DiscreteEventPriority=2;Xp.IdleEventPriority=268435456;Xp.LegacyRoot=0;Xp.NoEventPriority=0});var fN=Se((ySt,iee)=>{"use strict";p();iee.exports=see()});var ete=Se(is=>{"use strict";p();function n8(e,t){var n=e.length;e.push(t);e:for(;0<n;){var o=n-1>>>1,r=e[o];if(0<xN(r,t))e[o]=t,e[n]=r,n=o;else break e}}function Lg(e){return e.length===0?null:e[0]}function wN(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>xN(a,n))l<r&&0>xN(c,a)?(e[o]=c,e[l]=n,o=l):(e[o]=a,e[i]=n,o=i);else if(l<r&&0>xN(c,n))e[o]=c,e[l]=n,o=l;else break e}}return t}function xN(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"?(Yee=performance,is.unstable_now=function(){return Yee.now()}):(Z3=Date,qee=Z3.now(),is.unstable_now=function(){return Z3.now()-qee});var Yee,Z3,qee,lf=[],Zp=[],jOe=1,gA=null,bl=3,o8=!1,MT=!1,kT=!1,r8=!1,Vee=typeof setTimeout=="function"?setTimeout:null,Kee=typeof clearTimeout=="function"?clearTimeout:null,Jee=typeof setImmediate<"u"?setImmediate:null;function bN(e){for(var t=Lg(Zp);t!==null;){if(t.callback===null)wN(Zp);else if(t.startTime<=e)wN(Zp),t.sortIndex=t.expirationTime,n8(lf,t);else break;t=Lg(Zp)}}function s8(e){if(kT=!1,bN(e),!MT)if(Lg(lf)!==null)MT=!0,LB||(LB=!0,_B());else{var t=Lg(Zp);t!==null&&i8(s8,t.startTime-e)}}var LB=!1,FT=-1,zee=5,Xee=-1;function Zee(){return r8?!0:!(is.unstable_now()-Xee<zee)}function e8(){if(r8=!1,LB){var e=is.unstable_now();Xee=e;var t=!0;try{e:{MT=!1,kT&&(kT=!1,Kee(FT),FT=-1),o8=!0;var n=bl;try{t:{for(bN(e),gA=Lg(lf);gA!==null&&!(gA.expirationTime>e&&Zee());){var o=gA.callback;if(typeof o=="function"){gA.callback=null,bl=gA.priorityLevel;var r=o(gA.expirationTime<=e);if(e=is.unstable_now(),typeof r=="function"){gA.callback=r,bN(e),t=!0;break t}gA===Lg(lf)&&wN(lf),bN(e)}else wN(lf);gA=Lg(lf)}if(gA!==null)t=!0;else{var s=Lg(Zp);s!==null&&i8(s8,s.startTime-e),t=!1}}break e}finally{gA=null,bl=n,o8=!1}t=void 0}}finally{t?_B():LB=!1}}}var _B;typeof Jee=="function"?_B=function(){Jee(e8)}:typeof MessageChannel<"u"?(t8=new MessageChannel,$ee=t8.port2,t8.port1.onmessage=e8,_B=function(){$ee.postMessage(null)}):_B=function(){Vee(e8,0)};var t8,$ee;function i8(e,t){FT=Vee(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"):zee=0<e?Math.floor(1e3/e):5};is.unstable_getCurrentPriorityLevel=function(){return bl};is.unstable_next=function(e){switch(bl){case 1:case 2:case 3:var t=3;break;default:t=bl}var n=bl;bl=t;try{return e()}finally{bl=n}};is.unstable_requestPaint=function(){r8=!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=bl;bl=e;try{return t()}finally{bl=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:jOe++,callback:t,priorityLevel:e,startTime:n,expirationTime:r,sortIndex:-1},n>o?(e.sortIndex=n,n8(Zp,e),Lg(lf)===null&&e===Lg(Zp)&&(kT?(Kee(FT),FT=-1):kT=!0,i8(s8,n-o))):(e.sortIndex=r,n8(lf,e),MT||o8||(MT=!0,LB||(LB=!0,_B()))),e};is.unstable_shouldYield=Zee;is.unstable_wrapCallback=function(e){var t=bl;return function(){var n=bl;bl=t;try{return e.apply(this,arguments)}finally{bl=n}}}});var a8=Se((Bxt,tte)=>{"use strict";p();tte.exports=ete()});var nte=Se((xxt,NT)=>{"use strict";p();NT.exports=function(e){function t(A,g,B,w){return new xk(A,g,B,w)}function n(){}function o(A){var g="https://react.dev/errors/"+A;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 #"+A+"; visit "+g+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function r(A){var g=A,B=A;if(A.alternate)for(;g.return;)g=g.return;else{A=g;do g=A,(g.flags&4098)!==0&&(B=g.return),A=g.return;while(A)}return g.tag===3?B:null}function s(A){if(r(A)!==A)throw Error(o(188))}function i(A){var g=A.alternate;if(!g){if(g=r(A),g===null)throw Error(o(188));return g!==A?null:A}for(var B=A,w=g;;){var v=B.return;if(v===null)break;var F=v.alternate;if(F===null){if(w=v.return,w!==null){B=w;continue}break}if(v.child===F.child){for(F=v.child;F;){if(F===B)return s(v),A;if(F===w)return s(v),g;F=F.sibling}throw Error(o(188))}if(B.return!==w.return)B=v,w=F;else{for(var oe=!1,De=v.child;De;){if(De===B){oe=!0,B=v,w=F;break}if(De===w){oe=!0,w=v,B=F;break}De=De.sibling}if(!oe){for(De=F.child;De;){if(De===B){oe=!0,B=F,w=v;break}if(De===w){oe=!0,w=F,B=v;break}De=De.sibling}if(!oe)throw Error(o(189))}}if(B.alternate!==w)throw Error(o(190))}if(B.tag!==3)throw Error(o(188));return B.stateNode.current===B?A:g}function a(A){var g=A.tag;if(g===5||g===26||g===27||g===6)return A;for(A=A.child;A!==null;){if(g=a(A),g!==null)return g;A=A.sibling}return null}function l(A){var g=A.tag;if(g===5||g===26||g===27||g===6)return A;for(A=A.child;A!==null;){if(A.tag!==4&&(g=l(A),g!==null))return g;A=A.sibling}return null}function c(A){return A===null||typeof A!="object"?null:(A=_c&&A[_c]||A["@@iterator"],typeof A=="function"?A:null)}function u(A){if(A==null)return null;if(typeof A=="function")return A.$$typeof===Ii?null:A.displayName||A.name||null;if(typeof A=="string")return A;switch(A){case Tp:return"Fragment";case Pe:return"Profiler";case Qk:return"StrictMode";case Zn:return"Suspense";case Cr:return"SuspenseList";case Lo:return"Activity"}if(typeof A=="object")switch(A.$$typeof){case wp:return"Portal";case gt:return A.displayName||"Context";case ut:return(A._context.displayName||"Context")+".Consumer";case Lt:var g=A.render;return A=A.displayName,A||(A=g.displayName||g.name||"",A=A!==""?"ForwardRef("+A+")":"ForwardRef"),A;case _o:return g=A.displayName||null,g!==null?g:u(A.type)||"Memo";case eo:g=A._payload,A=A._init;try{return u(A(g))}catch{}}return null}function d(A){return{current:A}}function h(A){0>OD||(A.current=DG[OD],DG[OD]=null,OD--)}function f(A,g){OD++,DG[OD]=A.current,A.current=g}function y(A){return A>>>=0,A===0?32:31-(ELe(A)/ILe|0)|0}function I(A){var g=A&42;if(g!==0)return g;switch(A&-A){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 A&261888;case 262144:case 524288:case 1048576:case 2097152:return A&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return A&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return A}}function S(A,g,B){var w=A.pendingLanes;if(w===0)return 0;var v=0,F=A.suspendedLanes,oe=A.pingedLanes;A=A.warmLanes;var De=w&134217727;return De!==0?(w=De&~F,w!==0?v=I(w):(oe&=De,oe!==0?v=I(oe):B||(B=De&~A,B!==0&&(v=I(B))))):(De=w&~F,De!==0?v=I(De):oe!==0?v=I(oe):B||(B=w&~A,B!==0&&(v=I(B)))),v===0?0:g!==0&&g!==v&&(g&F)===0&&(F=v&-v,B=g&-g,F>=B||F===32&&(B&4194048)!==0)?g:v}function x(A,g){return(A.pendingLanes&~(A.suspendedLanes&~A.pingedLanes)&g)===0}function b(A,g){switch(A){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 A=Nk;return Nk<<=1,(Nk&62914560)===0&&(Nk=4194304),A}function R(A){for(var g=[],B=0;31>B;B++)g.push(A);return g}function Q(A,g){A.pendingLanes|=g,g!==268435456&&(A.suspendedLanes=0,A.pingedLanes=0,A.warmLanes=0)}function L(A,g,B,w,v,F){var oe=A.pendingLanes;A.pendingLanes=B,A.suspendedLanes=0,A.pingedLanes=0,A.warmLanes=0,A.expiredLanes&=B,A.entangledLanes&=B,A.errorRecoveryDisabledLanes&=B,A.shellSuspendCounter=0;var De=A.entanglements,ze=A.expirationTimes,lt=A.hiddenUpdates;for(B=oe&~B;0<B;){var xt=31-hu(B),ht=1<<xt;De[xt]=0,ze[xt]=-1;var Rt=lt[xt];if(Rt!==null)for(lt[xt]=null,xt=0;xt<Rt.length;xt++){var Yn=Rt[xt];Yn!==null&&(Yn.lane&=-536870913)}B&=~ht}w!==0&&O(A,w,0),F!==0&&v===0&&A.tag!==0&&(A.suspendedLanes|=F&~(oe&~g))}function O(A,g,B){A.pendingLanes|=g,A.suspendedLanes&=~g;var w=31-hu(g);A.entangledLanes|=g,A.entanglements[w]=A.entanglements[w]|1073741824|B&261930}function Y(A,g){var B=A.entangledLanes|=g;for(A=A.entanglements;B;){var w=31-hu(B),v=1<<w;v&g|A[w]&g&&(A[w]|=g),B&=~v}}function W(A,g){var B=g&-g;return B=(B&42)!==0?1:P(B),(B&(A.suspendedLanes|g))!==0?0:B}function P(A){switch(A){case 2:A=1;break;case 8:A=4;break;case 32:A=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:A=128;break;case 268435456:A=134217728;break;default:A=0}return A}function j(A){return A&=-A,2<A?8<A?(A&134217727)!==0?32:268435456:8:2}function _(A){if(typeof xLe=="function"&&bLe(A),Cu&&typeof Cu.setStrictMode=="function")try{Cu.setStrictMode($w,A)}catch{}}function N(A,g){return A===g&&(A!==0||1/A===1/g)||A!==A&&g!==g}function G(A){if(xG===void 0)try{throw Error()}catch(B){var g=B.stack.trim().match(/\n( *(at )?)/);xG=g&&g[1]||"",EK=-1<B.stack.indexOf(`
|
|
5
5
|
at`)?" (<anonymous>)":-1<B.stack.indexOf("@")?"@unknown:0:0":""}return`
|
|
6
6
|
`+xG+A+EK}function U(A,g){if(!A||bG)return"";bG=!0;var B=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var w={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(Yn){var Rt=Yn}Reflect.construct(A,[],ht)}else{try{ht.call()}catch(Yn){Rt=Yn}A.call(ht.prototype)}}else{try{throw Error()}catch(Yn){Rt=Yn}(ht=A())&&typeof ht.catch=="function"&&ht.catch(function(){})}}catch(Yn){if(Yn&&Rt&&typeof Yn.stack=="string")return[Yn.stack,Rt.stack]}return[null,null]}};w.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var v=Object.getOwnPropertyDescriptor(w.DetermineComponentFrameRoot,"name");v&&v.configurable&&Object.defineProperty(w.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var F=w.DetermineComponentFrameRoot(),oe=F[0],De=F[1];if(oe&&De){var ze=oe.split(`
|
|
7
7
|
`),lt=De.split(`
|
|
@@ -281,7 +281,7 @@ ${t.stderr}`,e.worktree,e.changedFilesSet);return{exitCode:t.exitCode,findings:n
|
|
|
281
281
|
`)){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=LI(a.file_name,t);ux(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 Yze={name:"go-vet",source:"typecheck",detect:({worktree:e})=>Tf(kh(e,"go.mod"))?cx("go")?{ok:!0}:{ok:!1,reason:"go not in PATH"}:{ok:!1,reason:"go.mod not found"},run:e=>{let t=lx(e.worktree,"go",["vet","./..."],P6),n=qze(`${t.stdout}
|
|
282
282
|
${t.stderr}`,e.worktree,e.changedFilesSet);return{exitCode:t.exitCode,findings:n,timedOut:t.timedOut}}};function qze(e,t,n){let o=[],r=/^(.+?\.go):(\d+)(?::(\d+))?:\s+(.+)$/gm,s;for(;(s=r.exec(e))!==null;){let i=LI(s[1],t);ux(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 Jze={name:"golangci-lint",source:"linter",detect:({worktree:e})=>Tf(kh(e,"go.mod"))?cx("golangci-lint")?{ok:!0}:{ok:!1,reason:"golangci-lint not in PATH"}:{ok:!1,reason:"go.mod not found"},run:e=>{let t=lx(e.worktree,"golangci-lint",["run","--out-format=json","./..."],U6),n=$ze(t.stdout,e.worktree,e.changedFilesSet);return{exitCode:t.exitCode,findings:n,timedOut:t.timedOut}}};function $ze(e,t,n){let o;try{o=JSON.parse(e)}catch{return[]}let r=[];for(let s of o.Issues??[]){let i=LI(s.Pos.Filename,t);ux(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 Vze=[Nze,Oze,Hze,Wze,Yze,Jze];async function Kze(e){let t=kze(e.worktree);if(!Tf(t))throw new Error(`Worktree not found: ${t}`);let n=[];try{let d=Tfe(e["changed-files"],"utf8");n=JSON.parse(d)}catch(d){throw new Error(`Failed to read changed-files JSON at ${e["changed-files"]}: ${d.message}`)}if(!Array.isArray(n))throw new Error("changed-files JSON must be an array of paths");let o=n.map(d=>LI(d,t)),r=new Set(o),s={worktree:t,changedFiles:o,changedFilesSet:r},i=[],a=[],l=[];for(let d of Vze){let h=d.detect(s);if(!h.ok){l.push({tool:d.name,reason:h.reason});continue}let f=Date.now(),y=d.run(s),I=Date.now()-f;i.push(...y.findings),a.push({tool:d.name,source:d.source,exitCode:y.exitCode,durationMs:I,findingsCount:y.findings.length,timedOut:y.timedOut})}let c={worktree:t,changedFiles:o,findings:i,toolsRun:a,toolsSkipped:l};Rze(Mze(e.out),{recursive:!0}),vze(e.out,JSON.stringify(c,null,2)+`
|
|
283
283
|
`,"utf8");let u=a.map(d=>`${d.tool}=${d.findingsCount}${d.timedOut?" (timeout)":""}`).join(", ");rt(`Wrote deterministic report to ${e.out}: ${i.length} findings (${u||"no tools applicable"}; skipped ${l.length})`)}var Qfe={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 Kze(e)}};p();import{writeFileSync as zze,readFileSync as Xze}from"node:fs";var Zze=new Set(["failure","cancelled","timed_out","action_required"]),eXe=new Set(["failure","error"]),vfe=new Set(["queued","in_progress","pending"]);function tXe(e,t){let n=[],o=!1;for(let s of e)s.status==="completed"?s.conclusion&&Zze.has(s.conclusion)&&n.push(s.name):vfe.has(s.status)&&(o=!0);for(let s of t)eXe.has(s.state)?n.push(s.context):vfe.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 nXe(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 oXe(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);ax();let c=wf("api",`repos/${a}/${l}/pulls/${t}`,"--jq",".user.login"),u=Cfe(),d=c.toLowerCase()===u.toLowerCase(),f=L6(`repos/${a}/${l}/commits/${n}/check-runs`)?.check_runs??[],I=L6(`repos/${a}/${l}/commits/${n}/status`)?.statuses??[],S=tXe(f,I),x=ix(`repos/${a}/${l}/pulls/${t}/comments`),b=x.filter(W=>/via Matilda \/review/.test(W.body??"")),T=new Set;for(let W of x)W.in_reply_to_id&&T.add(W.in_reply_to_id);let R=[];s&&(R=JSON.parse(Xze(s,"utf8")));let Q=new Set(R.map(W=>`${W.path}:${W.line}`)),L=nXe(b,T,Q,n),O=[];d&&O.push("self-PR"),S.class==="any_failure"&&O.push(`CI failing: ${S.failedCheckNames.join(", ")}`),S.class==="all_pending"&&O.push("CI still running");let Y={prNumber:t,commitSha:n,ownerRepo:o,isSelfPr:d,ciStatus:S,existingComments:{total:b.length,byBucket:{stale:L.stale.length,resolved:L.resolved.length,overlap:L.overlap.length,noConflict:L.noConflict.length},overlap:L.overlap,stale:L.stale,resolved:L.resolved,noConflict:L.noConflict},downgradeApprove:d||S.class==="any_failure"||S.class==="all_pending",downgradeRequestChanges:d,downgradeReasons:O,blockOnExistingComments:L.overlap.length>0};zze(r,JSON.stringify(Y,null,2)+`
|
|
284
|
-
`,"utf8"),rt(`Wrote presubmit report to ${r}`)}var Rfe={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 oXe(e)}};p();import{execFileSync as Mfe}from"node:child_process";import{existsSync as kfe,readdirSync as rXe,unlinkSync as sXe}from"node:fs";import{join as iXe}from"node:path";function aXe(e){let t=!1,n=/^pr-(\d+)$/.exec(e);if(n){let s=n[1],i=bv(s);if(kfe(i))try{Mfe("git",["worktree","remove",i,"--force"],{stdio:"pipe"}),rt(`Removed worktree: ${i}`),t=!0}catch(l){Ue(`Failed to remove worktree ${i}: ${l.message}`)}let a=wv(s);if(VL(a))try{Mfe("git",["branch","-D",a],{stdio:"pipe"}),rt(`Deleted ref: ${a}`),t=!0}catch(l){Ue(`Failed to delete branch ${a}: ${l.message}`)}}let o=Ife(e),r=[];try{r=kfe(Mh)?rXe(Mh):[]}catch(s){Ue(`Failed to read ${Mh}: ${s.message}`)}for(let s of r){if(!s.startsWith(o))continue;let i=iXe(Mh,s);try{sXe(i),rt(`Removed temp file: ${i}`),t=!0}catch(a){Ue(`Failed to remove ${i}: ${a.message}`)}}t||rt(`Nothing to clean for target "${e}".`)}var Ffe={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=>{aXe(e.target)}};var Nfe={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(Dfe).command(Sfe).command(bfe).command(Qfe).command(Rfe).command(Ffe).demandCommand(1,"Specify a subcommand: fetch-pr, pr-context, load-rules, deterministic, presubmit, or cleanup.").version(!1),handler:()=>{}};p();p();var H6="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 _fe(e,t=process.env){return e.getApprovalMode()!=="bogan"||e.getSandbox()||t.SANDBOX||lXe(t.MATILDA_CODE_SUPPRESS_BOGAN_WARNING)?null:H6}function lXe(e){return e==="1"||e==="true"}function uXe(){return new Promise(()=>{})}var Lfe={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"]||Ue("matilda serve: --no-http-bridge (native mode) is not yet implemented; falling back to http-bridge."),e.token&&Ue("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)&&(Ue("matilda serve: --mcp-client-budget must be a positive integer."),process.exit(1)),n==="enforce"&&t===void 0&&(Ue("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)&&(Ue("matilda serve: --max-pending-prompts-per-session must be a non-negative integer (0 / Infinity = unlimited)."),process.exit(1)),t!==void 0&&Ue(`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*gT)}, no refusal)`:""));try{let h=on(e.workspace??process.cwd()).merged,f=h.tools?.approvalMode,y=h.tools?.sandbox,I=process.env.SANDBOX,S=process.env.MATILDA_CODE_SUPPRESS_BOGAN_WARNING,x=S==="1"||S==="true";f==="bogan"&&!y&&!I&&!x&&Ue(H6)}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 d=h=>{let f=process.env[h];return f?Number(f):void 0};i=e["rate-limit-prompt"]??d("MATILDA_SERVE_RATE_LIMIT_PROMPT"),a=e["rate-limit-mutation"]??d("MATILDA_SERVE_RATE_LIMIT_MUTATION"),l=e["rate-limit-read"]??d("MATILDA_SERVE_RATE_LIMIT_READ"),c=e["rate-limit-window-ms"]??d("MATILDA_SERVE_RATE_LIMIT_WINDOW_MS");for(let[h,f]of[["--rate-limit-prompt",i],["--rate-limit-mutation",a],["--rate-limit-read",l]])f!==void 0&&(!Number.isFinite(f)||!Number.isInteger(f)||f<=0)&&(Ue(`matilda serve: ${h} must be a positive integer.`),process.exit(1));c!==void 0&&(!Number.isFinite(c)||!Number.isInteger(c)||c<1e3)&&(Ue("matilda serve: --rate-limit-window-ms must be an integer >= 1000."),process.exit(1))}let{runMatildaServe:u}=await import("./chunks/serve-VAU7AZ4D.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(d){Ue(`matilda serve: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}await uXe()}};p();p();p();var Ufe=k(Pfe(),1),AXe=new Intl.Segmenter,dXe=new RegExp("^\\p{Default_Ignorable_Code_Point}$","u");function kn(e,t={}){if(typeof e!="string"||e.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:o=!1}=t;if(o||(e=rr(e)),e.length===0)return 0;let r=0,s={ambiguousAsWide:!n};for(let{segment:i}of AXe.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)&&!dXe.test(i)){if((0,Ufe.default)().test(i)){r+=2;continue}r+=xl(a,s)}}return r}p();wz();import{stripVTControlCharacters as gXe}from"node:util";var Ax=e=>{if(!e)return 0;let t=e.split(`
|
|
284
|
+
`,"utf8"),rt(`Wrote presubmit report to ${r}`)}var Rfe={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 oXe(e)}};p();import{execFileSync as Mfe}from"node:child_process";import{existsSync as kfe,readdirSync as rXe,unlinkSync as sXe}from"node:fs";import{join as iXe}from"node:path";function aXe(e){let t=!1,n=/^pr-(\d+)$/.exec(e);if(n){let s=n[1],i=bv(s);if(kfe(i))try{Mfe("git",["worktree","remove",i,"--force"],{stdio:"pipe"}),rt(`Removed worktree: ${i}`),t=!0}catch(l){Ue(`Failed to remove worktree ${i}: ${l.message}`)}let a=wv(s);if(VL(a))try{Mfe("git",["branch","-D",a],{stdio:"pipe"}),rt(`Deleted ref: ${a}`),t=!0}catch(l){Ue(`Failed to delete branch ${a}: ${l.message}`)}}let o=Ife(e),r=[];try{r=kfe(Mh)?rXe(Mh):[]}catch(s){Ue(`Failed to read ${Mh}: ${s.message}`)}for(let s of r){if(!s.startsWith(o))continue;let i=iXe(Mh,s);try{sXe(i),rt(`Removed temp file: ${i}`),t=!0}catch(a){Ue(`Failed to remove ${i}: ${a.message}`)}}t||rt(`Nothing to clean for target "${e}".`)}var Ffe={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=>{aXe(e.target)}};var Nfe={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(Dfe).command(Sfe).command(bfe).command(Qfe).command(Rfe).command(Ffe).demandCommand(1,"Specify a subcommand: fetch-pr, pr-context, load-rules, deterministic, presubmit, or cleanup.").version(!1),handler:()=>{}};p();p();var H6="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 _fe(e,t=process.env){return e.getApprovalMode()!=="bogan"||e.getSandbox()||t.SANDBOX||lXe(t.MATILDA_CODE_SUPPRESS_BOGAN_WARNING)?null:H6}function lXe(e){return e==="1"||e==="true"}function uXe(){return new Promise(()=>{})}var Lfe={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"]||Ue("matilda serve: --no-http-bridge (native mode) is not yet implemented; falling back to http-bridge."),e.token&&Ue("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)&&(Ue("matilda serve: --mcp-client-budget must be a positive integer."),process.exit(1)),n==="enforce"&&t===void 0&&(Ue("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)&&(Ue("matilda serve: --max-pending-prompts-per-session must be a non-negative integer (0 / Infinity = unlimited)."),process.exit(1)),t!==void 0&&Ue(`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*gT)}, no refusal)`:""));try{let h=on(e.workspace??process.cwd()).merged,f=h.tools?.approvalMode,y=h.tools?.sandbox,I=process.env.SANDBOX,S=process.env.MATILDA_CODE_SUPPRESS_BOGAN_WARNING,x=S==="1"||S==="true";f==="bogan"&&!y&&!I&&!x&&Ue(H6)}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 d=h=>{let f=process.env[h];return f?Number(f):void 0};i=e["rate-limit-prompt"]??d("MATILDA_SERVE_RATE_LIMIT_PROMPT"),a=e["rate-limit-mutation"]??d("MATILDA_SERVE_RATE_LIMIT_MUTATION"),l=e["rate-limit-read"]??d("MATILDA_SERVE_RATE_LIMIT_READ"),c=e["rate-limit-window-ms"]??d("MATILDA_SERVE_RATE_LIMIT_WINDOW_MS");for(let[h,f]of[["--rate-limit-prompt",i],["--rate-limit-mutation",a],["--rate-limit-read",l]])f!==void 0&&(!Number.isFinite(f)||!Number.isInteger(f)||f<=0)&&(Ue(`matilda serve: ${h} must be a positive integer.`),process.exit(1));c!==void 0&&(!Number.isFinite(c)||!Number.isInteger(c)||c<1e3)&&(Ue("matilda serve: --rate-limit-window-ms must be an integer >= 1000."),process.exit(1))}let{runMatildaServe:u}=await import("./chunks/serve-7IPJHK45.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(d){Ue(`matilda serve: ${d instanceof Error?d.message:String(d)}`),process.exit(1)}await uXe()}};p();p();p();var Ufe=k(Pfe(),1),AXe=new Intl.Segmenter,dXe=new RegExp("^\\p{Default_Ignorable_Code_Point}$","u");function kn(e,t={}){if(typeof e!="string"||e.length===0)return 0;let{ambiguousIsNarrow:n=!0,countAnsiEscapeCodes:o=!1}=t;if(o||(e=rr(e)),e.length===0)return 0;let r=0,s={ambiguousAsWide:!n};for(let{segment:i}of AXe.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)&&!dXe.test(i)){if((0,Ufe.default)().test(i)){r+=2;continue}r+=xl(a,s)}}return r}p();wz();import{stripVTControlCharacters as gXe}from"node:util";var Ax=e=>{if(!e)return 0;let t=e.split(`
|
|
285
285
|
`);return Math.max(...t.map(n=>Ka(n)))},Hfe=new Map,Gfe=1e3;function Ro(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<=Gfe){let o=Hfe.get(e);if(o)return o}let n=Array.from(e);return e.length<=Gfe&&Hfe.set(e,n),n}function Et(e){return Ro(e).length}function zt(e,t,n){return Ro(e).slice(t,n).join("")}function dx(e){let t=rr(e),n=gXe(t);return Ro(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 G6=new Map,Ka=e=>{if(/^[\x20-\x7E]*$/.test(e))return e.length;if(G6.has(e))return G6.get(e);let t=kn(e);return G6.set(e,t),t};var W6=bz();function vr(e){if(typeof e=="string")return e.search(W6)===-1?e:(W6.lastIndex=0,e.replace(W6,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=vr(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=vr(r);s!==r&&(t===null&&(t={...e}),t[o]=s)}return t!==null?t:e}var mXe=[{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 Wfe(e,t=200){let n=e;for(let{pattern:o,replacement:r}of mXe)n=n.replace(o,r);return n.length>t?t<=3?n.slice(0,t):n.slice(0,t-3)+"...":n}var fXe=/[\x00-\x1f\x7f-\x9f]/g;function pXe(e){switch(e){case"\b":return"\\b";case" ":return"\\t";case`
|
|
286
286
|
`:return"\\n";case"\f":return"\\f";case"\r":return"\\r";default:return`\\u${e.charCodeAt(0).toString(16).padStart(4,"0")}`}}function gx(e){return vr(e).replace(fXe,pXe)}p();function jfe(){let e=on();return Mt.setRuntimeBaseDir(e.merged.advanced?.runtimeOutputDir,process.cwd()),new Xs(process.cwd())}var ZL=38,e2=16,t2=24,n2=12;function hXe(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 vv(e){let t=e.replace(/[\r\n\t]/g,"");return vr(t).replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g,"")}function Fh(e,t){let n=kn(e);return n>=t?e:e+" ".repeat(t-n)}function Rv(e,t){if(kn(e)<=t)return e;let o=t>3?"...":"",r=t-kn(o),s="",i=0;for(let a of e){if(i+=kn(a),i>r)break;s+=a}return s+o}function CXe(e){if(e.length===0){rt("No sessions found.");return}let t=process.stdout.columns??80,n=Math.max(20,t-ZL-e2-t2-n2-4),o=Fh("SESSION ID",ZL)+" "+Fh("STARTED",e2)+" "+Fh("TITLE",t2)+" "+Fh("BRANCH",n2)+" PROMPT";rt(o);for(let r of e){let s=Rv(vv(String(r.sessionId??"")),ZL),i=Rv(vv(hXe(r.startTime)),e2),a=vv(r.prompt??""),l=Rv(r.customTitle!=null?vv(r.customTitle):a,t2),c=Rv(r.gitBranch!=null?vv(r.gitBranch):"-",n2),u=Rv(a,n);rt(`${Fh(s,ZL)} ${Fh(i,e2)} ${Fh(l,t2)} ${Fh(c,n2)} ${u}`)}}function EXe(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 Yfe(e){return e instanceof Error?e.message:String(e)}async function IXe(e){let t;try{t=jfe()}catch(o){Ue(`Error: failed to initialize session service: ${Yfe(o)}`),process.exit(1);return}let n;try{n=await t.listSessions({size:e.limit??20})}catch(o){Ue(`Error: failed to list sessions: ${Yfe(o)}`),process.exit(1);return}if(e.json){for(let o of n.items)rt(JSON.stringify(EXe(o)));n.items.length>0&&n.hasMore&&Ue(`Note: ${n.items.length} sessions shown, more available. Use --limit to show more.`)}else CXe(n.items),n.items.length>0&&n.hasMore&&rt(`Showing ${n.items.length} sessions. Use --limit to show more.`)}var qfe={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 IXe(e)}};var Jfe={command:"sessions",describe:"Manage Matilda sessions",builder:e=>e.command(qfe).demandCommand(1,"You need at least one command before continuing.").version(!1),handler:()=>{}};p();p();import*as Mv from"node:fs";import*as Nh from"node:path";import{execFileSync as yXe,spawnSync as DXe}from"node:child_process";import BXe from"node:readline/promises";import{stdin as SXe,stdout as xXe}from"node:process";function fx(e,t,n=5e3){return yXe("git",t,{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:n}).trim()}function $fe(e){let t=Mv.statSync(e).isDirectory()?e:Nh.dirname(e);for(;;){if(Mv.existsSync(Nh.join(t,".git"))&&Mv.existsSync(Nh.join(t,"package.json")))return t;let n=Nh.dirname(t);if(n===t)return null;t=n}}function Vfe(){let e=process.argv[1];if(e)try{let t=$fe(Nh.resolve(e));if(t)return t}catch{}try{return $fe(process.cwd())}catch{return null}}function j6(e=Vfe()){if(!e||process.env.DEV==="true")return null;let t=fx(e,["rev-parse","--abbrev-ref","HEAD"]);if(!t||t==="HEAD")return null;fx(e,["fetch","--quiet","origin",t],3e3);let n=fx(e,["rev-parse","HEAD"]),o=fx(e,["rev-parse",`origin/${t}`]);return!n||!o||n===o?null:{root:e,branch:t,local:n,remote:o}}function mx(e,t,n){if(DXe(t,n,{cwd:e,stdio:"inherit",shell:process.platform==="win32"}).status!==0)throw new Error(`${t} ${n.join(" ")} failed.`)}function bXe(e){return/(^|\/)NOTICES\.txt$/.test(e)||/(^|\/)settings\.schema\.json$/.test(e)}function wXe(e){return e.split(`
|
|
287
287
|
`).map(t=>t.slice(2).trim()).filter(Boolean).filter(t=>!bXe(t))}function Y6(e=Vfe()){if(!e)throw new Error("Could not find a Matilda Code source checkout to update.");let t=fx(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=fx(e,["status","--porcelain"]),o=wXe(n);if(o.length>0)throw new Error(`Matilda Code checkout has local changes; refusing to self-update:
|
|
@@ -378,7 +378,7 @@ ${a.join(`
|
|
|
378
378
|
`)}${l}`:i}function Ltt(e){if(e.length===0)return[];let{addWidth:t,remWidth:n,statColumnWidth:o}=pq(e),r=[];for(let s of e){let i=gx(s.filename);if(s.isBinary){let u=s.isUntracked?` ${m("(binary, new)")}`:s.isDeleted?` ${m("(binary, deleted)")}`:` ${m("(binary)")}`;r.push(` ${Ott("~",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?` ${m("(new, partial)")}`:` ${m("(new)")}`:s.isDeleted&&(c=` ${m("(deleted)")}`),r.push(` ${a} ${l} ${i}${c}`)}return r}function Ott(e,t){return e.length>=t?e:`${e}${" ".repeat(t-e.length)}`}var JCe={name:"diff",get description(){return m("Show working-tree change stats versus HEAD")},kind:"built-in",supportedModes:["interactive","non_interactive","acp"],action:ktt};p();var $Ce={name:"editor",get description(){return m("set external editor preference")},kind:"built-in",supportedModes:["interactive"],action:()=>({type:"dialog",dialog:"editor"})};p();import*as Ld from"node:fs/promises";import $v from"node:path";p();p();import{randomUUID as Htt}from"node:crypto";p();p();p();var dc=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 Wh=class extends dc{async emitStopHookLoop(t,n,o){let r=cA(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=dc.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(dc.toEpochMs(n),o);await this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:t},...r?{_meta:r}:{}})}async emitAgentMessage(t,n,o){let r=this.buildChunkMeta(dc.toEpochMs(n),o);await this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:t},...r?{_meta:r}:{}})}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 Tx=class extends dc{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 N2(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 Utt={read:"read",edit:"edit",delete:"delete",move:"move",search:"search",execute:"execute",think:"think",fetch:"fetch",agent:"other",other:"other"},jh=class e extends dc{planEmitter;constructor(t){super(t),this.planEmitter=new Tx(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}:{},...dc.toEpochMs(t.timestamp)!=null&&{timestamp:dc.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.subagentMeta,provenance:r.provenance,...r.serverId?{serverId:r.serverId}:{},...dc.toEpochMs(t.timestamp)!=null&&{timestamp:dc.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===Kt.TODO_WRITE}isExitPlanModeTool(t){return t===Kt.EXIT_PLAN_MODE}isEnterPlanModeTool(t){return t===Kt.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":Utt[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:N2(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 Yh=class{ctx;messageEmitter;toolCallEmitter;constructor(t){this.ctx=t,this.messageEmitter=new Wh(t),this.toolCallEmitter=new jh(t)}async replay(t){for(let n of t)await this.replayRecord(n)}async replayRecord(t){switch(this.setActiveRecordId(t.uuid,t.timestamp),t.type){case"user":if(t.subtype==="notification"||t.subtype==="cron"){let n=t.systemPayload?.displayText;n&&await this.messageEmitter.emitUserMessage(n,t.timestamp);break}if(t.subtype==="mid_turn_user_message"){let n=t.systemPayload?.displayText;n?await this.messageEmitter.emitUserMessage(n,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),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){for(let r of t.parts??[]){if("text"in r&&r.text){let s=r.thought??!1;await this.messageEmitter.emitMessage(r.text,n,s,o)}if("functionCall"in r&&r.functionCall){let s=r.functionCall.name??"",i=r.functionCall.id??`${s}-${Date.now()}`;await this.toolCallEmitter.emitStart({toolName:s,callId:i,args:r.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,`
|
|
379
379
|
`),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 Gtt(e){if(e.message?.parts){for(let t of e.message.parts)if("functionResponse"in t&&t.functionResponse?.name)return t.functionResponse.name}}function Wtt(e){if(e.message?.parts){for(let t of e.message.parts)if("functionResponse"in t&&t.functionResponse?.id)return t.functionResponse.id}}function jtt(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 Ytt(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=jtt(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 qtt(e){let t=Ytt(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=Gtt(r),i=r.toolCallResult.callId??Wtt(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 d=n.get(s)??0;l=u[d],n.set(s,d+1)}}let{resultDisplay:c}=r.toolCallResult;if(c&&typeof c=="object"&&"fileName"in c){let u=c,d="originalContent"in u,h="newContent"in u,f;if(typeof u.fileName=="string"?f=l?.file_path||u.fileName:f="unknown",d||h){if(o.filesWritten++,o.writtenFilePaths.add(f),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??""),I=String(u.newContent??""),S=y.split(`
|
|
380
380
|
`).filter(b=>b.length>0).length,x=I.split(`
|
|
381
|
-
`).filter(b=>b.length>0).length;o.linesAdded+=x,o.linesRemoved+=S}}}}return o}function Jtt(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 $tt(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=Jtt(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 Vtt(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-
|
|
381
|
+
`).filter(b=>b.length>0).length;o.linesAdded+=x,o.linesRemoved+=S}}}}return o}function Jtt(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 $tt(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=Jtt(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 Vtt(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-6MF6HV7Q.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?.(),d=r.filter(y=>y.type==="user").length,h=qtt(r),f=$tt(r);return{sessionId:n,startTime:o,exportTime:new Date().toISOString(),cwd:i,gitRepo:l,gitBranch:a,model:c,channel:u,promptCount:d,contextUsagePercent:f.contextUsagePercent,contextWindowSize:f.contextWindowSize,totalTokens:f.totalTokens,filesWritten:h.writtenFilePaths.size,linesAdded:h.linesAdded,linesRemoved:h.linesRemoved,uniqueFiles:Array.from(h.writtenFilePaths)}}var hq=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??Htt()}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(`
|
|
382
382
|
`)}}];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 Cq(e,t){let n=new hq(e.sessionId,t);await new Yh(n).replay(e.messages),n.flushMessages();let r=n.getMessages(),s=await Vtt(e,t);return{sessionId:e.sessionId,startTime:e.startTime,messages:r,metadata:s}}p();function Eq(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=ztt(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||Ktt(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 Ktt(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 ztt(e,t){let n=e.toolCallResult,o=Xtt(e);if(o===Kt.TODO_WRITE)return null;let r=n?.callId??e.uuid,s=Ztt(e),{kind:i,title:a,locations:l}=ent(t,o,s??n?.args),c=ont(s??n?.args),u=nnt(n?.resultDisplay)??rnt(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 Xtt(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 Ztt(e){if(e.message?.parts){for(let t of e.message.parts)if("functionCall"in t&&t.functionCall?.args)return t.functionCall.args}}function ent(e,t,n){let o=e.getToolRegistry?.(),r=t?o?.getTool?.(t):void 0,s=r?.displayName??t??"tool_call",i,a=tnt(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 tnt(e,t){return t&&(t===Kt.EXIT_PLAN_MODE||t===Kt.ENTER_PLAN_MODE)?"switch_mode":t&&t===Kt.TODO_WRITE?"todowrite":e&&new Set(["read","edit","delete","move","search","execute","think","fetch","other"]).has(e)?e:"other"}function nnt(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:N2(t)}}]:[{type:"diff",path:t.fileName,oldText:t.originalContent??"",newText:t.newContent}]:null}function ont(e){if(typeof e=="string"||typeof e=="object"&&e!==null)return e}function rnt(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 yq(e){let t=[],n=e.metadata;if(t.push(`# Chat Session Export
|
|
383
383
|
`),t.push(`- **Session ID**: \`${Ou(e.sessionId)}\``),t.push(`- **Start Time**: ${Ou(e.startTime)}`),t.push(`- **Exported**: ${Ou(n?.exportTime??new Date().toISOString())}`),t.push(""),n?.cwd&&t.push(`- **Working Directory**: \`${Ou(n.cwd)}\``),n?.gitRepo&&t.push(`- **Git Repository**: ${Ou(n.gitRepo)}`),n?.gitBranch&&t.push(`- **Git Branch**: \`${Ou(n.gitBranch)}\``),t.push(""),n?.model&&t.push(`- **Model**: ${Ou(n.model)}`),n?.channel&&t.push(`- **Channel**: ${Ou(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(`- \`${Ou(o)}\``);t.push("</details>")}t.push(`
|
|
384
384
|
---
|
|
@@ -690,7 +690,7 @@ ${ee}
|
|
|
690
690
|
|
|
691
691
|
`),sendMessageType:Qe};d++,e.getMaxSessionTurns()>=0&&d>e.getMaxSessionTurns()&&await cW(e);let Nt=[{role:"user",parts:[{text:dt.modelText}]}],Jt=!0,un;for(iB(i.begin(dT(dt.sendMessageType)));;){let no=[],io=Date.now(),nn=y.sendMessageStream(Nt[0]?.parts||[],I.signal,o,{type:Jt?dt.sendMessageType:"toolResult",modelOverride:un,...Jt&&{notificationDisplayText:dt.displayText}});Jt=!1,a.startAssistantMessage();for await(let Vt of nn)if(I.signal.aborted&&(a.finalizeAssistantMessage(),Q(b),Y(),await x()),a.processEvent(Vt),Vt.type==="tool_call_request"&&no.push(Vt.value),Vt.type==="loop_detected"&&OIe(e,Vt.value?.loopType),l==="text"&&Vt.type==="error"){let Ds=Mg(Vt.value.error,e.getContentGeneratorConfig()?.authType);throw process.stderr.write(`${Ds}
|
|
692
692
|
`),new uf(Ds)}if(a.finalizeAssistantMessage(),h+=Date.now()-io,no.length>0){let Vt=await ve(no,Ds=>{un=Ds});if(le!==void 0)return;Nt=[{role:"user",parts:Vt}]}else break}},re=null,ae=()=>{if(re)return re;let Qe=(async()=>{for(;b.length>0;){if(le!==void 0)return;await Ce()}})();return re=Qe,Qe.finally(()=>{re===Qe&&(re=null)}),Qe},fe=e.isCronEnabled()?e.getCronScheduler():null;for(fe&&(await fe.enableDurable(e.getSessionId()).catch(Qe=>{Mf.warn(`Durable cron init failed \u2014 persistent tasks will not fire in this run: ${Qe}`)}),await new Promise((Qe,nt)=>{let Le=()=>{fe.stop(),Qe()};if(I.signal.aborted){Le();return}I.signal.addEventListener("abort",Le,{once:!0});let dt=()=>{if(le!==void 0){I.signal.removeEventListener("abort",Le),fe.stop(),Qe();return}fe.sessionSize===0&&!re&&(I.signal.removeEventListener("abort",Le),fe.stop(),Qe())},Nt=Jt=>{I.signal.removeEventListener("abort",Le),fe.stop(),nt(Jt)};fe.start(Jt=>{let un=Jt.prompt.slice(0,40);b.push({displayText:`Cron: ${un}`,modelText:Jt.prompt,sendMessageType:"cron"}),ae().then(dt,Nt)}),dt()}));I.signal.aborted&&(xe.abortAll(),Q(b),Y(),await x()),L=!1,await ae(),!(le!==void 0||!xe.hasUnfinalizedTasks()&&b.length===0);)await new Promise(Qe=>setTimeout(Qe,100));let Ie=e.getGeminiClient().consumePendingMemoryTaskPromises();Ie.length>0&&await Promise.allSettled(Ie),Y();let Ve=Ir.getMetrics(),Be=gR(Ve),Ne=l==="json"?Ir.getMetrics():void 0;if(le!==void 0)return ye();if(e.getJsonSchema()){let Qe=me.trim(),nt=Qe?` Output preview (${me.length}${me.length>=ue?"+":""} chars): ${JSON.stringify(Qe)}.`:"",Le=`Model produced plain text instead of calling the structured_output tool as required by --json-schema after ${d} turn(s).`+nt;return a.emitResult({isError:!0,durationMs:Date.now()-f,apiDurationMs:h,numTurns:d,errorMessage:Le,usage:Be,stats:Ne}),1}return a.emitResult({isError:!1,durationMs:Date.now()-f,apiDurationMs:h,numTurns:d,usage:Be,stats:Ne}),0}}}catch(M){try{a.finalizeAssistantMessage()}catch{}Q(b),Y();let H=S.getExceeded(),q=H?H.message:M instanceof Error?M.message:String(M),X=Ir.getMetrics(),ne=gR(X),de=l==="json"?Ir.getMetrics():void 0,Te=M instanceof uf;if(!(l==="text"&&Te))try{a.emitResult({isError:!0,durationMs:Date.now()-f,apiDurationMs:h,numTurns:d,errorMessage:q,usage:ne,stats:de})}catch(Xe){Mf.error(`Failed to emit terminal result envelope: ${Xe instanceof Error?Xe.message:String(Xe)}`)}H&&await uW(e,H),await Zoe(M,e)}finally{e.onTeamManagerChange(null,J),N&&(U(N),N=null),S.stop();let M=e.getBackgroundTaskRegistry();M.setNotificationCallback(void 0),M.setRegisterCallback(void 0);let H=e.getMonitorRegistry();r.captureMonitorNotifications!==!1&&(O||H.abortAll({notify:!1}),H.setNotificationCallback(void 0)),r.captureMonitorRegistrations!==!1&&H.setRegisterCallback(void 0),process.stdout.removeListener("error",P),process.removeListener("SIGINT",j),process.removeListener("SIGTERM",j),WK()&&await jK()}return 1})}p();import*as gO from"node:path";var GIe=He("WORKTREE_STARTUP"),Zq="HEAD";async function WIe(e,t){if(e===void 0)return null;let n=e.trim(),o=process.cwd(),r=new Gp(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=gO.resolve(i),l=a===o?r:new Gp(a),c=Gp.parsePRReference(n),u=c!==null,d;if(c!==null)d=`pr-${c}`;else if(n.length===0)d=Gp.generateAutoSlug();else{let L=Gp.validateUserWorktreeSlug(n);if(L)return{ok:!1,error:`--worktree: ${L}`};d=n}let[h,f]=await Promise.all([l.getCurrentBranch().catch(()=>{}),l.getCurrentCommitHash().catch(()=>"")]),y=h&&h!==Zq?h:void 0,I=l.getUserWorktreePath(d),S=Nz(d),x=null;try{x=await l.getRegisteredWorktreeBranch(I)}catch{x=null}if(x!==null){if(x.branch!==S)return{ok:!1,error:`--worktree: ${I} is already a git worktree, but its branch is ${x.branch} (expected ${S}). Refusing to re-attach. Resolve the conflict manually (e.g. \`git worktree remove ${I}\`).`};let L=gO.resolve(I);try{process.chdir(L)}catch(O){return{ok:!1,error:`--worktree: failed to chdir into ${L} (${O instanceof Error?O.message:String(O)}).`}}return GIe.debug(`setupStartupWorktree: re-attached to existing worktree at ${L} (branch=${x.branch})`),{ok:!0,context:{worktreePath:L,slug:d,branch:x.branch,repoRoot:a,originalBranch:y??Zq,originalHeadCommit:x.headCommit,isPullRequest:u,wasReattached:!0}}}let b=null;if(c!==null){let L=await l.fetchPullRequestRef(c);if(!L.success)return{ok:!1,error:`--worktree: ${L.error}`};if(b=await l.resolveRef("FETCH_HEAD"),b===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?b:y,R=await l.createUserWorktree(d,T,{symlinkDirectories:t?.symlinkDirectories});if(!R.success||!R.worktree)return{ok:!1,error:`--worktree: ${R.error??"failed to create worktree."}`};let Q=gO.resolve(R.worktree.path);try{process.chdir(Q)}catch(L){return{ok:!1,error:`--worktree: created worktree at ${Q} but failed to chdir into it (${L instanceof Error?L.message:String(L)}). Run \`cd ${Q}\` manually.`}}return{ok:!0,context:{worktreePath:Q,slug:d,branch:R.worktree.branch,repoRoot:a,originalBranch:y??Zq,originalHeadCommit:u?b:f,isPullRequest:u,wasReattached:!1}}}async function jIe(e,t){let n=e.getSessionId(),o=e.getSessionService().getWorktreeSessionPath(n),r=!1,s,i=null;try{i=await _F(o)}catch(a){GIe.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 _z(t.worktreePath,n).catch(()=>{}),await aX(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 e5(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}
|
|
693
|
-
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 ort}from"node:readline/promises";import rrt from"node:process";var jx=class extends Error{},mO=class{input;constructor(t=rrt.stdin){this.input=t}async*read(){let t=ort({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 jx("Parsed value is not an object");if(!("type"in n)||typeof n.type!="string")throw new jx('Missing required "type" field');return n}catch(n){if(n instanceof jx)throw n;let o=n instanceof Error?n.message:String(n);throw new jx(`Failed to parse stream-json line: ${o}`)}}};p();var fO=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 srt}from"node:crypto";var YIe=3e4,zh=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}`)},YIe);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=YIe,o){if(this.context.inputClosed)throw new Error("Input closed");if(o?.aborted)throw new Error("Request aborted");let r=srt();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 d={type:"control_request",request_id:r,request:t};try{this.context.streamJson.send(d)}catch(h){o&&o.removeEventListener("abort",a),this.registry.deregisterOutgoingRequest(r),i(h)}})}cleanup(){}};var gc=He("SYSTEM_CONTROLLER"),irt=6e5,pO=class extends zh{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-7XW5T2FM.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 gc.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<=irt&&(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 RE(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),gc.debug(`[SystemController] Added ${i} SDK MCP servers to config`)}catch(a){gc.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),gc.debug(`[SystemController] Added ${i} external MCP servers to config`)}catch(a){gc.error("[SystemController] Failed to add external MCP servers:",a)}}if(t.agents&&Array.isArray(t.agents))try{this.context.config.setSessionSubagents(t.agents),gc.debug(`[SystemController] Added ${t.agents.length} session subagents to config`)}catch(s){gc.error("[SystemController] Failed to add session subagents:",s)}let r=this.buildControlCapabilities();return gc.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 gc.warn(`[SystemController] Ignoring invalid MCP server config for '${t}'`),null;let o=this.normalizeAuthProviderType(n.authProviderType),r=this.normalizeOAuthConfig(n.oauth);return new RE(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:gc.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&&gc.debug("[SystemController] Interrupt signal triggered"),gc.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),gc.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 gc.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 Ux(this.context.config,t,"non_interactive");return t.aborted?[]:n.map(o=>o.name).sort()}catch(n){return t.aborted?[]:(gc.error("[SystemController] Failed to load slash commands:",n),[])}}};p();var art=6e4,hO=class extends zh{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??art,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 lrt=3e4,CO=class extends zh{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},lrt,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 ZI=He("CONTROL_DISPATCHER"),EO=class{context;systemController;permissionController;sdkMcpController;pendingIncomingRequests=new Map;pendingOutgoingRequests=new Map;abortHandler=null;constructor(t){this.context=t,this.systemController=new pO(t,this,"SystemController"),this.permissionController=new hO(t,this,"PermissionController"),this.sdkMcpController=new CO(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){ZI.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"),ZI.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"))}ZI.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&&ZI.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(){ZI.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){ZI.warn(`[ControlDispatcher] Timeout waiting for ${this.pendingIncomingRequests.size} pending incoming requests`);break}await new Promise(r=>setTimeout(r,t))}this.pendingIncomingRequests.size===0&&ZI.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 IO=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 t5(e){return e&&typeof e=="object"&&e.type==="user"&&"message"in e}function qIe(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 JIe(e){return e&&typeof e=="object"&&e.type==="system"&&"subtype"in e&&"uuid"in e&&"session_id"in e}function $Ie(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 VIe(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 n5(e){return e&&typeof e=="object"&&e.type==="control_request"&&"request_id"in e&&"request"in e}function KIe(e){return e&&typeof e=="object"&&e.type==="control_response"&&"response"in e}function zIe(e){return e&&typeof e=="object"&&e.type==="control_cancel_request"&&"request_id"in e}var Jr=He("NON_INTERACTIVE_SESSION"),o5=class{userMessageQueue=[];monitorStartedQueue=[];monitorQueue=[];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=DT()){this.config=t,this.settings=o,this.sessionId=t.getSessionId(),this.abortController=new AbortController,this.initialPrompt=n??null,this.inputReader=new mO,this.outputAdapter=new Ud(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){Jr.debug("[Session] Initializing config");try{Ca("config_initialize_start"),await this.config.initialize(t),Ca("config_initialize_end"),await this.config.waitForMcpReady();let n=typeof this.config.getFailedMcpServerNames=="function"?this.config.getFailedMcpServerNames():[];n.length>0&&process.stderr.write(`Warning: MCP server(s) failed to start: ${n.join(", ")}. Continuing with built-in tools and any servers that did connect.
|
|
693
|
+
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 ort}from"node:readline/promises";import rrt from"node:process";var jx=class extends Error{},mO=class{input;constructor(t=rrt.stdin){this.input=t}async*read(){let t=ort({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 jx("Parsed value is not an object");if(!("type"in n)||typeof n.type!="string")throw new jx('Missing required "type" field');return n}catch(n){if(n instanceof jx)throw n;let o=n instanceof Error?n.message:String(n);throw new jx(`Failed to parse stream-json line: ${o}`)}}};p();var fO=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 srt}from"node:crypto";var YIe=3e4,zh=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}`)},YIe);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=YIe,o){if(this.context.inputClosed)throw new Error("Input closed");if(o?.aborted)throw new Error("Request aborted");let r=srt();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 d={type:"control_request",request_id:r,request:t};try{this.context.streamJson.send(d)}catch(h){o&&o.removeEventListener("abort",a),this.registry.deregisterOutgoingRequest(r),i(h)}})}cleanup(){}};var gc=He("SYSTEM_CONTROLLER"),irt=6e5,pO=class extends zh{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-HGBI6TH7.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 gc.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<=irt&&(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 RE(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),gc.debug(`[SystemController] Added ${i} SDK MCP servers to config`)}catch(a){gc.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),gc.debug(`[SystemController] Added ${i} external MCP servers to config`)}catch(a){gc.error("[SystemController] Failed to add external MCP servers:",a)}}if(t.agents&&Array.isArray(t.agents))try{this.context.config.setSessionSubagents(t.agents),gc.debug(`[SystemController] Added ${t.agents.length} session subagents to config`)}catch(s){gc.error("[SystemController] Failed to add session subagents:",s)}let r=this.buildControlCapabilities();return gc.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 gc.warn(`[SystemController] Ignoring invalid MCP server config for '${t}'`),null;let o=this.normalizeAuthProviderType(n.authProviderType),r=this.normalizeOAuthConfig(n.oauth);return new RE(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:gc.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&&gc.debug("[SystemController] Interrupt signal triggered"),gc.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),gc.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 gc.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 Ux(this.context.config,t,"non_interactive");return t.aborted?[]:n.map(o=>o.name).sort()}catch(n){return t.aborted?[]:(gc.error("[SystemController] Failed to load slash commands:",n),[])}}};p();var art=6e4,hO=class extends zh{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??art,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 lrt=3e4,CO=class extends zh{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},lrt,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 ZI=He("CONTROL_DISPATCHER"),EO=class{context;systemController;permissionController;sdkMcpController;pendingIncomingRequests=new Map;pendingOutgoingRequests=new Map;abortHandler=null;constructor(t){this.context=t,this.systemController=new pO(t,this,"SystemController"),this.permissionController=new hO(t,this,"PermissionController"),this.sdkMcpController=new CO(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){ZI.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"),ZI.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"))}ZI.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&&ZI.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(){ZI.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){ZI.warn(`[ControlDispatcher] Timeout waiting for ${this.pendingIncomingRequests.size} pending incoming requests`);break}await new Promise(r=>setTimeout(r,t))}this.pendingIncomingRequests.size===0&&ZI.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 IO=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 t5(e){return e&&typeof e=="object"&&e.type==="user"&&"message"in e}function qIe(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 JIe(e){return e&&typeof e=="object"&&e.type==="system"&&"subtype"in e&&"uuid"in e&&"session_id"in e}function $Ie(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 VIe(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 n5(e){return e&&typeof e=="object"&&e.type==="control_request"&&"request_id"in e&&"request"in e}function KIe(e){return e&&typeof e=="object"&&e.type==="control_response"&&"response"in e}function zIe(e){return e&&typeof e=="object"&&e.type==="control_cancel_request"&&"request_id"in e}var Jr=He("NON_INTERACTIVE_SESSION"),o5=class{userMessageQueue=[];monitorStartedQueue=[];monitorQueue=[];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=DT()){this.config=t,this.settings=o,this.sessionId=t.getSessionId(),this.abortController=new AbortController,this.initialPrompt=n??null,this.inputReader=new mO,this.outputAdapter=new Ud(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){Jr.debug("[Session] Initializing config");try{Ca("config_initialize_start"),await this.config.initialize(t),Ca("config_initialize_end"),await this.config.waitForMcpReady();let n=typeof this.config.getFailedMcpServerNames=="function"?this.config.getFailedMcpServerNames():[];n.length>0&&process.stderr.write(`Warning: MCP server(s) failed to start: ${n.join(", ")}. Continuing with built-in tools and any servers that did connect.
|
|
694
694
|
`),BB(this.config.getSessionId()),this.configInitialized=!0,this.registerMonitorRegistrations(),this.registerMonitorNotifications()}catch(n){throw Jr.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&&(Jr.debug("[Session] Initialization complete"),this.initializationResolve(),this.initializationResolve=null,this.initializationReject=null)}failInitialization(t){this.initializationReject&&(Jr.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 fO({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 EO(this.controlContext),this.controlService=new IO(this.controlContext,this.dispatcher))}getDispatcher(){return this.controlSystemEnabled!==!0?null:(this.dispatcher||this.ensureControlSystem(),this.dispatcher)}handleFirstMessage(t){if(n5(t)){let n=t;if(this.controlSystemEnabled=!0,this.ensureControlSystem(),n.request.subtype==="initialize"){this.initializeSdkMode(n);return}Jr.debug("[Session] Ignoring non-initialize control request during initialization");return}if(t5(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){Jr.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){Jr.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){Jr.warn("[Session] Control system not enabled");return}n.dispatch(t).catch(o=>{Jr.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=crt(t);if(!n){Jr.debug("[Session] No text content in user message");return}await this.waitForInitialization();let o=this.getNextPromptId();try{await mR(this.config,this.settings,n,o,{abortController:this.abortController,adapter:this.outputAdapter,controlService:this.controlService??void 0,captureMonitorNotifications:!1,captureMonitorRegistrations:!1})}catch(r){Jr.error("[Session] Query execution error:",r)}}async processMonitorNotificationBatch(t){await this.waitForInitialization();for(let s of t)this.outputAdapter.emitUserMessage([{text:s.displayText}]),this.outputAdapter.emitSystemMessage("task_notification",s.sdkNotification);let n=t.map(s=>s.modelText).join(`
|
|
695
695
|
|
|
696
696
|
`),o=t.map(s=>s.displayText).join("; "),r=this.getNextPromptId();await mR(this.config,this.settings,n,r,{abortController:this.abortController,adapter:this.outputAdapter,controlService:this.controlService??void 0,sendMessageType:"notification",notificationDisplayText:o,captureMonitorNotifications:!1,captureMonitorRegistrations:!1})}async processPendingWork(){if(!(this.isShuttingDown||this.abortController.signal.aborted))for(;(this.userMessageQueue.length>0||this.monitorStartedQueue.length>0||this.monitorQueue.length>0)&&!this.isShuttingDown&&!this.abortController.signal.aborted;){if(this.userMessageQueue.length>0){let o=this.userMessageQueue.shift();try{await this.processUserMessage(o)}catch(r){Jr.error("[Session] Error processing user message:",r),this.emitErrorResult(r)}continue}let t=this.monitorStartedQueue.shift();if(t){this.outputAdapter.emitSystemMessage("task_started",t);continue}if(this.monitorQueue.length===0)continue;let n=this.monitorQueue.splice(0);try{await this.processMonitorNotificationBatch(n)}catch(o){Jr.error("[Session] Error processing monitor notification batch:",o),this.emitErrorResult(o)}}}enqueueUserMessage(t){this.userMessageQueue.push(t),this.ensureProcessingStarted()}enqueueMonitorStarted(t){this.monitorStartedQueue.push(t),this.ensureProcessingStarted()}enqueueMonitorNotification(t){this.monitorQueue.push(t),this.ensureProcessingStarted()}ensureProcessingStarted(){this.processingPromise||(this.processingPromise=this.processPendingWork().finally(()=>{this.processingPromise=null,(this.userMessageQueue.length>0||this.monitorStartedQueue.length>0||this.monitorQueue.length>0)&&!this.isShuttingDown&&!this.abortController.signal.aborted&&this.ensureProcessingStarted()}))}emitErrorResult(t,n=0,o=0,r=0){let s=t instanceof Error?t.message:String(t);this.outputAdapter.emitResult({isError:!0,errorMessage:s,durationMs:o,apiDurationMs:r,numTurns:n,usage:void 0})}handleInterrupt(){Jr.info("[Session] Interrupt requested"),this.abortController.abort()}setupSignalHandlers(){this.shutdownHandler=()=>{Jr.info("[Session] Shutdown signal received"),this.isShuttingDown=!0,this.abortController.abort()},process.on("SIGINT",this.shutdownHandler),process.on("SIGTERM",this.shutdownHandler)}async waitForAllPendingWork(){try{await this.waitForInitialization()}catch(t){Jr.error("[Session] Initialization error during shutdown:",t)}if(this.dispatcher){let t=this.dispatcher.getPendingIncomingRequestCount();t>0&&Jr.debug(`[Session] Waiting for ${t} pending control request handlers`),await this.dispatcher.waitForPendingIncomingRequests()}for(;this.processingPromise;){Jr.debug("[Session] Waiting for user message processing");try{await this.processingPromise}catch(t){Jr.error("[Session] Error in user message processing:",t)}}}async shutdown(){Jr.debug("[Session] Shutting down"),this.isShuttingDown=!0,this.abortTaskRegistries(),this.stopMonitorCallbacks(),await this.waitForAllPendingWork(),this.abortTaskRegistries(),this.finishShutdown()}async drainAndShutdown(){Jr.debug("[Session] Draining pending work before shutdown"),this.abortTaskRegistries(),this.stopMonitorCallbacks(),await this.waitForAllPendingWork(),this.abortTaskRegistries(),this.finishShutdown()}abortTaskRegistries(){this.config.getMonitorRegistry().abortAll({notify:!1}),this.config.getBackgroundShellRegistry().abortAll(),this.config.getBackgroundTaskRegistry().abortAll()}finishShutdown(){this.dispatcher?.shutdown(),this.cleanupSignalHandlers()}stopMonitorCallbacks(){if(!this.monitorNotificationsRegistered&&!this.monitorRegistrationsRegistered)return;let t=this.config.getMonitorRegistry();this.monitorNotificationsRegistered&&(t.setNotificationCallback(void 0),this.monitorNotificationsRegistered=!1),this.monitorRegistrationsRegistered&&(t.setRegisterCallback(void 0),this.monitorRegistrationsRegistered=!1)}cleanupSignalHandlers(){this.shutdownHandler&&(process.removeListener("SIGINT",this.shutdownHandler),process.removeListener("SIGTERM",this.shutdownHandler),this.shutdownHandler=null)}async run(){try{Jr.info("[Session] Starting session",this.sessionId),this.initialPrompt!==null&&this.handleFirstMessage(this.initialPrompt);try{for await(let t of this.inputReader.read()){if(this.abortController.signal.aborted)break;if(KIe(t)){this.handleControlResponse(t);continue}if(this.controlSystemEnabled===null){this.handleFirstMessage(t);continue}if(n5(t)?this.handleControlRequestAsync(t):zIe(t)?this.handleControlCancel(t):t5(t)?this.enqueueUserMessage(t):!qIe(t)&&!JIe(t)&&!$Ie(t)&&!VIe(t)&&Jr.warn("[Session] Unknown message type:",JSON.stringify(t,null,2)),this.isShuttingDown)break}}catch(t){throw Jr.error("[Session] Stream reading error:",t),t}this.dispatcher&&this.dispatcher.markInputClosed(),await this.drainAndShutdown()}catch(t){throw Jr.error("[Session] Error:",t),await this.shutdown(),t}finally{this.cleanupSignalHandlers()}}};function crt(e){let t=e.message.content;if(typeof t=="string")return t;if(Array.isArray(t)){let n=t.map(o=>!o||typeof o!="object"?"":"type"in o&&o.type==="text"&&"text"in o?typeof o.text=="string"?o.text:"":JSON.stringify(o)).filter(o=>o.length>0);return n.length>0?n.join(`
|
|
@@ -819,7 +819,7 @@ ${X}`),T&&gb.existsSync(T)){let Te=gb.readFileSync(T,"utf8").trim();Te&&Te!==x&&
|
|
|
819
819
|
|
|
820
820
|
${X}`)}let de={...j,status:ne,resultDisplay:X};e({type:"tool_group",tools:[de],isUserInitiated:!0},y),Amt(s,h,X)}).catch(H=>{t(null);let q=H instanceof Error?H.message:String(H);e({type:"error",text:`An unexpected error occurred: ${q}`},y)}).finally(()=>{f.removeEventListener("abort",N),T&&gb.existsSync(T)&&gb.unlinkSync(T),u(null),i(!1),L()})}catch(G){t(null);let U=G instanceof Error?G.message:String(G);e({type:"error",text:`An unexpected error occurred: ${U}`},y),T&&gb.existsSync(T)&&gb.unlinkSync(T),u(null),i(!1),L()}},Q=new Promise(L=>{R(L)});return n(Q),!0},[r,o,e,t,n,s,i,l,a]),activeShellPtyId:c}};p();var HQe=(e,t)=>{let n=0,o=0;for(;o<e.length;){let r=e.indexOf("```",o);if(r===-1||r>=t)break;n++,o=r+3}return n%2===1},dmt=(e,t)=>{if(!HQe(e,t))return-1;let n=0;for(;n<t;){let o=e.indexOf("```",n);if(o===-1||o>=t)break;let r=e.indexOf("```",o+3);if(o<t&&(r===-1||t<r+3))return o;if(r===-1)break;n=r+3}return-1},GQe=e=>{let t=dmt(e,e.length);if(t!==-1)return t;let n=e.length;for(;n>=0;){let o=e.lastIndexOf(`
|
|
821
821
|
|
|
822
|
-
`,n);if(o===-1)break;let r=o+2;if(!HQe(e,r))return r;n=o-1}return e.length};p();var YU=k(pe(),1);var hM=e=>{let[t,n]=YU.default.useState(e),o=YU.default.useRef(e),r=YU.default.useCallback(s=>{let i;typeof s=="function"?i=s(o.current):i=s,n(i),o.current=i},[]);return[t,o,r]};p();var Qm=k(pe(),1);import*as WQe from"node:path";var gmt=He("REACT_TOOL_SCHEDULER");function jQe(e,t,n,o){let[r,s]=(0,Qm.useState)([]),i=(0,Qm.useCallback)((h,f)=>{s(y=>y.map(I=>I.request.callId===h&&I.status==="executing"?{...I,liveOutput:f}:I))},[]),a=(0,Qm.useCallback)(async h=>{await e(h)},[e]),l=(0,Qm.useCallback)(h=>{s(f=>h.map(y=>{let I=f.find(x=>x.request.callId===y.request.callId),S=I?.responseSubmittedToGemini??!1;return y.status==="executing"?{...y,responseSubmittedToGemini:S,liveOutput:I?.liveOutput}:{...y,responseSubmittedToGemini:S,liveOutput:void 0,pid:void 0,promoteAbortController:void 0}}))},[s]),c=(0,Qm.useMemo)(()=>new kz({config:t,chatRecordingService:t.getChatRecordingService(),outputUpdateHandler:i,onAllToolCallsComplete:a,onToolCallsUpdate:l,getPreferredEditor:n,onEditorClose:o}),[t,i,a,l,n,o]),u=(0,Qm.useCallback)((h,f)=>{c.schedule(h,f)},[c]),d=(0,Qm.useCallback)(h=>{s(f=>f.map(y=>h.includes(y.request.callId)?{...y,responseSubmittedToGemini:!0}:y))},[]);return[r,u,d]}function mb(e){switch(e){case"validating":return"Executing";case"awaiting_approval":return"Confirming";case"executing":return"Executing";case"success":return"Success";case"cancelled":return"Canceled";case"error":return"Error";case"scheduled":return"Pending";default:{let t=e;return gmt.warn(`Unknown core status encountered: ${t}`),"Error"}}}function mmt(e,t,n){let o=new Set(["write_file","edit"]),r=new Set(["read_file"]),s=t?.file_path;if(!s)return;let i=WQe.resolve(s);if(ZK(i,n)){if(o.has(e))return"write";if(r.has(e))return"read"}}function PJ(e,t){let o=(Array.isArray(e)?e:[e]).map(r=>{let s,i,a=!1;r.status==="error"?(s=r.tool===void 0?r.request.name:r.tool.displayName,i=JSON.stringify(r.request.args)):(s=r.tool.displayName,i=r.invocation.getDescription(),a=r.tool.isOutputMarkdown);let l={callId:r.request.callId,name:s,description:i,renderOutputAsMarkdown:a,isMemoryOp:t&&r.status!=="error"?mmt(r.request.name,r.request.args,t):void 0};switch(r.status){case"success":return{...l,status:mb(r.status),resultDisplay:r.response.resultDisplay,confirmationDetails:void 0};case"error":return{...l,status:mb(r.status),resultDisplay:r.response.resultDisplay,confirmationDetails:void 0};case"cancelled":return{...l,status:mb(r.status),resultDisplay:r.response.resultDisplay,confirmationDetails:void 0};case"awaiting_approval":return{...l,status:mb(r.status),resultDisplay:void 0,confirmationDetails:r.confirmationDetails};case"executing":return{...l,status:mb(r.status),resultDisplay:r.liveOutput??void 0,confirmationDetails:void 0,ptyId:r.pid,executionStartTime:r.executionStartTime};case"validating":case"scheduled":return{...l,status:mb(r.status),resultDisplay:void 0,confirmationDetails:void 0};default:return{callId:r.request.callId,name:"Unknown Tool",description:"Encountered an unknown tool call state.",status:"Error",resultDisplay:"Unknown tool call state",confirmationDetails:void 0,renderOutputAsMarkdown:!1}}});return{type:"tool_group",tools:o,memoryWriteCount:o.filter(r=>r.isMemoryOp==="write").length||void 0,memoryReadCount:o.filter(r=>r.isMemoryOp==="read").length||void 0}}import{promises as YQe}from"node:fs";import qQe from"node:path";p();var qU=k(pe(),1);var UJ=(0,qU.createContext)(null);function JU(){return(0,qU.useContext)(UJ)}import fmt from"node:process";var tp=He("GEMINI_STREAM");function pmt(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if((n.type==="gemini"||n.type==="gemini_content")&&typeof n.text=="string"&&n.text.trim().length>0)return n.text}}function HJ(e){return e.replace(/^(?:[ \t]*\r?\n)+/,"")}function hmt(e){if(!e)return"";let t=Array.isArray(e)?e:[e],n=[];for(let o of t)if("functionResponse"in o&&o.functionResponse){let r=o.functionResponse.response;r!==void 0&&n.push(r)}else"text"in o&&typeof o.text=="string"&&n.push(o.text);return n.length===0?"":n.length===1?n[0]:n}function $U(e){let t=e.status,n=e.message?.toLowerCase()??"";return t===429||n.includes("rate limit")?"rate_limit":t===401||n.includes("unauthorized")?"authentication_failed":t===402||t===403||n.includes("billing")||n.includes("quota")?"billing_error":t===400||n.includes("invalid")?"invalid_request":t!==void 0&&t>=500?"server_error":n.includes("max_tokens")||n.includes("token limit")?"max_output_tokens":"unknown"}function Cmt(e){let t=[],n=!1;if(typeof e=="string")return{hasImages:!1,hasUnsupportedFormats:!1,unsupportedMimeTypes:[]};let o=Array.isArray(e)?e:[e];for(let r of o){if(typeof r=="string")continue;let s;"inlineData"in r&&r.inlineData?.mimeType?.startsWith("image/")&&(n=!0,s=r.inlineData.mimeType),"fileData"in r&&r.fileData?.mimeType?.startsWith("image/")&&(n=!0,s=r.fileData.mimeType),s&&!E7(s)&&t.push(s)}return{hasImages:n,hasUnsupportedFormats:t.length>0,unsupportedMimeTypes:t}}var JQe=new Set([Kt.EDIT,"replace",Kt.WRITE_FILE,Kt.NOTEBOOK_EDIT]),Emt=12,$Qe=16,Imt=1,ymt=20,Dmt=160;function Bmt(e){if(e<=0)return 0;if(e<=6)return e;let t=Math.max(1,Math.ceil(Dmt/$Qe)),n=Math.ceil(e/t);return Math.min(ymt,Math.max(Imt,n))}function Smt(e){let t=e?.merged?.ui?.showCitations;return t!==void 0?t:!0}var VQe=(e,t,n,o,r,s,i,a,l,c,u,d,h,f,y,I,S,x,b,T)=>{let[R,Q]=(0,St.useState)(null),L=(0,St.useRef)(null),O=(0,St.useRef)(new Set),Y=(0,St.useRef)(!1),W=(0,St.useRef)(!1),P=(0,St.useRef)(new Up),j=(0,St.useRef)(null),_=(0,St.useRef)(null),N=(0,St.useRef)(!1),G=(0,St.useRef)(!1),U=JU(),[J,M]=(0,St.useState)(!1),H=(0,St.useRef)(0),[q,X]=(0,St.useState)(null),[ne,de]=(0,St.useState)(null),Te=(0,St.useRef)(t);(0,St.useLayoutEffect)(()=>{Te.current=t},[t]);let xe=(0,St.useRef)(new Set),[Xe,$,z]=hM(null),[te,le,me]=hM(null),ue=(0,St.useRef)(null),[ye,ve,we]=hM(null),[ee,se,Me]=hM(null),ge=(0,St.useRef)(null),ie=(0,St.useRef)(new Set),Ce=(0,St.useRef)(null),re=(0,St.useRef)(void 0),ae=(0,St.useRef)(0),[fe,Ie]=(0,St.useState)(!1),{startNewPrompt:Ve,getPromptCount:Be,stats:Ne}=Ra(),Qe=o.storage,[nt,Le,dt]=jQe(async he=>{if(he.length>0){let ke=o.getProjectRoot(),et=PJ(he,ke);n(et,Date.now()),await ma(he)}},o,l,f),Nt=(0,St.useMemo)(()=>nt.length?PJ(nt,o.getProjectRoot()):void 0,[nt,o]),Jt=(0,St.useMemo)(()=>{let he=nt?.find(ke=>ke.status==="executing"&&ke.request.name==="run_shell_command");if(he)return he.pid},[nt]),un=(0,St.useRef)(!1),[no,io]=(0,St.useState)(null),nn=(0,St.useCallback)(()=>{ge.current&&(clearInterval(ge.current),ge.current=null)},[]),Vt=(0,St.useCallback)(()=>{nn(),Ds.current=null,we(null),Me(null)},[we,Me,nn]),Ds=(0,St.useRef)(null),nr=(0,St.useCallback)(he=>{nn(),Ds.current=he.skipDelay;let ke=Date.now(),{message:et,attempt:ot,maxRetries:Dt,delayMs:Tt}=he,V=et??m("Rate limit exceeded. Please wait and try again."),K=()=>{let Ae=Date.now()-ke,Ee=Math.max(0,Tt-Ae),be=Math.ceil(Ee/1e3),We=`Retrying in ${be}s\u2026 (attempt ${ot}/${Dt})`;we({type:"error",text:V,hint:We}),Me({type:"retry_countdown",text:m("Retrying in {{seconds}} seconds\u2026 (attempt {{attempt}}/{{maxRetries}})",{seconds:String(be),attempt:String(ot),maxRetries:String(Dt)})}),Ee<=0&&nn()};K(),ge.current=setInterval(K,1e3)},[we,Me,nn]);(0,St.useEffect)(()=>()=>nn(),[nn]);let uo=(0,St.useCallback)(async he=>{M(!0),await he,M(!1)},[]),{handleShellCommand:Ge,activeShellPtyId:fn}=UQe(n,z,uo,s,o,e,I,S,x),Bo=fn||Jt;(0,St.useEffect)(()=>{Bo||I(!1)},[Bo,I]);let Pt=(0,St.useMemo)(()=>nt.some(he=>he.status==="awaiting_approval")?"waiting_for_confirmation":nt.some(he=>{if(he.status!=="executing")return!1;let ke=he.liveOutput;return typeof ke=="object"&&ke!==null&&"type"in ke&&ke.type==="task_execution"&&"pendingConfirmation"in ke&&ke.pendingConfirmation!=null})?"waiting_for_confirmation":J||nt.some(he=>he.status==="executing"||he.status==="scheduled"||he.status==="validating"||(he.status==="success"||he.status==="error"||he.status==="cancelled")&&!he.responseSubmittedToGemini)?"responding":"idle",[J,nt]);(0,St.useEffect)(()=>{if(o.getApprovalMode()==="bogan"&&Pt==="idle"){let he=t.findLastIndex(et=>et.type==="user"),ke=he===-1?0:t.length-he;ke>0&&lT(o,new cT(o.getApprovalMode(),ke))}},[Pt,o,t]);let $n=(0,St.useCallback)(he=>{if(Pt!=="responding"||Y.current)return;let ke=he?.reason==="steer";for(let Tt of O.current)Tt();let et=$.current;Y.current=!0,W.current=!1,L.current?.abort();for(let Tt of xe.current)Tt.abort();xe.current.clear(),o.getArenaAgentClient()?.reportCancelled();let ot=o.getSessionId()+"########"+Be(),Dt=new t7(o.getModel(),ot,o.getContentGeneratorConfig()?.authType);qK(o,Dt),$.current&&n($.current,Date.now()),n({type:"info",text:ke?m("Steering with queued message\u2026"):m("Request cancelled.")},Date.now()),z(null),Vt();try{y({pendingItem:et,lastTurnUserItem:_.current,turnProducedMeaningfulContent:N.current,preserveQueue:ke})}finally{M(!1),I(!1)}},[Pt,n,z,y,$,I,Vt,o,Be]),Un=(0,St.useCallback)(async(he,ke,et,ot,Dt)=>{if(Y.current)return{queryToSend:null,shouldProceed:!1};if(typeof he=="string"&&he.trim().length===0)return{queryToSend:null,shouldProceed:!1};_.current=null;let Tt=null;if(typeof he=="string"){let V=he.trim();if(Dt==="notification")return s(`Received notification (${V.length} chars)`),{queryToSend:V,shouldProceed:!0};if(Dt==="teammate")return s(`Received teammate message (${V.length} chars)`),{queryToSend:V,shouldProceed:!0};s(`Received user query (${V.length} chars)`),await T?.logMessage("user",V);let K=Xa(V)?await i(V):!1;if(K)switch(K.type){case"schedule_tool":{let{toolName:Ae,toolArgs:Ee}=K,be={callId:`${Ae}-${Date.now()}-${Math.random().toString(16).slice(2)}`,name:Ae,args:Ee,isClientInitiated:!0,prompt_id:ot};return Le([be],et),{queryToSend:null,shouldProceed:!1}}case"submit_prompt":return Tt=K.content,Ce.current=K.onComplete??null,{queryToSend:Tt,shouldProceed:!0};case"handled":return{queryToSend:null,shouldProceed:!1};default:{let Ae=K;throw new Error(`Unhandled slash command result type: ${Ae}`)}}if(a&&Ge(V,et))return{queryToSend:null,shouldProceed:!1};if(Tt=V,Dt!=="cron"){let Ae=n({type:"user",text:V,promptId:ot},ke);_.current={id:Ae,text:V}}if(nhe(V)){let Ae=await dO({query:V,config:o,onDebugMessage:s,messageId:ke,signal:et,addItem:n});if(!Ae.shouldProceed)return{queryToSend:null,shouldProceed:!1};Tt=Ae.processedQuery}}else Tt=he;return Tt===null?(s("Query processing resulted in null, not sending to Gemini."),{queryToSend:null,shouldProceed:!1}):{queryToSend:Tt,shouldProceed:!0}},[o,n,s,Ge,i,T,a,Le]),ts=(0,St.useCallback)((he,ke,et)=>{if(Y.current)return"";ae.current+=he.length,Ie(!0),N.current=!0;let ot=ke+he;if($.current?.type!=="gemini"&&$.current?.type!=="gemini_content"){if(ot.trim().length===0)return ot;$.current&&n($.current,et),z({type:"gemini",text:""}),ot=HJ(ot)}let Dt=GQe(ot);if(Dt===ot.length)z(Tt=>({type:Tt?.type,text:ot}));else{let Tt=ot.substring(0,Dt),V=ot.substring(Dt);n({type:$.current?.type,text:Tt},et),z({type:"gemini_content",text:V}),ot=V}return ot},[n,$,z]),Wn=(0,St.useCallback)(he=>{X(ke=>{if(!ke)return tp.isEnabled()&&tp.debug(`[THOUGHT_MERGE] New thought: subjectLength=${he.subject?.length??0}, description length=${he.description?.length??0}`),he;let et=he.subject||ke.subject,ot=`${ke.description??""}${he.description??""}`;return tp.isEnabled()&&tp.debug(`[THOUGHT_MERGE] Accumulating thought: prev length=${ke.description?.length??0}, incoming length=${he.description?.length??0}, total length=${ot.length}`),{subject:et,description:ot}})},[X]),jn=(0,St.useCallback)((he,ke)=>{if(Y.current)return"";let et=he.description??"";if(!et)return ke;let ot=ke+et;if(ot.trim().length===0)return ot;let Dt=ke.trim().length===0,Tt=Dt?HJ(ot):et;return Dt&&(ue.current=Date.now()),Wn({...he,description:Tt}),me({type:"gemini_thought",text:HJ(ot),durationMs:ue.current?Date.now()-ue.current:0}),Dt?Tt:ot},[Wn,me]),fr=(0,St.useCallback)(he=>{if(le.current){let ke={...le.current};ke.type==="gemini_thought"&&ue.current&&(ke.durationMs=Date.now()-ue.current),n(ke,he)}me(null),ue.current=null},[n,le,me]),Ao=(0,St.useCallback)(he=>{if(!Y.current){if(G.current=!1,fr(he),$.current){if($.current.type==="tool_group"){let ke=$.current.tools.map(ot=>ot.status==="Pending"||ot.status==="Confirming"||ot.status==="Executing"?{...ot,status:"Canceled"}:ot),et={...$.current,tools:ke};n(et,he)}else n($.current,he);z(null)}n({type:"info",text:"User cancelled the request."},he),Vt(),M(!1),X(null)}},[n,fr,$,z,X,Vt]),pr=(0,St.useCallback)((he,ke)=>{G.current=!0,fr(ke),$.current&&(n($.current,ke),z(null));let et=ge.current!==null;Vt();let ot=Mg(he.error,o.getContentGeneratorConfig()?.authType);if(!et){let Tt=m("Press Ctrl+Y to retry");we({type:"error",text:ot,hint:Tt})}X(null);let Dt=$U(he.error);o.getHookSystem()?.fireStopFailureEvent(Dt,he.error.message,ot).catch(Tt=>{tp.warn(`StopFailure hook failed: ${Tt}`)})},[n,fr,$,z,we,o,X,Vt]),Ur=(0,St.useCallback)((he,ke)=>{Smt(r)&&($.current&&(n($.current,ke),z(null)),n({type:"info",text:he},ke))},[n,$,z,r]),Hr=(0,St.useCallback)((he,ke)=>{let et=he.value.reason;if(!et)return;let Dt={[Hi.FINISH_REASON_UNSPECIFIED]:void 0,[Hi.STOP]:void 0,[Hi.MAX_TOKENS]:'Output hop limit \u2014 cut mid-jump. Say "continue" to keep going.',[Hi.SAFETY]:"Response stopped due to safety reasons.",[Hi.RECITATION]:"Response stopped due to recitation policy.",[Hi.LANGUAGE]:"Response stopped due to unsupported language.",[Hi.BLOCKLIST]:"Response stopped due to forbidden terms.",[Hi.PROHIBITED_CONTENT]:"Response stopped due to prohibited content.",[Hi.SPII]:"Response stopped due to sensitive personally identifiable information.",[Hi.OTHER]:"Response stopped for other reasons.",[Hi.MALFORMED_FUNCTION_CALL]:"Response stopped due to malformed function call.",[Hi.IMAGE_SAFETY]:"Response stopped due to image safety violations.",[Hi.IMAGE_PROHIBITED_CONTENT]:"Response stopped due to image prohibited content.",[Hi.IMAGE_RECITATION]:"Response stopped due to image recitation policy.",[Hi.IMAGE_OTHER]:"Response stopped due to other image-related reasons.",[Hi.NO_IMAGE]:"Response stopped due to no image.",[Hi.UNEXPECTED_TOOL_CALL]:"Response stopped due to unexpected tool call."}[et];if(Dt){let Tt=et===Hi.MAX_TOKENS?"\u{1F998} ":"\u26A0\uFE0F ";n({type:"info",text:`${Tt}${Dt}`},ke)}ge.current&&Vt()},[n,Vt]),pi=(0,St.useCallback)((he,ke)=>{$.current&&(n($.current,ke),z(null));let ot=`IMPORTANT: This conversation ${he?.triggerReason==="image_overflow"?`accumulated enough tool screenshots to trigger compaction for ${o.getModel()}`:`approached the input token limit for ${o.getModel()}`}. A compressed context will be sent for future messages (compressed from: ${he?.originalTokenCount??"unknown"} to ${he?.newTokenCount??"unknown"} tokens).`;de(Dt=>({key:(Dt?.key??0)+1,text:ot}))},[n,o,$,z,de]),Vs=(0,St.useCallback)(()=>n({type:"info",text:`The session has reached the maximum number of turns: ${o.getMaxSessionTurns()}. Please update this limit in your setting.json file.`},Date.now()),[n,o]),Ni=(0,St.useCallback)(he=>n({type:"error",text:`\u{1F6AB} Session token limit exceeded: ${he.currentTokens.toLocaleString()} tokens > ${he.limit.toLocaleString()} limit.
|
|
822
|
+
`,n);if(o===-1)break;let r=o+2;if(!HQe(e,r))return r;n=o-1}return e.length};p();var YU=k(pe(),1);var hM=e=>{let[t,n]=YU.default.useState(e),o=YU.default.useRef(e),r=YU.default.useCallback(s=>{let i;typeof s=="function"?i=s(o.current):i=s,n(i),o.current=i},[]);return[t,o,r]};p();var Qm=k(pe(),1);import*as WQe from"node:path";var gmt=He("REACT_TOOL_SCHEDULER");function jQe(e,t,n,o){let[r,s]=(0,Qm.useState)([]),i=(0,Qm.useCallback)((h,f)=>{s(y=>y.map(I=>I.request.callId===h&&I.status==="executing"?{...I,liveOutput:f}:I))},[]),a=(0,Qm.useCallback)(async h=>{await e(h)},[e]),l=(0,Qm.useCallback)(h=>{s(f=>h.map(y=>{let I=f.find(x=>x.request.callId===y.request.callId),S=I?.responseSubmittedToGemini??!1;return y.status==="executing"?{...y,responseSubmittedToGemini:S,liveOutput:I?.liveOutput}:{...y,responseSubmittedToGemini:S,liveOutput:void 0,pid:void 0,promoteAbortController:void 0}}))},[s]),c=(0,Qm.useMemo)(()=>new kz({config:t,chatRecordingService:t.getChatRecordingService(),outputUpdateHandler:i,onAllToolCallsComplete:a,onToolCallsUpdate:l,getPreferredEditor:n,onEditorClose:o}),[t,i,a,l,n,o]),u=(0,Qm.useCallback)((h,f)=>{c.schedule(h,f)},[c]),d=(0,Qm.useCallback)(h=>{s(f=>f.map(y=>h.includes(y.request.callId)?{...y,responseSubmittedToGemini:!0}:y))},[]);return[r,u,d]}function mb(e){switch(e){case"validating":return"Executing";case"awaiting_approval":return"Confirming";case"executing":return"Executing";case"success":return"Success";case"cancelled":return"Canceled";case"error":return"Error";case"scheduled":return"Pending";default:{let t=e;return gmt.warn(`Unknown core status encountered: ${t}`),"Error"}}}function mmt(e,t,n){let o=new Set(["write_file","edit"]),r=new Set(["read_file"]),s=t?.file_path;if(!s)return;let i=WQe.resolve(s);if(ZK(i,n)){if(o.has(e))return"write";if(r.has(e))return"read"}}function PJ(e,t){let o=(Array.isArray(e)?e:[e]).map(r=>{let s,i,a=!1;r.status==="error"?(s=r.tool===void 0?r.request.name:r.tool.displayName,i=JSON.stringify(r.request.args)):(s=r.tool.displayName,i=r.invocation.getDescription(),a=r.tool.isOutputMarkdown);let l={callId:r.request.callId,name:s,description:i,renderOutputAsMarkdown:a,isMemoryOp:t&&r.status!=="error"?mmt(r.request.name,r.request.args,t):void 0};switch(r.status){case"success":return{...l,status:mb(r.status),resultDisplay:r.response.resultDisplay,confirmationDetails:void 0};case"error":return{...l,status:mb(r.status),resultDisplay:r.response.resultDisplay,confirmationDetails:void 0};case"cancelled":return{...l,status:mb(r.status),resultDisplay:r.response.resultDisplay,confirmationDetails:void 0};case"awaiting_approval":return{...l,status:mb(r.status),resultDisplay:void 0,confirmationDetails:r.confirmationDetails};case"executing":return{...l,status:mb(r.status),resultDisplay:r.liveOutput??void 0,confirmationDetails:void 0,ptyId:r.pid,executionStartTime:r.executionStartTime};case"validating":case"scheduled":return{...l,status:mb(r.status),resultDisplay:void 0,confirmationDetails:void 0};default:return{callId:r.request.callId,name:"Unknown Tool",description:"Encountered an unknown tool call state.",status:"Error",resultDisplay:"Unknown tool call state",confirmationDetails:void 0,renderOutputAsMarkdown:!1}}});return{type:"tool_group",tools:o,memoryWriteCount:o.filter(r=>r.isMemoryOp==="write").length||void 0,memoryReadCount:o.filter(r=>r.isMemoryOp==="read").length||void 0}}import{promises as YQe}from"node:fs";import qQe from"node:path";p();var qU=k(pe(),1);var UJ=(0,qU.createContext)(null);function JU(){return(0,qU.useContext)(UJ)}import fmt from"node:process";var tp=He("GEMINI_STREAM");function pmt(e){for(let t=e.length-1;t>=0;t--){let n=e[t];if((n.type==="gemini"||n.type==="gemini_content")&&typeof n.text=="string"&&n.text.trim().length>0)return n.text}}function HJ(e){return e.replace(/^(?:[ \t]*\r?\n)+/,"")}function hmt(e){if(!e)return"";let t=Array.isArray(e)?e:[e],n=[];for(let o of t)if("functionResponse"in o&&o.functionResponse){let r=o.functionResponse.response;r!==void 0&&n.push(r)}else"text"in o&&typeof o.text=="string"&&n.push(o.text);return n.length===0?"":n.length===1?n[0]:n}function $U(e){let t=e.status,n=e.message?.toLowerCase()??"";return t===429||n.includes("rate limit")?"rate_limit":t===401||n.includes("unauthorized")?"authentication_failed":t===402||t===403||n.includes("billing")||n.includes("quota")?"billing_error":t===400||n.includes("invalid")?"invalid_request":t!==void 0&&t>=500?"server_error":n.includes("max_tokens")||n.includes("token limit")?"max_output_tokens":"unknown"}function Cmt(e){let t=[],n=!1;if(typeof e=="string")return{hasImages:!1,hasUnsupportedFormats:!1,unsupportedMimeTypes:[]};let o=Array.isArray(e)?e:[e];for(let r of o){if(typeof r=="string")continue;let s;"inlineData"in r&&r.inlineData?.mimeType?.startsWith("image/")&&(n=!0,s=r.inlineData.mimeType),"fileData"in r&&r.fileData?.mimeType?.startsWith("image/")&&(n=!0,s=r.fileData.mimeType),s&&!E7(s)&&t.push(s)}return{hasImages:n,hasUnsupportedFormats:t.length>0,unsupportedMimeTypes:t}}var JQe=new Set([Kt.EDIT,"replace",Kt.WRITE_FILE,Kt.NOTEBOOK_EDIT]),Emt=12,$Qe=16,Imt=1,ymt=20,Dmt=160;function Bmt(e){if(e<=0)return 0;if(e<=6)return e;let t=Math.max(1,Math.ceil(Dmt/$Qe)),n=Math.ceil(e/t);return Math.min(ymt,Math.max(Imt,n))}function Smt(e){let t=e?.merged?.ui?.showCitations;return t!==void 0?t:!0}var VQe=(e,t,n,o,r,s,i,a,l,c,u,d,h,f,y,I,S,x,b,T)=>{let[R,Q]=(0,St.useState)(null),L=(0,St.useRef)(null),O=(0,St.useRef)(new Set),Y=(0,St.useRef)(!1),W=(0,St.useRef)(!1),P=(0,St.useRef)(new Up),j=(0,St.useRef)(null),_=(0,St.useRef)(null),N=(0,St.useRef)(!1),G=(0,St.useRef)(!1),U=JU(),[J,M]=(0,St.useState)(!1),H=(0,St.useRef)(0),[q,X]=(0,St.useState)(null),[ne,de]=(0,St.useState)(null),Te=(0,St.useRef)(t);(0,St.useLayoutEffect)(()=>{Te.current=t},[t]);let xe=(0,St.useRef)(new Set),[Xe,$,z]=hM(null),[te,le,me]=hM(null),ue=(0,St.useRef)(null),[ye,ve,we]=hM(null),[ee,se,Me]=hM(null),ge=(0,St.useRef)(null),ie=(0,St.useRef)(new Set),Ce=(0,St.useRef)(null),re=(0,St.useRef)(void 0),ae=(0,St.useRef)(0),[fe,Ie]=(0,St.useState)(!1),{startNewPrompt:Ve,getPromptCount:Be,stats:Ne}=Ra(),Qe=o.storage,[nt,Le,dt]=jQe(async he=>{if(he.length>0){let ke=o.getProjectRoot(),et=PJ(he,ke);n(et,Date.now()),await ma(he)}},o,l,f),Nt=(0,St.useMemo)(()=>nt.length?PJ(nt,o.getProjectRoot()):void 0,[nt,o]),Jt=(0,St.useMemo)(()=>{let he=nt?.find(ke=>ke.status==="executing"&&ke.request.name==="run_shell_command");if(he)return he.pid},[nt]),un=(0,St.useRef)(!1),[no,io]=(0,St.useState)(null),nn=(0,St.useCallback)(()=>{ge.current&&(clearInterval(ge.current),ge.current=null)},[]),Vt=(0,St.useCallback)(()=>{nn(),Ds.current=null,we(null),Me(null)},[we,Me,nn]),Ds=(0,St.useRef)(null),nr=(0,St.useCallback)(he=>{nn(),Ds.current=he.skipDelay;let ke=Date.now(),{message:et,attempt:ot,maxRetries:Dt,delayMs:Tt}=he,V=et??m("Rate limit exceeded. Please wait and try again."),K=()=>{let Ae=Date.now()-ke,Ee=Math.max(0,Tt-Ae),be=Math.ceil(Ee/1e3),We=`Retrying in ${be}s\u2026 (attempt ${ot}/${Dt})`;we({type:"error",text:V,hint:We}),Me({type:"retry_countdown",text:m("Retrying in {{seconds}} seconds\u2026 (attempt {{attempt}}/{{maxRetries}})",{seconds:String(be),attempt:String(ot),maxRetries:String(Dt)})}),Ee<=0&&nn()};K(),ge.current=setInterval(K,1e3)},[we,Me,nn]);(0,St.useEffect)(()=>()=>nn(),[nn]);let uo=(0,St.useCallback)(async he=>{M(!0),await he,M(!1)},[]),{handleShellCommand:Ge,activeShellPtyId:fn}=UQe(n,z,uo,s,o,e,I,S,x),Bo=fn||Jt;(0,St.useEffect)(()=>{Bo||I(!1)},[Bo,I]);let Pt=(0,St.useMemo)(()=>nt.some(he=>he.status==="awaiting_approval")?"waiting_for_confirmation":nt.some(he=>{if(he.status!=="executing")return!1;let ke=he.liveOutput;return typeof ke=="object"&&ke!==null&&"type"in ke&&ke.type==="task_execution"&&"pendingConfirmation"in ke&&ke.pendingConfirmation!=null})?"waiting_for_confirmation":J||nt.some(he=>he.status==="executing"||he.status==="scheduled"||he.status==="validating"||(he.status==="success"||he.status==="error"||he.status==="cancelled")&&!he.responseSubmittedToGemini)?"responding":"idle",[J,nt]);(0,St.useEffect)(()=>{if(o.getApprovalMode()==="bogan"&&Pt==="idle"){let he=t.findLastIndex(et=>et.type==="user"),ke=he===-1?0:t.length-he;ke>0&&lT(o,new cT(o.getApprovalMode(),ke))}},[Pt,o,t]);let $n=(0,St.useCallback)(he=>{if(Pt!=="responding"||Y.current)return;let ke=he?.reason==="steer";for(let Tt of O.current)Tt();let et=$.current;Y.current=!0,W.current=!1,L.current?.abort();for(let Tt of xe.current)Tt.abort();xe.current.clear(),o.getArenaAgentClient()?.reportCancelled();let ot=o.getSessionId()+"########"+Be(),Dt=new t7(o.getModel(),ot,o.getContentGeneratorConfig()?.authType);qK(o,Dt),$.current&&n($.current,Date.now()),n({type:"info",text:ke?m("Steering with queued message\u2026"):m("Request cancelled.")},Date.now()),z(null),Vt();try{y({pendingItem:et,lastTurnUserItem:_.current,turnProducedMeaningfulContent:N.current,preserveQueue:ke})}finally{M(!1),I(!1)}},[Pt,n,z,y,$,I,Vt,o,Be]),Un=(0,St.useCallback)(async(he,ke,et,ot,Dt)=>{if(Y.current)return{queryToSend:null,shouldProceed:!1};if(typeof he=="string"&&he.trim().length===0)return{queryToSend:null,shouldProceed:!1};_.current=null;let Tt=null;if(typeof he=="string"){let V=he.trim();if(Dt==="notification")return s(`Received notification (${V.length} chars)`),{queryToSend:V,shouldProceed:!0};if(Dt==="teammate")return s(`Received teammate message (${V.length} chars)`),{queryToSend:V,shouldProceed:!0};s(`Received user query (${V.length} chars)`),await T?.logMessage("user",V);let K=Xa(V)?await i(V):!1;if(K)switch(K.type){case"schedule_tool":{let{toolName:Ae,toolArgs:Ee}=K,be={callId:`${Ae}-${Date.now()}-${Math.random().toString(16).slice(2)}`,name:Ae,args:Ee,isClientInitiated:!0,prompt_id:ot};return Le([be],et),{queryToSend:null,shouldProceed:!1}}case"submit_prompt":return Tt=K.content,Ce.current=K.onComplete??null,{queryToSend:Tt,shouldProceed:!0};case"handled":return{queryToSend:null,shouldProceed:!1};default:{let Ae=K;throw new Error(`Unhandled slash command result type: ${Ae}`)}}if(a&&Ge(V,et))return{queryToSend:null,shouldProceed:!1};if(Tt=V,Dt!=="cron"){let Ae=n({type:"user",text:V,promptId:ot},ke);_.current={id:Ae,text:V}}if(nhe(V)){let Ae=await dO({query:V,config:o,onDebugMessage:s,messageId:ke,signal:et,addItem:n});if(!Ae.shouldProceed)return{queryToSend:null,shouldProceed:!1};Tt=Ae.processedQuery}}else Tt=he;return Tt===null?(s("Query processing resulted in null, not sending to Gemini."),{queryToSend:null,shouldProceed:!1}):{queryToSend:Tt,shouldProceed:!0}},[o,n,s,Ge,i,T,a,Le]),ts=(0,St.useCallback)((he,ke,et)=>{if(Y.current)return"";ae.current+=he.length,Ie(!0),N.current=!0;let ot=ke+he;if($.current?.type!=="gemini"&&$.current?.type!=="gemini_content"){if(ot.trim().length===0)return ot;$.current&&n($.current,et),z({type:"gemini",text:""}),ot=HJ(ot)}let Dt=GQe(ot);if(Dt===ot.length)z(Tt=>({type:Tt?.type,text:ot}));else{let Tt=ot.substring(0,Dt),V=ot.substring(Dt);n({type:$.current?.type,text:Tt},et),z({type:"gemini_content",text:V}),ot=V}return ot},[n,$,z]),Wn=(0,St.useCallback)(he=>{X(ke=>{if(!ke)return tp.isEnabled()&&tp.debug(`[THOUGHT_MERGE] New thought: subjectLength=${he.subject?.length??0}, description length=${he.description?.length??0}`),he;let et=he.subject||ke.subject,ot=`${ke.description??""}${he.description??""}`;return tp.isEnabled()&&tp.debug(`[THOUGHT_MERGE] Accumulating thought: prev length=${ke.description?.length??0}, incoming length=${he.description?.length??0}, total length=${ot.length}`),{subject:et,description:ot}})},[X]),jn=(0,St.useCallback)((he,ke)=>{if(Y.current)return"";let et=he.description??"";if(!et)return ke;let ot=ke+et;if(ot.trim().length===0)return ot;let Dt=ke.trim().length===0,Tt=Dt?HJ(ot):et;return Dt&&(ue.current=Date.now()),Wn({...he,description:Tt}),me({type:"gemini_thought",text:HJ(ot),durationMs:ue.current?Date.now()-ue.current:0}),Dt?Tt:ot},[Wn,me]),fr=(0,St.useCallback)(he=>{if(le.current){let ke={...le.current};ke.type==="gemini_thought"&&ue.current&&(ke.durationMs=Date.now()-ue.current),n(ke,he)}me(null),ue.current=null},[n,le,me]),Ao=(0,St.useCallback)(he=>{if(!Y.current){if(G.current=!1,fr(he),$.current){if($.current.type==="tool_group"){let ke=$.current.tools.map(ot=>ot.status==="Pending"||ot.status==="Confirming"||ot.status==="Executing"?{...ot,status:"Canceled"}:ot),et={...$.current,tools:ke};n(et,he)}else n($.current,he);z(null)}n({type:"info",text:"User cancelled the request."},he),Vt(),M(!1),X(null)}},[n,fr,$,z,X,Vt]),pr=(0,St.useCallback)((he,ke)=>{G.current=!0,fr(ke),$.current&&(n($.current,ke),z(null));let et=ge.current!==null;Vt();let ot=Mg(he.error,o.getContentGeneratorConfig()?.authType);if(!et){let Tt=m("Press Ctrl+Y to retry");we({type:"error",text:ot,hint:Tt})}X(null);let Dt=$U(he.error);o.getHookSystem()?.fireStopFailureEvent(Dt,he.error.message,ot).catch(Tt=>{tp.warn(`StopFailure hook failed: ${Tt}`)})},[n,fr,$,z,we,o,X,Vt]),Ur=(0,St.useCallback)((he,ke)=>{Smt(r)&&($.current&&(n($.current,ke),z(null)),n({type:"info",text:he},ke))},[n,$,z,r]),Hr=(0,St.useCallback)((he,ke)=>{let et=he.value.reason;if(!et)return;let Dt={[Hi.FINISH_REASON_UNSPECIFIED]:void 0,[Hi.STOP]:void 0,[Hi.MAX_TOKENS]:'Response cut short (token budget or incomplete tool call). Say "continue" \u2014 prefer a short tool call without a long report first.',[Hi.SAFETY]:"Response stopped due to safety reasons.",[Hi.RECITATION]:"Response stopped due to recitation policy.",[Hi.LANGUAGE]:"Response stopped due to unsupported language.",[Hi.BLOCKLIST]:"Response stopped due to forbidden terms.",[Hi.PROHIBITED_CONTENT]:"Response stopped due to prohibited content.",[Hi.SPII]:"Response stopped due to sensitive personally identifiable information.",[Hi.OTHER]:"Response stopped for other reasons.",[Hi.MALFORMED_FUNCTION_CALL]:"Response stopped due to malformed function call.",[Hi.IMAGE_SAFETY]:"Response stopped due to image safety violations.",[Hi.IMAGE_PROHIBITED_CONTENT]:"Response stopped due to image prohibited content.",[Hi.IMAGE_RECITATION]:"Response stopped due to image recitation policy.",[Hi.IMAGE_OTHER]:"Response stopped due to other image-related reasons.",[Hi.NO_IMAGE]:"Response stopped due to no image.",[Hi.UNEXPECTED_TOOL_CALL]:"Response stopped due to unexpected tool call."}[et];if(Dt){let Tt=et===Hi.MAX_TOKENS?"\u{1F998} ":"\u26A0\uFE0F ";n({type:"info",text:`${Tt}${Dt}`},ke)}ge.current&&Vt()},[n,Vt]),pi=(0,St.useCallback)((he,ke)=>{$.current&&(n($.current,ke),z(null));let ot=`IMPORTANT: This conversation ${he?.triggerReason==="image_overflow"?`accumulated enough tool screenshots to trigger compaction for ${o.getModel()}`:`approached the input token limit for ${o.getModel()}`}. A compressed context will be sent for future messages (compressed from: ${he?.originalTokenCount??"unknown"} to ${he?.newTokenCount??"unknown"} tokens).`;de(Dt=>({key:(Dt?.key??0)+1,text:ot}))},[n,o,$,z,de]),Vs=(0,St.useCallback)(()=>n({type:"info",text:`The session has reached the maximum number of turns: ${o.getMaxSessionTurns()}. Please update this limit in your setting.json file.`},Date.now()),[n,o]),Ni=(0,St.useCallback)(he=>n({type:"error",text:`\u{1F6AB} Session token limit exceeded: ${he.currentTokens.toLocaleString()} tokens > ${he.limit.toLocaleString()} limit.
|
|
823
823
|
|
|
824
824
|
\u{1F4A1} Solutions:
|
|
825
825
|
\u2022 Start a new session: Use /clear command
|
|
@@ -931,7 +931,7 @@ ${r.join(`
|
|
|
931
931
|
`)}
|
|
932
932
|
---
|
|
933
933
|
${o}`}var _1e=new Set(["github.com","raw.githubusercontent.com","codeload.github.com","api.github.com"]);function L1e(e){let t;try{t=new URL(e)}catch{throw Fe.invalidParams(void 0,"Skill sourceUrl must be a valid URL")}if(t.protocol!=="https:")throw Fe.invalidParams(void 0,"Skill sourceUrl must be an HTTPS URL");if(!_1e.has(t.hostname))throw Fe.invalidParams(void 0,"Skill sourceUrl host is not allowed (only github.com sources are supported)")}function O1e(e){let t=new URL(e);if(t.protocol!=="https:")throw Fe.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 uDt(e){return`https://raw.githubusercontent.com/${e.owner}/${e.repo}/${e.ref}/${e.filePath}`}function ADt(e){return!e||e==="."?"":e.split("/").map(encodeURIComponent).join("/")}function jV(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 dDt(e,t){let n=jV(e,t+124,12);return n?Number.parseInt(n,8):0}function gDt(e,t){for(let n=0;n<512;n+=1)if(e[t+n]!==0)return!1;return!0}function mDt(e,t){let n=jV(e,t,100),o=jV(e,t+345,155);return o?`${o}/${n}`:n}function fDt(e){let t=e.split("/").filter(Boolean);return t.length>1?t.slice(1).join("/"):""}var mk=100*1024*1024,P1e=500*1024*1024,pDt=16,hDt=2e3,iG=class extends Error{};async function CDt(e,t,n={}){let o=n.maxCompressedBytes??mk,r=n.maxDecompressedBytes??P1e;if(e.length>o)throw Fe.invalidParams(void 0,"Skill archive exceeds the maximum allowed size");let s;try{let c=[],u=0;await Kyt(R1e.from([Buffer.from(e)]),zyt(),new M1e({write(d,h,f){if(u+=d.length,u>r){f(new iG);return}c.push(d),f()}})),s=Buffer.concat(c)}catch(c){throw c instanceof iG?Fe.invalidParams(void 0,"Decompressed skill archive exceeds the maximum allowed size"):Fe.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&&!gDt(s,c);){let u=mDt(s,c),d=String.fromCharCode(s[c+156]||0),h=dDt(s,c),f=c+512,y=f+Math.ceil(h/512)*512;if(d==="0"||d==="\0"){let I=fDt(u);if(I.startsWith(a)){let S=I.slice(a.length);S&&l.push({relativePath:S,content:s.subarray(f,f+h)})}}c=y}return l}var EDt=[".githubusercontent.com",".github.com"];function IDt(e){return _1e.has(e)?!0:EDt.some(t=>e.endsWith(t))}async function JV(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 Fe.invalidParams(void 0,"Skill download redirected to an invalid URL")}if(a.protocol!=="https:"||!IDt(a.hostname))throw Fe.invalidParams(void 0,"Skill download redirected to a disallowed host");o=a.toString()}throw Fe.invalidParams(void 0,"Skill download exceeded the maximum number of redirects")}async function U1e(e,t){let n=e.body;if(!n){let l=new Uint8Array(await e.arrayBuffer());if(l.byteLength>t)throw Fe.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(),Fe.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 H1e(e){let t=await JV(e);if(!t.ok)throw Fe.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>mk)throw Fe.invalidParams(void 0,"Skill download exceeds the maximum allowed size")}return U1e(t,mk)}async function yDt(e){let t=O1e(e),n=t?uDt(t):e,o=await H1e(n);return{skillContent:Buffer.from(o).toString("utf8"),files:[{relativePath:"SKILL.md",content:o}]}}async function DDt(e,t){let n=`https://codeload.github.com/${e.owner}/${e.repo}/tar.gz/${encodeURIComponent(e.ref)}`,o=await JV(n,{headers:{"User-Agent":"matilda-code"}});if(!o.ok)throw Fe.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>mk)throw Fe.invalidParams(void 0,"Skill archive exceeds the maximum allowed size")}return CDt(await U1e(o,mk),t)}async function BDt(e,t){let n=ADt(t),o=`https://api.github.com/repos/${e.owner}/${e.repo}/contents/${n}?ref=${encodeURIComponent(e.ref)}`,r=await JV(o,{headers:{Accept:"application/vnd.github+json","User-Agent":"matilda-code"}});if(!r.ok)throw Fe.invalidParams(void 0,`Failed to list GitHub skill files (${r.status})`);let s=await r.json();if(!Array.isArray(s))throw Fe.invalidParams(void 0,"GitHub skill URL must point to a directory-backed SKILL.md file");return s}async function G1e(e,t,n="",o=0,r={files:0,bytes:0}){if(o>pDt)throw Fe.invalidParams(void 0,"Skill directory nesting exceeds the maximum allowed depth");let s=await BDt(e,t),i=[];for(let a of s){let l=wr(a),c=dp(l.name,"github.name"),u=dp(l.path,"github.path"),d=dp(l.type,"github.type"),h=n?No.posix.join(n,c):c;if(d==="dir"){i.push(...await G1e(e,u,h,o+1,r));continue}if(d!=="file")continue;if(r.files+=1,r.files>hDt)throw Fe.invalidParams(void 0,"Skill directory contains too many files");let f=dp(l.download_url,"github.download_url");L1e(f);let y=await H1e(f);if(r.bytes+=y.length,r.bytes>P1e)throw Fe.invalidParams(void 0,"Skill directory exceeds the maximum allowed size");i.push({relativePath:h,content:y})}return i}async function SDt(e,t){let n=await G1e(e,t).catch(o=>(Jn.warn("GitHub API directory listing failed, falling back to archive download:",o),null));return n||DDt(e,t)}async function xDt(e){L1e(e);let t=O1e(e);if(!t||No.posix.basename(t.filePath)!=="SKILL.md")return yDt(e);let n=No.posix.dirname(t.filePath),o=await SDt(t,n),r=o.find(s=>s.relativePath==="SKILL.md");if(!r)throw Fe.invalidParams(void 0,"GitHub skill directory does not contain SKILL.md");return{skillContent:Buffer.from(r.content).toString("utf8"),files:o}}function bDt(e,t){let n=No.resolve(e),o=No.resolve(e,t);if(o!==n&&!o.startsWith(n+No.sep))throw Fe.invalidParams(void 0,`Invalid skill file path: ${t}`);return o}function x1e(e,t){let n=No.resolve(e),o=No.resolve(e,t);if(!o.startsWith(n+No.sep))throw Fe.invalidParams(void 0,"Invalid skill.slug");return o}function wDt(e,t){if(e==null)return[];if(!Array.isArray(e))throw Fe.invalidParams(void 0,`Invalid ${t}: expected string[]`);return Array.from(new Set(e.map(n=>{if(typeof n!="string")throw Fe.invalidParams(void 0,`Invalid ${t}: expected string[]`);return n.trim()}).filter(Boolean)))}function b1e(e,t){if(!(e==null||e==="")){if(typeof e!="number"||!Number.isFinite(e)||e<=0)throw Fe.invalidParams(void 0,`Invalid ${t}: expected positive number`);return e}}function TDt(e){if(e==null)return;let t=wr(e);if(t.enableThinking!==void 0&&typeof t.enableThinking!="boolean")throw Fe.invalidParams(void 0,"Invalid advancedConfig.enableThinking: expected boolean");let n=wr(t.multimodal),o={};for(let a of["image","video","audio","pdf"]){let l=n[a];if(l!==void 0){if(typeof l!="boolean")throw Fe.invalidParams(void 0,`Invalid advancedConfig.multimodal.${a}: expected boolean`);o[a]=l}}let r=b1e(t.contextWindowSize,"advancedConfig.contextWindowSize"),s=b1e(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 QDt(e,t){if(typeof e.documentationUrl=="string")return e.documentationUrl;if(typeof e.documentationUrl=="function")try{return e.documentationUrl(t)}catch{return}}function vDt(e){return typeof wr(e).id=="string"}function W1e(e,t){if(!t)return;let o=wr(e.merged.env)[t];return typeof o=="string"&&o.length>0?o:void 0}function RDt(e,t){let o=wr(e.merged.modelProviders)[t];return Array.isArray(o)?o.filter(vDt):[]}function j1e(e,t){let n=UF(e);if(!n)return;let o=e.protocolOptions?.length?e.protocolOptions:[e.protocol];for(let r of o){let s=RDt(t,r).filter(n);if(s.length>0)return{protocol:r,models:s}}}function Y1e(e,t,n){try{return typeof e.envKey=="function"?e.envKey(t,n):e.envKey}catch{return}}function MDt(e){let t=wr(e?.generationConfig),n=wr(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 kDt(e,t){let n=j1e(e,t),o=n?.models[0],r=n?.protocol??e.protocol,s=typeof o?.baseUrl=="string"?o.baseUrl:Hc(e),i=typeof o?.envKey=="string"?o.envKey:Y1e(e,r,s),a=W1e(t,i);if(!(!!a||!!n))return;let c=MDt(o);return{protocol:r,baseUrl:sG(s),...a?{hasApiKey:!0}:{},...n?{modelIds:n.models.map(u=>u.id)}:{},...c?{advancedConfig:c}:{}}}function FDt(e,t){let n=j1e(e,t),o=n?.models[0],r=n?.protocol??e.protocol,s=typeof o?.baseUrl=="string"?o.baseUrl:Hc(e),i=typeof o?.envKey=="string"?o.envKey:Y1e(e,r,s);return W1e(t,i)}function NDt(e,t){let n=e.protocolOptions?.[0]??e.protocol,o=e.baseUrl===void 0?mB(n):Hc(e),r=kDt(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:pd(e),models:e.models??[],modelsEditable:e.modelsEditable===!0||!e.models,showAdvancedConfig:e.showAdvancedConfig===!0,apiKeyPlaceholder:e.apiKeyPlaceholder,documentationUrl:QDt(e,o),uiGroup:e.uiGroup??"third-party",uiLabels:e.uiLabels,...r?{existingConfig:r}:{}}}function _Dt(e,t,n){let o=Nm(t.protocol,"protocol");if(o&&o!==e.protocol&&!e.protocolOptions?.includes(o))throw Fe.invalidParams(void 0,`Invalid protocol for provider "${e.id}"`);let r=Hc(e,Nm(t.baseUrl,"baseUrl")).trim();if(!r&&e.baseUrl===void 0&&(r=mB(o??e.protocol)),!r)throw Fe.invalidParams(void 0,`Invalid or missing baseUrl for provider "${e.id}"`);let s=Nm(t.apiKey,"apiKey")??n;if(!s)throw Fe.invalidParams(void 0,"Invalid or missing apiKey");let i=e.validateApiKey?.(s,r);if(i)throw Fe.invalidParams(void 0,i);let a=pd(e),l=wDt(t.modelIds,"modelIds"),c=l.length>0?l:a;if(c.length===0)throw Fe.invalidParams(void 0,`Invalid or missing modelIds for provider "${e.id}"`);let u=TDt(t.advancedConfig);return{...o?{protocol:o}:{},baseUrl:r,apiKey:s,modelIds:c,...u?{advancedConfig:u}:{}}}function LDt(e){if(e!==void 0){if(e==="user")return"User";if(e==="workspace")return"Workspace";throw Fe.invalidParams(void 0,"Invalid scope for provider connect")}}function ODt(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 WV(e){let t={};for(let n of F1e){let o=ODt(e,n);o!==void 0&&(t[n]=o)}return t}function PDt(e,t){let n=k1e[e];switch(n.type){case"boolean":if(typeof t!="boolean")throw Fe.invalidParams(void 0,`${e} must be a boolean`);return t;case"number":if(typeof t!="number"||!Number.isFinite(t))throw Fe.invalidParams(void 0,`${e} must be a number`);if(n.min!==void 0&&t<n.min)throw Fe.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 Fe.invalidParams(void 0,`${e} must be one of ${o?.join(", ")}`);return t}case"string":{if(t===void 0)return;if(typeof t!="string")throw Fe.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 Fe.invalidParams(void 0,`${e} has an unsupported setting type`)}}function mg(e){if(e!==void 0){if(!Array.isArray(e))throw Fe.invalidParams(void 0,"Expected an array of strings");return e.map(t=>typeof t=="string"?t.trim():"").filter(Boolean)}}function iD(e){if(e===void 0)return;let t=wr(e),n={};for(let[o,r]of Object.entries(t))typeof r=="string"&&o.trim()&&(n[o.trim()]=r);return n}function gk(e){if(e==null||e==="")return;let t=typeof e=="number"?e:Number.parseInt(String(e),10);if(!Number.isFinite(t)||t<=0)throw Fe.invalidParams(void 0,"Expected a positive number");return t}function UDt(e){let t=wr(e),n=t.transport;if(n!=="stdio"&&n!=="http"&&n!=="sse")throw Fe.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=gk(t.timeout);if(i!==void 0&&(o.timeout=i),typeof t.trust=="boolean"&&(o.trust=t.trust),o.includeTools=mg(t.includeTools),o.excludeTools=mg(t.excludeTools),n==="stdio"){let c=t.command;if(typeof c!="string"||!c.trim())throw Fe.invalidParams(void 0,"Stdio MCP servers require a command");return o.command=c.trim(),o.args=mg(t.args),o.env=iD(t.env),o}let l=t[n==="http"?"httpUrl":"url"];if(typeof l!="string"||!l.trim())throw Fe.invalidParams(void 0,`${n.toUpperCase()} MCP servers require a URL`);return n==="http"?o.httpUrl=l.trim():o.url=l.trim(),o.headers=iD(t.headers),o}function HDt(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 GDt(e){let t=wr(e);if(typeof t.httpUrl=="string")return{transport:"http",httpUrl:t.httpUrl,headers:iD(t.headers),timeout:gk(t.timeout),trust:typeof t.trust=="boolean"?t.trust:void 0,description:typeof t.description=="string"?t.description:void 0,includeTools:mg(t.includeTools),excludeTools:mg(t.excludeTools),extensionName:typeof t.extensionName=="string"?t.extensionName:void 0};if(typeof t.url=="string")return{transport:"sse",url:t.url,headers:iD(t.headers),timeout:gk(t.timeout),trust:typeof t.trust=="boolean"?t.trust:void 0,description:typeof t.description=="string"?t.description:void 0,includeTools:mg(t.includeTools),excludeTools:mg(t.excludeTools),extensionName:typeof t.extensionName=="string"?t.extensionName:void 0};if(typeof t.command=="string")return{transport:"stdio",command:t.command,args:mg(t.args),cwd:typeof t.cwd=="string"?t.cwd:void 0,env:iD(t.env),timeout:gk(t.timeout),trust:typeof t.trust=="boolean"?t.trust:void 0,description:typeof t.description=="string"?t.description:void 0,includeTools:mg(t.includeTools),excludeTools:mg(t.excludeTools),extensionName:typeof t.extensionName=="string"?t.extensionName:void 0}}var aG="__redacted__";function WDt(e){let t=n=>n&&Object.fromEntries(Object.keys(n).map(o=>[o,aG]));return{...e,env:t(e.env),headers:t(e.headers)}}function jDt(e,t){let n=(o,r)=>{if(!o)return o;let s=wr(r),i={};for(let[a,l]of Object.entries(o)){if(l!==aG){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 w1e(e){return e&&Object.fromEntries(Object.keys(e).map(t=>[t,aG]))}function T1e(e,t){if(!e)return e;let n=wr(t),o={};for(let[r,s]of Object.entries(e)){if(s!==aG){o[r]=s;continue}let i=n[r];typeof i=="string"&&(o[r]=i)}return o}function YDt(e){return{...e,hooks:e.hooks.map(t=>({...t,...t.env?{env:w1e(t.env)}:{},...t.headers?{headers:w1e(t.headers)}:{}}))}}function qDt(e,t){let n=Array.isArray(t.hooks)?t.hooks:[];return{...e,hooks:e.hooks.map((o,r)=>{let s=wr(n[r]);return{...o,...o.env?{env:T1e(o.env,s.env)}:{},...o.headers?{headers:T1e(o.headers,s.headers)}:{}}})}}function Ak(e,t){let n=wr(e.mcpServers);return Object.entries(n).map(([o,r])=>{try{let s=GDt(r);return s?{name:o,scope:t,server:WDt(s)}:void 0}catch(s){Jn.warn(`Skipping malformed MCP server config [${t}:${o}]:`,s);return}}).filter(o=>!!o)}function Q1e(e){return typeof e=="string"&&N1e.includes(e)}function JDt(e){let t=wr(e),n=t.type;if(n!=="command"&&n!=="http")throw Fe.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 Fe.invalidParams(void 0,"Command hooks require a command");o.command=s.trim(),o.env=iD(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 Fe.invalidParams(void 0,"HTTP hooks require a URL");o.url=s.trim(),o.headers=iD(t.headers),o.allowedEnvVars=mg(t.allowedEnvVars),typeof t.once=="boolean"&&(o.once=t.once)}let r=gk(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 q1e(e){let t=wr(e),n=t.hooks;if(!Array.isArray(n)||n.length===0)throw Fe.invalidParams(void 0,"Hook definition requires at least one hook");let o={hooks:n.map(JDt)};return typeof t.matcher=="string"&&(o.matcher=t.matcher),typeof t.sequential=="boolean"&&(o.sequential=t.sequential),o}function dk(e,t,n){let o=wr(e.hooks),r=[];for(let s of N1e){let i=o[s];Array.isArray(i)&&i.forEach((a,l)=>{try{r.push({event:s,scope:t,index:l,hook:YDt(q1e(a)),extensionName:n})}catch(c){Jn.warn(`Skipping malformed hook entry [${t}:${s}:${l}]:`,c)}})}return r}function sD(e){if(e==="workspace")return"Workspace";if(e==="user")return"User";throw Fe.invalidParams(void 0,"scope must be user or workspace")}function rG(e,t){return e.forScope(sD(t)).settings}async function v1e(e,t){for(let n of Su()){let o=No.join(e,n);try{return await Pa.access(o),o}catch{}}return No.join(e,t)}async function $Dt(e){let t=Su()[0]??"MATILDA.md",n=await v1e(Mt.getGlobalMatildaDir(),t),o=await v1e(e.cwd,t),r=Pp(e.projectRoot);return{userMemoryFile:n,projectMemoryFile:o,autoMemoryDir:r}}async function J1e(e,t,n){await e.initialize({skipGeminiInitialization:!0,skipMcpDiscovery:!0});let o=M1e.toWeb(process.stdout),r=R1e.toWeb(process.stdin);console.log=console.error,console.info=console.error,console.debug=console.error;let s=uZ(o,r),i,a=new AZ(f=>(i=new YV(e,t,n,f),i),s),l=async f=>{if(i)try{await i.shutdownMcpPool(8e3)}catch(y){Jn.error(`[ACP] MCP pool drain (${f}) error:`,y)}},c=!1,u=!1,d=async f=>{if(u)return;u=!0;let y=new Set([e]),I=i?.getActiveSessions();if(I)for(let S of I){let x=S.getConfig?.();x&&y.add(x)}for(let S of y){let x=S.getHookSystem?.();if(!(S.getDisableAllHooks?.()||!x||!S.hasHooksForEvent?.("SessionEnd")))try{await x.fireSessionEndEvent(f)}catch(T){Jn.warn(`SessionEnd hook failed: ${T instanceof Error?T.message:String(T)}`)}}},h=async()=>{if(!c){c=!0,Jn.debug("[ACP] Shutdown signal received, closing streams"),await d("other"),i?.disposeSessions();try{process.stdin.destroy()}catch{}try{process.stdout.destroy()}catch{}await l("signal"),Ea().catch(f=>{Jn.error("[ACP] Cleanup error:",f)}).finally(()=>{process.exit(0)})}};process.on("SIGTERM",h),process.on("SIGINT",h),await a.closed,await d("prompt_input_exit"),await l("ide_close"),i?.disposeSessions(),process.off("SIGTERM",h),process.off("SIGINT",h)}function VDt(e){if("command"in e&&"args"in e&&"env"in e)return e}function KDt(e){if("type"in e&&e.type==="sse")return e}function zDt(e){if("type"in e&&e.type==="http")return e}function XDt(e){if(!e||!e.trim())return c3;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:c3}function ZDt(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.
|
|
934
|
-
`),3e4;let n=Number.parseInt(t,10);return Number.isFinite(n)?Math.min(6e5,Math.max(1e3,n)):3e4}function eBt(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 gX({clientBudget:o,mode:r,onEvent:e})}var YV=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=eBt(s=>{this.broadcastBudgetEvent(s)}),this.mcpPool=new dX(this.config,{workspaceContext:this.config.getWorkspaceContext(),debugMode:this.config.getDebugMode(),pooledTransports:XDt(process.env.MATILDA_SERVE_MCP_POOL_TRANSPORTS),drainDelayMs:ZDt(process.env.MATILDA_SERVE_MCP_POOL_DRAIN_MS),budget:this.workspaceMcpBudget}))}sessions=new Map;clientCapabilities;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)&&Jn.warn(`MCP pool drain: ${n.drained} clean, ${n.forced} timed out, ${n.errors.length} errors`)}catch(n){Jn.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}try{await n.cancelPendingPrompt()}catch(o){Jn.debug(`Session ${t} cancel during close failed: ${o instanceof Error?o.message:String(o)}`)}try{await n.getConfig().getToolRegistry()?.stop()}catch(o){Jn.debug(`Session ${t} tool registry stop during close failed: ${o instanceof Error?o.message:String(o)}`)}nf(n.getConfig(),t),this.mcpPool?.releaseSession(t),Ir.removeSession(t),this.sessions.delete(t)}disposeSessions(){for(let t of this.sessions.values())t.dispose();this.sessions.clear()}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=>{Jn.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=_V();return{protocolVersion:cZ,agentInfo:{name:"matilda-code",title:"Matilda",version:"0.19.
|
|
934
|
+
`),3e4;let n=Number.parseInt(t,10);return Number.isFinite(n)?Math.min(6e5,Math.max(1e3,n)):3e4}function eBt(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 gX({clientBudget:o,mode:r,onEvent:e})}var YV=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=eBt(s=>{this.broadcastBudgetEvent(s)}),this.mcpPool=new dX(this.config,{workspaceContext:this.config.getWorkspaceContext(),debugMode:this.config.getDebugMode(),pooledTransports:XDt(process.env.MATILDA_SERVE_MCP_POOL_TRANSPORTS),drainDelayMs:ZDt(process.env.MATILDA_SERVE_MCP_POOL_DRAIN_MS),budget:this.workspaceMcpBudget}))}sessions=new Map;clientCapabilities;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)&&Jn.warn(`MCP pool drain: ${n.drained} clean, ${n.forced} timed out, ${n.errors.length} errors`)}catch(n){Jn.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}try{await n.cancelPendingPrompt()}catch(o){Jn.debug(`Session ${t} cancel during close failed: ${o instanceof Error?o.message:String(o)}`)}try{await n.getConfig().getToolRegistry()?.stop()}catch(o){Jn.debug(`Session ${t} tool registry stop during close failed: ${o instanceof Error?o.message:String(o)}`)}nf(n.getConfig(),t),this.mcpPool?.releaseSession(t),Ir.removeSession(t),this.sessions.delete(t)}disposeSessions(){for(let t of this.sessions.values())t.dispose();this.sessions.clear()}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=>{Jn.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=_V();return{protocolVersion:cZ,agentInfo:{name:"matilda-code",title:"Matilda",version:"0.19.9"},authMethods:n,agentCapabilities:{loadSession:!0,promptCapabilities:{image:!0,audio:!0,embeddedContext:!0},sessionCapabilities:{list:{},resume:{}},mcpCapabilities:{sse:!0,http:!0}}}}async authenticate({methodId:t}){let n=bi.nativeEnum(xi).parse(t),o,r=s=>{o=s.verification_uri_complete,this.connection.extNotification("authenticate/update",{_meta:{authUri:o}})};n==="matilda-oauth"&&tf.once("auth-uri",r),await y7();try{await this.config.refreshAuth(n),this.settings.setValue("User","security.auth.selectedType",n)}finally{n==="matilda-oauth"&&tf.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){if(!await qC(this.settings,t.cwd,async()=>new Xs(t.cwd).sessionExists(t.sessionId)))throw Fe.resourceNotFound(`session:${t.sessionId}`);let o=await this.newSessionConfig(t.cwd,t.mcpServers??[],t.sessionId,!0);await this.ensureAuthenticated(o),this.setupFileSystem(o);let r=o.getResumedSessionData(),s=await this.createAndStoreSession(o,r?.conversation);await this.#e(o,s);let i=this.buildModesData(o),a=this.buildAvailableModels(o),l=this.buildConfigOptions(o);return{modes:i,models:a,configOptions:l}}async unstable_resumeSession(t){if(!await qC(this.settings,t.cwd,async()=>new Xs(t.cwd).sessionExists(t.sessionId)))throw Fe.resourceNotFound(`session:${t.sessionId}`);let o=await this.newSessionConfig(t.cwd,t.mcpServers??[],t.sessionId,!0);await this.ensureAuthenticated(o),this.setupFileSystem(o);let r=await this.createAndStoreSession(o);await this.#e(o,r);let s=this.buildModesData(o),i=this.buildAvailableModels(o),a=this.buildConfigOptions(o);return{modes:s,models:i,configOptions:a}}async#e(t,n){try{let o=t.getSessionService().getWorktreeSessionPath(t.getSessionId()),r=await dB(o);r.contextMessage&&(n.pendingWorktreeNotice=r.contextMessage)}catch(o){Jn.warn(`ACP worktree restore failed: ${o}`)}}async unstable_listSessions(t){let n=t.cwd||process.cwd(),o=t.cursor?Number(t.cursor):void 0,r=t._meta?.size,s=typeof r=="number"&&r>0?Math.floor(r):void 0,i=await qC(this.settings,n,()=>new Xs(n).listSessions({cursor:Number.isNaN(o)?void 0:o,size:s}));return{sessions:i.items.map(l=>({_meta:{createdAt:l.startTime,startTime:l.startTime,preview:l.prompt,...l.gitBranch?{gitBranch:l.gitBranch}:{},...l.titleSource?{titleSource:l.titleSource}:{}},cwd:l.cwd,sessionId:l.sessionId,title:l.customTitle||l.prompt||"(session)",updatedAt:new Date(l.mtime).toISOString()})),nextCursor:i.nextCursor!=null?String(i.nextCursor):void 0}}async setSessionMode(t){let n=this.sessions.get(t.sessionId);if(!n)throw Fe.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 Fe.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 Fe.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 Fe.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}`);return n.prompt(t)}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:uk(t.user.settings)},workspace:{path:t.workspace.path,rules:uk(t.workspace.settings)},merged:uk(t.merged),isTrusted:t.isTrusted}}async buildCoreSettings(t,n){let o=t.user.settings,r=t.workspace.settings,s=t.merged,i=[];try{let f=new yl({workspaceDir:n,isWorkspaceTrusted:t.isTrusted});await f.refreshCache(),i=f.getLoadedExtensions()}catch(f){Jn.warn("Extension loading failed, continuing without extensions:",f)}let a=await Promise.all(i.map(async f=>{let y=await AB(f.config,f.id,"user"),I=await AB(f.config,f.id,"workspace"),S=f.settings??[];return{id:f.id,name:f.name,version:f.version,isActive:f.isActive,path:f.path,commands:f.commands??[],skills:(f.skills??[]).map(x=>x.name),mcpServers:Object.keys(f.config.mcpServers??{}),settings:S.map(x=>{let b=y[x.envVar],T=I[x.envVar],R=T!==void 0,Q=b!==void 0,L=R?T:b,O=R?"workspace":Q?"user":void 0;return{name:x.name,description:x.description,envVar:x.envVar,sensitive:!!x.sensitive,userValue:x.sensitive?void 0:b,workspaceValue:x.sensitive?void 0:T,effectiveValue:x.sensitive?void 0:L,effectiveScope:O,hasUserValue:Q,hasWorkspaceValue:R}})}})),l=i.filter(f=>f.isActive),c=l.flatMap(f=>Ak({mcpServers:f.config.mcpServers??{}},"extension").map(y=>({...y,server:{...y.server,extensionName:f.name}}))),u=l.flatMap(f=>dk({hooks:f.hooks??{}},"extension",f.name)),d=new Map;for(let f of Ak(o,"user"))d.set(f.name,f);if(t.isTrusted)for(let f of Ak(r,"workspace"))d.set(f.name,f);let h=[...dk(o,"user"),...t.isTrusted?dk(r,"workspace"):[]];return{user:{path:t.user.path,values:WV(o),mcpServers:Ak(o,"user"),hooks:dk(o,"user")},workspace:{path:t.workspace.path,values:WV(r),mcpServers:Ak(r,"workspace"),hooks:dk(r,"workspace")},merged:{values:WV(s),mcpServers:[...d.values(),...c],hooks:[...h,...u]},extensions:a,isTrusted:t.isTrusted}}syncLivePermissionManagers(t,n){for(let o of eDt){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){Jn.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(Yz()){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)}
|
|
935
935
|
`)}let a,l,c,u=new Set,d="session",h=this.workspaceMcpBudget;if(h!==void 0)d="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 I=y.getMcpClientAccounting();a=I.total,l=y.getMcpClientBudget(),c=y.getMcpBudgetMode(),u=new Set(I.refusedServerNames)}}catch(y){process.stderr.write(`matilda serve: getMcpClientAccounting failed: ${y instanceof Error?y.message:String(y)}
|
|
936
936
|
`)}let f=new md;return{v:yr,workspaceCwd:n,initialized:!0,discoveryState:this.discoveryState(),servers:await Promise.all(Object.entries(s).map(async([y,I])=>{let S=t.isMcpServerDisabled(y),x=!1;try{x=await f.getCredentials(y)!==null}catch{}let b=uA(y),R=u.has(y)&&!S,Q={kind:"mcp_server",status:R?"error":this.mcpCellStatus(b,S),name:y,mcpStatus:this.mcpStatus(b),transport:this.mcpTransport(I),disabled:S,hasOAuthTokens:x};R?(Q.errorKind="budget_exhausted",Q.disabledReason="budget",Q.hint="Raise --mcp-client-budget or remove servers from mcpServers config."):S&&(Q.disabledReason="config");let L=I&&typeof I=="object"?I.description:void 0,O=I&&typeof I=="object"?I.extensionName:void 0;if(typeof L=="string"&&(Q.description=L),typeof O=="string"&&(Q.extensionName=O),Q.source=Q.extensionName?"extension":r.mcpServers?.[y]?"project":"user",I&&typeof I=="object"){let W=I,P={};if(typeof W.command=="string"&&(P.command=W.command),Array.isArray(W.args)){let j=W.args.filter(_=>typeof _=="string");j.length>0&&(P.args=j)}typeof W.httpUrl=="string"&&(P.httpUrl=W.httpUrl),typeof W.url=="string"&&(P.url=W.url),typeof W.cwd=="string"&&(P.cwd=W.cwd),Object.keys(P).length>0&&(Q.config=P)}let Y=i[y];return Y&&(Q.entryCount=Y.entryCount,Q.entrySummary=Y.entrySummary.map(W=>({entryIndex:W.entryIndex,refs:W.refs,status:this.mcpStatus(W.status)}))),Q})),...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,d)}:{}}}catch(n){return{v:yr,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:yr,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 Rg&&l.serverName===n).length===0)for(let l of this.getActiveSessions()){let c=l.getConfig().getToolRegistry(),u=c?.getAllTools()??[];if(u.some(d=>d instanceof Rg&&d.serverName===n)){s=c,i=u;break}}let a=i.filter(l=>l instanceof Rg&&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,d=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}:{},...d?{annotations:d}:{},isValid:c.length===0,...c.length>0?{invalidReason:c.join(", ")}:{}}});return{v:yr,workspaceCwd:o,serverName:n,initialized:!0,acpChannelLive:!0,tools:a}}catch(r){return{v:yr,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>=gT*n&&(i="warning",l=`Live MCP clients are above ${Math.round(gT*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??$p(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:yr,workspaceCwd:this.workspaceCwd(t),initialized:!0,skills:[]};try{let o=await n.listSkills();return{v:yr,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:yr,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?Jh(s,a):s||void 0,c=new Map;for(let f of t.getAllConfiguredModels()){let y=String(f.authType),I=c.get(y);I||(I={kind:"model_provider",status:"ok",authType:y,current:!1,models:[]},c.set(y,I));let S=f.isRuntimeModel&&f.runtimeSnapshotId?f.runtimeSnapshotId:f.id,x=Jh(S,f.authType),b=a===f.authType&&i&&(s===S||s===f.id||l===x),T={modelId:x,baseModelId:NEe(S),name:f.label,...f.description!==void 0?{description:f.description}:{},contextLimit:f.contextWindowSize??XG(S),...f.modalities!==void 0?{modalities:f.modalities}:{},...f.baseUrl!==void 0?{baseUrl:sG(f.baseUrl)}:{},...f.envKey!==void 0?{envKey:f.envKey}:{},isCurrent:b,isRuntime:f.isRuntimeModel===!0};I.models.push(T),b&&(I.current=!0)}let d=t.getContentGeneratorConfig?.()?.baseUrl||void 0,h=this.settings.merged?.fastModel||void 0;return{v:yr,workspaceCwd:n,initialized:!0,...a||l?{current:{...a?{authType:String(a)}:{},...l?{modelId:l}:{},...d?{baseUrl:sG(d)}:{},...h?{fastModelId:h}:{}}}:{},providers:[...c.values()]}}catch(n){return{v:yr,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 hZ)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=Zyt[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=$p(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(uA(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=$p(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=$p(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=$p(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=$p(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:yr,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:yr,workspaceCwd:n,initialized:!0,acpChannelLive:!0,tools:s}}catch(o){let r=$p(o)??"protocol_error";return{v:yr,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 Fe.invalidParams(void 0,`Session not found for id: ${t}`);return n}buildSessionContextStatus(t){let o=this.sessionOrThrow(t).getConfig();return{v:yr,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 DZ(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:yr,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:BZ(s)}}async buildSessionSupportedCommandsStatus(t){let n=this.sessionOrThrow(t),{availableCommands:o,availableSkills:r}=await HV(n.getConfig());return{v:yr,sessionId:t,availableCommands:o,availableSkills:r??[]}}buildSessionTasksStatus(t){let n=this.sessionOrThrow(t);return B1e(t,n.getConfig())}buildSessionStatsStatus(t){let n=this.sessionOrThrow(t),o=n.getConfig(),r=Ir.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:yr,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:yr,workspaceCwd:n,initialized:!0,disabled:o,hooks:[],events:nN};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:yr,workspaceCwd:n,initialized:!0,disabled:o,hooks:i,events:nN}}catch(n){let o=!1;try{o=t.getDisableAllHooks()}catch{}return{v:yr,workspaceCwd:this.safeWorkspaceCwd(t),initialized:!1,disabled:o,hooks:[],events:nN,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:yr,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:yr,sessionId:t,workspaceCwd:r,disabled:s,hooks:l}}catch(r){let s=!1;try{s=o.getDisableAllHooks()}catch{}return{v:yr,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:fd(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:yr,workspaceCwd:n,initialized:!0,extensions:r}}catch(n){return{v:yr,workspaceCwd:this.safeWorkspaceCwd(t),initialized:!1,extensions:[],errors:[this.errorCell("extensions",n)]}}}async installSkillFromUrl(t){let n=this.config.getSkillManager();if(!n)throw Fe.invalidParams(void 0,"SkillManager is not available");let o=await xDt(t.sourceUrl),r=No.join(Mt.getGlobalMatildaDir(),"skills"),s=x1e(r,t.slug),i=No.join(s,"SKILL.md"),a=n.parseSkillContent(o.skillContent,i,"user");if(a.name!==t.slug)throw Fe.invalidParams(void 0,`Skill name "${a.name}" does not match requested slug "${t.slug}"`);let l=`${s}.installing-${process.pid}-${Date.now()}`;try{await Pa.rm(l,{recursive:!0,force:!0});for(let c of o.files){let u=bDt(l,c.relativePath);await Pa.mkdir(No.dirname(u),{recursive:!0}),await Pa.writeFile(u,c.content)}await Pa.rm(s,{recursive:!0,force:!0}),await Pa.rename(l,s)}catch(c){throw await Pa.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 Fe.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 Fe.invalidParams(void 0,`Skill name "${i.name}" does not match requested slug "${t.slug}"`);let a=No.resolve(o),l=No.resolve(r),c=No.resolve(Mt.getGlobalMatildaDir());if(!(l===No.join(a,"SKILL.md"))||a===No.parse(a).root||a===c)throw Fe.invalidParams(void 0,`Refusing to delete unexpected skill directory: ${o}`);return await Pa.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=x1e(No.join(Mt.getGlobalMatildaDir(),"skills"),t),u=No.join(c,"SKILL.md"),d=await Pa.readFile(u,"utf8").catch(()=>{});if(d!==void 0)return{skillDir:c,skillFile:u,content:d}}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 Fe.invalidParams(void 0,`${n==="project"?"Project":"Global"} skill not found: ${t}`);let l=await Pa.readFile(a,"utf8").catch(()=>{throw Fe.invalidParams(void 0,`${n==="project"?"Project":"Global"} skill not found: ${t}`)});return{skillDir:No.dirname(a),skillFile:a,content:l}}async findProjectSkillFileFromCwd(t,n,o){let r=No.resolve(n);for(let s of nDt){let i=No.join(r,s,oDt),c=(await o.loadSkillsFromDir(i,"project")).find(d=>d.name===t)?.filePath;if(!c)continue;let u=await Pa.readFile(c,"utf8").catch(()=>{throw Fe.invalidParams(void 0,`Project skill not found: ${t}`)});return{skillDir:No.dirname(c),skillFile:c,content:u}}}async setGlobalSkillEnabled(t,n){let o=this.config.getSkillManager();if(!o)throw Fe.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 Fe.invalidParams(void 0,`Skill name "${a.name}" does not match requested slug "${t.slug}"`);let l=cDt(s,t.enabled);if(o.parseSkillContent(l,r,i),No.basename(r)!=="SKILL.md")throw Fe.invalidParams(void 0,`Refusing to write to unexpected skill file: ${r}`);return await Pa.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/providers/list":return{providers:fT.map(i=>NDt(i,this.settings))};case"matilda/providers/connect":{let i=dp(n.providerId,"providerId"),a=hX(i);if(!a)throw Fe.invalidParams(void 0,`Unknown provider: ${i}`);let l=_Dt(a,n,FDt(a,this.settings)),c=LDt(n.scope),u=jp(a,l);return await Yp(u,{settings:Jp(this.settings,c),reloadModelProviders:d=>this.config.reloadModelProvidersConfig(d),syncAuthState:(d,h)=>this.config.getModelsConfig().syncAfterAuthRefresh(d,h),refreshAuth:d=>this.config.refreshAuth(d)}),{success:!0,providerId:a.id,providerLabel:a.label,authType:u.authType,modelId:u.modelSelection?.modelId}}case"matilda/skills/install":return this.installSkillFromUrl(sDt(n));case"matilda/skills/delete":return this.deleteGlobalSkill(iDt(n));case"matilda/skills/setEnabled":return this.setGlobalSkillEnabled(aDt(n),o);case"matilda/settings/getMemory":{let i=on(r);return this.settings=i,{settings:S1e(i.merged.memory)}}case"matilda/settings/setMemory":{let i=wr(n.updates),a=on(r);for(let l of rDt)if(i[l]!==void 0){if(typeof i[l]!="boolean")throw Fe.invalidParams(void 0,`Invalid memory setting '${l}': expected boolean`);a.setValue("User",`memory.${l}`,i[l])}return this.settings=a,{settings:S1e(a.merged.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 $Dt({cwd:r,projectRoot:i})}}case Dl.workspaceMcp:return await this.buildWorkspaceMcpStatus(this.config);case Dl.workspaceMcpTools:{let i=n.serverName;if(typeof i!="string"||i.length===0)throw Fe.invalidParams(void 0,"Invalid or missing serverName");return this.buildWorkspaceMcpToolsStatus(this.config,i)}case Dl.workspaceSkills:return await this.buildWorkspaceSkillsStatus(this.config);case Dl.workspaceTools:return this.buildWorkspaceToolsStatus(this.config);case Dl.workspaceProviders:return this.buildWorkspaceProvidersStatus(this.config);case Dl.workspacePreflight:return await this.buildAcpPreflightCells(this.config);case Dl.sessionContext:{let i=n.sessionId;if(typeof i!="string"||i.length===0)throw Fe.invalidParams(void 0,"Invalid or missing sessionId");return this.buildSessionContextStatus(i)}case Dl.sessionContextUsage:{let i=n.sessionId;if(typeof i!="string"||i.length===0)throw Fe.invalidParams(void 0,"Invalid or missing sessionId");return await this.buildSessionContextUsageStatus(i,n.detail===!0)}case Dl.sessionSupportedCommands:{let i=n.sessionId;if(typeof i!="string"||i.length===0)throw Fe.invalidParams(void 0,"Invalid or missing sessionId");return await this.buildSessionSupportedCommandsStatus(i)}case Dl.sessionTasks:{let i=n.sessionId;if(typeof i!="string"||i.length===0)throw Fe.invalidParams(void 0,"Invalid or missing sessionId");return this.buildSessionTasksStatus(i)}case Dl.sessionStats:{let i=n.sessionId;if(typeof i!="string"||i.length===0)throw Fe.invalidParams(void 0,"Invalid or missing sessionId");return this.buildSessionStatsStatus(i)}case Dl.sessionRewindSnapshots:{let i=n.sessionId;if(typeof i!="string"||!s.test(i))throw Fe.invalidParams(void 0,"Invalid or missing sessionId");let a=this.sessions.get(i);if(!a)throw Fe.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,f)=>({s:h,idx:f})).filter(({s:h})=>h.promptId.startsWith(u)&&/^\d+$/.test(h.promptId.slice(u.length))).map(async({s:h,idx:f})=>{let y=await l.getDiffStats(h.promptId);return{promptId:h.promptId,turnIndex:f,timestamp:h.timestamp.toISOString(),diffStats:{filesChanged:y?.filesChanged?.length??0,insertions:y?.insertions??0,deletions:y?.deletions??0}}}))}}case Dl.workspaceHooks:return this.buildWorkspaceHooksStatus(this.config);case Dl.sessionHooks:{let i=n.sessionId;if(typeof i!="string"||i.length===0)throw Fe.invalidParams(void 0,"Invalid or missing sessionId");return this.buildSessionHooksStatus(i)}case Dl.workspaceExtensions:return this.buildWorkspaceExtensionsStatus(this.config);case Ja.workspaceMcpRestart:{let i=n.serverName;if(typeof i!="string"||i.length===0)throw Fe.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 Fe.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 Fe(-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 Fe.internalError(void 0,"McpClientManager unavailable on this Config");if(u.isServerDiscovering(i))return{serverName:i,restarted:!1,skipped:!0,reason:"in_flight"};let d=u.getMcpClientAccounting(),h=u.getMcpClientBudget();if(u.getMcpBudgetMode()==="enforce"&&h!==void 0&&!d.reservedSlots.includes(i)&&d.reservedSlots.length>=h)return{serverName:i,restarted:!1,skipped:!0,reason:"budget_would_exceed"};try{let R=on(this.config.getTargetDir()).merged.tools?.disabled;R!==void 0&&!Array.isArray(R)&&process.stderr.write(`matilda serve: MCP restart for ${JSON.stringify(i)}: tools.disabled has unexpected type ${typeof R}; clearing disabled set \u2014 check settings.json. Expected an array of strings.
|
|
937
937
|
`);let Q=BQ(R);this.config.setDisabledTools(new Set(Q))}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.
|
|
@@ -953,7 +953,7 @@ Reason: ${t}${t instanceof Error&&t.stack?`
|
|
|
953
953
|
Stack trace:
|
|
954
954
|
${t.stack}`:""}`;As.emit("log-error",o),e||(e=!0,As.emit("open-debug-console"))})}function cBt(e){return e==="SIGINT"?130:143}function uBt(e){let t=!1,n=s=>{process.stdin.isTTY&&process.stdin.setRawMode(e),!t&&(t=!0,Ea().catch(i=>{gp.error(`Error during ${s} cleanup:`,i)}).finally(()=>{process.exit(cBt(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 ABt(e,t,n,o=process.cwd(),r){let s=await BT();gBt(rBt(o),t);try{let S=e.getSessionId(),x=e.storage.getRuntimeStatusPath(S);await U7(x,{sessionId:S,workDir:e.getTargetDir(),matildaVersion:s}),e.markRuntimeStatusEnabled()}catch{}let i=process.stdout.isTTY&&!e.getScreenReader()?h1e(process.stdout):()=>{},a=process.stdout.isTTY&&!e.getScreenReader()?C1e(process.stdout):()=>{},l=null,c=e.getJsonFd?.(),u=e.getJsonFile?.();try{c!=null?l=new lk(e,{fd:c},{version:s}):u!=null&&(l=new lk(e,{filePath:u},{version:s}))}catch(S){gp.error("Failed to initialize dual output bridge:",S),Ue(`Warning: dual output disabled \u2014 ${S instanceof Error?S.message:String(S)}`)}let d=null,h=e.getInputFile?.();if(h)try{d=new WH(h)}catch(S){gp.error("Failed to initialize remote input watcher:",S),Ue(`Warning: remote input disabled \u2014 ${S instanceof Error?S.message:String(S)}`)}let f=RV(),y=()=>{let S=qNe(),x=parseInt(process.versions.node.split(".")[0],10);return(0,zu.jsx)(IV.Provider,{value:d,children:(0,zu.jsx)(UJ.Provider,{value:l,children:(0,zu.jsx)(WI.Provider,{value:t,children:(0,zu.jsx)(C2,{kittyProtocolEnabled:S.enabled,config:e,debugKeystrokeLogging:t.merged.general?.debugKeystrokeLogging,pasteWorkaround:process.platform==="win32"||x<20,initialCapturedInput:f,children:(0,zu.jsx)(YSe,{sessionId:e.getSessionId(),children:(0,zu.jsx)(D0e,{settings:t,children:(0,zu.jsx)(QTe,{config:e,children:(0,zu.jsx)(Vwe,{config:e,children:(0,zu.jsx)(jNe,{config:e,settings:t,startupWarnings:n,version:s,initializationResult:r})})})})})})})})})},I=cQ(process.env.DEBUG?(0,zu.jsx)(V1e.default.StrictMode,{children:(0,zu.jsx)(y,{})}):(0,zu.jsx)(y,{}),{exitOnCtrlC:!1,isScreenReaderEnabled:e.getScreenReader()});Ca("first_paint"),iNe().then(S=>{cNe(S,t,e.getProjectRoot())}).catch(S=>{gp.warn(`Update check failed: ${S}`)}),Ed(async()=>{d?.shutdown(),await l?.shutdown(),aIe(),I.unmount(),a(),i()})}async function K1e(){Ca("main_entry"),RZ()&&B7((i,a)=>QZ(i,a)),lBt(),o1e(),process.argv.includes("--bare")&&(process.env[g3]="1"),tZ();let e=await ape();Ca("after_parse_arguments"),kE(e.bare)&&(process.env[g3]="1");let t=kE(e.bare)?DT():on();t.corruptedPath&&(process.env[I3]=t.corruptedPath,process.env[y3]=t.wasRecovered?"1":"0"),await MZ(),Ca("after_load_settings");let n=D3(t);for(let i of n)Ue(i);t.corruptedPath&&Ue("Warning: Settings file had invalid JSON and was reset. A copy of the corrupted file has been saved at: "+t.corruptedPath),e.listExtensions&&(await DW(),process.exit(0)),!kE(e.bare)&&process.stdin.isTTY&&process.stdout.isTTY&&!e.prompt&&!e.promptInteractive&&!e.inputFile&&t.merged.general?.enableAutoUpdate!==!1&&await Kfe()&&process.exit(0),e.promptInteractive&&!process.stdin.isTTY&&(Ue("Error: The --prompt-interactive flag cannot be used when input is piped from stdin."),process.exit(1));let o=$6(e);nBt.setDefaultResultOrder(iBt(t.merged.advanced?.dnsResolutionOrder)),In.loadCustomThemes(t.merged.ui?.customThemes);let r=t.merged.ui?.theme;if(r&&r!==Xc?In.setActiveTheme(r)||Ue(`Warning: Theme "${r}" not found.`):In.setActiveTheme(Xc),!process.env.SANDBOX){let i=t.merged.advanced?.autoConfigureMemory?aBt(o):[],a=await G1(t.merged,e);if(a){let l=await Fv(t.merged,e,void 0,[],{userHooks:t.getUserHooks(),projectHooks:t.getProjectHooks()},kv(t));if(!t.merged.security?.auth?.useExternal)try{let S=l.getModelsConfig().getCurrentAuthType();if(S){let x=zB(S,l);if(x)throw new Error(x);await l.refreshAuth(S)}}catch(S){Ue(`Error authenticating: ${S}`),process.exit(1)}let c=e.inputFormat,u=e.acp||e.experimentalAcp,d="";$1e(e,c,!!u,process.stdin.isTTY)&&(d=await SV());let h=(S,x)=>{let b=[...S];if(x){let T=b.findIndex(R=>R==="--prompt"||R==="-p");T>-1&&b.length>T+1?b[T+1]=`${x}
|
|
955
955
|
|
|
956
|
-
${b[T+1]}`:b.push("--prompt",x)}return b},f=(S,x)=>{let b=S.indexOf("--"),T=b<0?S:S.slice(0,b),R=L=>T.some(O=>L.some(Y=>O===Y||O.startsWith(`${Y}=`)));if(R(["--session-id","--sandbox-session-id"])||R(["--continue","-c"])||R(["--resume","-r"]))return S;let Q=["--sandbox-session-id",x];return b<0?[...S,...Q]:[...T,...Q,...S.slice(b)]},y=l.getSessionId(),I=y?f(h(process.argv,d),y):h(process.argv,d);await xV(()=>ZNe(a,i,l,I)),process.exit(0)}else await $Ne(i,[],{afterSpawn:$V})}if(e.worktree!==void 0){let i=process.cwd(),a=c=>{let u=c.trim();return u.startsWith("{")||u.startsWith("[")},l=c=>typeof c!="string"||c.length===0||a(c)?c:lG.resolve(i,c);if(e.mcpConfig=l(e.mcpConfig),e.openaiLoggingDir=l(e.openaiLoggingDir),e.jsonFile=l(e.jsonFile),e.inputFile=l(e.inputFile),e.telemetryOutfile=l(e.telemetryOutfile),Array.isArray(e.includeDirectories)&&(e.includeDirectories=e.includeDirectories.map(c=>typeof c=="string"&&c.length>0?lG.resolve(i,c):c)),typeof e.jsonSchema=="string"){let c=e.jsonSchema.trim();if(c.startsWith("@")){let u=c.slice(1);u.length>0&&!lG.isAbsolute(u)&&(e.jsonSchema="@"+lG.resolve(i,u))}}}let s=null;e.worktree!==void 0&&(e.acp||e.experimentalAcp)&&(Ue("--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 WIe(e.worktree,{symlinkDirectories:t.merged.worktree?.symlinkDirectories});i!==null&&(i.ok||(Ue(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 kV();else if(!OI(e.resume)){let l=await new Xs(process.cwd()).findSessionsByTitle(e.resume);l.length===1?i=l[0].sessionId:l.length>1&&(Ue(`Multiple sessions found with title "${e.resume}". Please select one:`),i=await kV(process.cwd(),l))}i!==void 0?e={...e,resume:i}:(e.resume===""||!OI(e.resume))&&(e.resume!==""?(Ue(`No saved session found with title "${e.resume}".`),process.exit(1)):process.exit(0))}Ca("after_sandbox_check"),kE(e.bare)||JX(t.merged.general?.outputLanguage);{let i=await Fv(t.merged,e,process.cwd(),e.extensions,{userHooks:t.getUserHooks(),projectHooks:t.getProjectHooks()},kv(t));if(Ca("after_load_cli_config"),s){i.setPendingStartupWorktreeNotice(e5(s));try{let b=await jIe(i,s);b.overrodeResumedWorktree&&Ue(`--worktree overrode the resumed session's previous worktree "${b.overriddenSlug??"(unknown)"}". That worktree directory was left intact on disk.`),i.setPendingStartupWorktreeNotice(e5(s,b))}catch(b){gp.warn(`--worktree sidecar persist failed (non-fatal, notice preserved): ${b instanceof Error?b.message:String(b)}`)}}Ed(()=>{try{let b=Ir.getMetrics();if(!Object.values(b.models).some(R=>R.api.totalRequests>0))return;GF({sessionId:i.getSessionId(),startTime:Ir.getSessionStartTime(),endTime:new Date,project:i.getProjectRoot(),metrics:b})}catch{}}),Ed(()=>i.shutdown());try{let b=i.getModelsConfig(),T=b.getCurrentAuthType(),R=b.getGenerationConfig().baseUrl,Q=i.getProxy();l1e(T,{resolvedBaseUrl:R,proxy:Q})}catch(b){gp.debug(`Preconnect skipped due to error getting authType: ${b}`)}let a=process.stdin.isRaw,l,c;i.isInteractive()&&Ed(uBt(a)),i.isInteractive()&&!a&&process.stdin.isTTY&&(process.stdin.setRawMode(!0),s1e(),Ed(()=>RV()),l=iIe(),(!r||r===Xc)&&(c=In.resolveAutoThemeAsync().catch(b=>{gp.warn("Async theme auto-detection failed:",b)}))),Cye(o);let u=process.stdin.isTTY?"text":typeof i.getInputFormat=="function"?i.getInputFormat():"text",d=await Ppe(i,t);Ca("after_initialize_app"),i.getExperimentalZedIntegration()&&(await J1e(i,t,e),await Ea(),process.exit(0)),i.isInteractive()&&import("./chunks/scheduler-
|
|
956
|
+
${b[T+1]}`:b.push("--prompt",x)}return b},f=(S,x)=>{let b=S.indexOf("--"),T=b<0?S:S.slice(0,b),R=L=>T.some(O=>L.some(Y=>O===Y||O.startsWith(`${Y}=`)));if(R(["--session-id","--sandbox-session-id"])||R(["--continue","-c"])||R(["--resume","-r"]))return S;let Q=["--sandbox-session-id",x];return b<0?[...S,...Q]:[...T,...Q,...S.slice(b)]},y=l.getSessionId(),I=y?f(h(process.argv,d),y):h(process.argv,d);await xV(()=>ZNe(a,i,l,I)),process.exit(0)}else await $Ne(i,[],{afterSpawn:$V})}if(e.worktree!==void 0){let i=process.cwd(),a=c=>{let u=c.trim();return u.startsWith("{")||u.startsWith("[")},l=c=>typeof c!="string"||c.length===0||a(c)?c:lG.resolve(i,c);if(e.mcpConfig=l(e.mcpConfig),e.openaiLoggingDir=l(e.openaiLoggingDir),e.jsonFile=l(e.jsonFile),e.inputFile=l(e.inputFile),e.telemetryOutfile=l(e.telemetryOutfile),Array.isArray(e.includeDirectories)&&(e.includeDirectories=e.includeDirectories.map(c=>typeof c=="string"&&c.length>0?lG.resolve(i,c):c)),typeof e.jsonSchema=="string"){let c=e.jsonSchema.trim();if(c.startsWith("@")){let u=c.slice(1);u.length>0&&!lG.isAbsolute(u)&&(e.jsonSchema="@"+lG.resolve(i,u))}}}let s=null;e.worktree!==void 0&&(e.acp||e.experimentalAcp)&&(Ue("--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 WIe(e.worktree,{symlinkDirectories:t.merged.worktree?.symlinkDirectories});i!==null&&(i.ok||(Ue(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 kV();else if(!OI(e.resume)){let l=await new Xs(process.cwd()).findSessionsByTitle(e.resume);l.length===1?i=l[0].sessionId:l.length>1&&(Ue(`Multiple sessions found with title "${e.resume}". Please select one:`),i=await kV(process.cwd(),l))}i!==void 0?e={...e,resume:i}:(e.resume===""||!OI(e.resume))&&(e.resume!==""?(Ue(`No saved session found with title "${e.resume}".`),process.exit(1)):process.exit(0))}Ca("after_sandbox_check"),kE(e.bare)||JX(t.merged.general?.outputLanguage);{let i=await Fv(t.merged,e,process.cwd(),e.extensions,{userHooks:t.getUserHooks(),projectHooks:t.getProjectHooks()},kv(t));if(Ca("after_load_cli_config"),s){i.setPendingStartupWorktreeNotice(e5(s));try{let b=await jIe(i,s);b.overrodeResumedWorktree&&Ue(`--worktree overrode the resumed session's previous worktree "${b.overriddenSlug??"(unknown)"}". That worktree directory was left intact on disk.`),i.setPendingStartupWorktreeNotice(e5(s,b))}catch(b){gp.warn(`--worktree sidecar persist failed (non-fatal, notice preserved): ${b instanceof Error?b.message:String(b)}`)}}Ed(()=>{try{let b=Ir.getMetrics();if(!Object.values(b.models).some(R=>R.api.totalRequests>0))return;GF({sessionId:i.getSessionId(),startTime:Ir.getSessionStartTime(),endTime:new Date,project:i.getProjectRoot(),metrics:b})}catch{}}),Ed(()=>i.shutdown());try{let b=i.getModelsConfig(),T=b.getCurrentAuthType(),R=b.getGenerationConfig().baseUrl,Q=i.getProxy();l1e(T,{resolvedBaseUrl:R,proxy:Q})}catch(b){gp.debug(`Preconnect skipped due to error getting authType: ${b}`)}let a=process.stdin.isRaw,l,c;i.isInteractive()&&Ed(uBt(a)),i.isInteractive()&&!a&&process.stdin.isTTY&&(process.stdin.setRawMode(!0),s1e(),Ed(()=>RV()),l=iIe(),(!r||r===Xc)&&(c=In.resolveAutoThemeAsync().catch(b=>{gp.warn("Async theme auto-detection failed:",b)}))),Cye(o);let u=process.stdin.isTTY?"text":typeof i.getInputFormat=="function"?i.getInputFormat():"text",d=await Ppe(i,t);Ca("after_initialize_app"),i.getExperimentalZedIntegration()&&(await J1e(i,t,e),await Ea(),process.exit(0)),i.isInteractive()&&import("./chunks/scheduler-5LM4YZEI.js").then(b=>b.startBackgroundHousekeeping(i,t)).catch(b=>{gp.warn("failed to start background housekeeping:",b)});let h=i.getQuestion(),f=[...new Set([...await e1e(),...await n1e({workspaceRoot:process.cwd(),useRipgrep:t.merged.tools?.useRipgrep??!0,useBuiltinRipgrep:t.merged.tools?.useBuiltinRipgrep??!0}),...D3(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(f);for(let b of f)Ue(b);if(Ca("before_render"),i.isInteractive()){i.getJsonSchema?.()&&(Ue("Error: --json-schema is a headless-only flag. Provide a one-shot prompt via -p / --prompt or pipe one in via stdin."),await Ea(),process.exit(1)),vZ(!0),await l,await c,await ABt(i,t,f,process.cwd(),d),$V();return}if($V(),i.getDebugMode()&&(Ue("Debug mode enabled"),Ue(`Logging to: ${Mt.getDebugLogPath(i.getSessionId())}`),oF()&&Ue("Warning: Debug logging is degraded (write failures occurred)")),!i.isInteractive()){let b=_fe(i);b&&Ue(b)}if(u!=="stream-json"){Ca("config_initialize_start"),await i.initialize();for(let T of i.getWarnings())y.has(T)||(y.add(T),Ue(T));Ca("config_initialize_end"),await i.waitForMcpReady();let b=typeof i.getFailedMcpServerNames=="function"?i.getFailedMcpServerNames():[];b.length>0&&Ue(`Warning: MCP server(s) failed to start: ${b.join(", ")}. Continuing with built-in tools and any servers that did connect. Re-run with MATILDA_CODE_DEBUG=1 to see per-server reasons.`),BB(i.getSessionId())}if($1e(e,u,!1,process.stdin.isTTY)){let b=await SV();b&&(h=`${b}
|
|
957
957
|
|
|
958
958
|
${h}`)}let I=await c1e(t.merged.security?.auth?.useExternal,i,t),S=dBt(i.getSessionId());if(u==="stream-json"){let b=(h??"").trim();await XIe(I,b.length>0?b:"",t),await Ea(),process.exit(process.exitCode??0)}h||(Ue("No input provided via stdin. Input can be provided by piping data into gemini or using the --prompt option."),process.exit(1)),oB(i,{"event.name":"user_prompt","event.timestamp":new Date().toISOString(),prompt:h,prompt_id:S,auth_type:i.getContentGeneratorConfig()?.authType,prompt_length:h.length}),gp.debug(`Session ID: ${i.getSessionId()}`);let x=await mR(I,t,h,S);await Ea(),process.exit(x)}}function $1e(e,t,n,o){return o||t==="stream-json"||n?!1:e.prompt===void 0&&e.promptInteractive===void 0}function dBt(e){return`${e}########0`}function gBt(e,t){if(!t.merged.ui?.hideWindowTitle){let n=GU(e);process.stdout.write(`\x1B]2;${n}\x07`),process.on("exit",()=>{process.stdout.write("\x1B]2;\x07")})}}TZ();OZ();var mBt=e=>{if(!e||typeof e!="object")return;let t=e.code;return typeof t=="string"?t:void 0},fBt=e=>{if(!(e instanceof Error))return!1;let t=e.message,n=mBt(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=>{fBt(e)||(e instanceof Error?Ue(e.stack??e.message):Ue(String(e)),process.exit(1))});K1e().catch(e=>{if(e instanceof TK){let t=e.message;process.env.NO_COLOR||(t=`\x1B[31m${t}\x1B[0m`),console.error(t),process.exit(e.exitCode)}e instanceof uf&&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)});
|
|
959
959
|
/**
|