@maincode-ai/matilda-code 0.21.8 → 0.21.9-nightly.20261002.296952bb8
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/bundled/mainy/docs/configuration/settings.md +9 -5
- package/bundled/mainy/docs/reference/keyboard-shortcuts.md +3 -2
- package/chunks/{agent-IL7T4I2K.js → agent-42XJRVPF.js} +1 -1
- package/chunks/{agent-headless-PR64PSXJ.js → agent-headless-B2WO2BRG.js} +1 -1
- package/chunks/ca-H4HPSGTI.js +25 -0
- package/chunks/{chunk-6GY6EBMC.js → chunk-3YQUDBZO.js} +3 -3
- package/chunks/{chunk-FV4IIIXN.js → chunk-4TV7Y2I2.js} +449 -449
- package/chunks/{chunk-QBBPRMPV.js → chunk-BIPE2DPO.js} +1 -1
- package/chunks/{chunk-WOH6NLJH.js → chunk-CRGV5RTO.js} +1 -1
- package/chunks/{chunk-W6CQYQAL.js → chunk-PDJEUFFM.js} +1 -1
- package/chunks/{chunk-YQNGLSJG.js → chunk-ZT5FM6LA.js} +2 -2
- package/chunks/{chunk-6D5M34RS.js → chunk-ZYUCUBVQ.js} +1 -1
- package/chunks/{computer-use-LL6VH2YY.js → computer-use-2WEBSUBX.js} +1 -1
- package/chunks/{contextCommand-NYUQREN7.js → contextCommand-T4EPLKEG.js} +1 -1
- package/chunks/de-S7F37S4F.js +25 -0
- package/chunks/{edit-EZH4FRBA.js → edit-XF6JZJTG.js} +1 -1
- package/chunks/en-S6DMCJQZ.js +25 -0
- package/chunks/{enter-worktree-2NFK4Q5V.js → enter-worktree-ZGDRA7LQ.js} +1 -1
- package/chunks/{enterPlanMode-3RRWLKZY.js → enterPlanMode-SD6WNSGY.js} +1 -1
- package/chunks/{exit-worktree-ROPZ6KRN.js → exit-worktree-GKXP3BXX.js} +1 -1
- package/chunks/{exitPlanMode-XIZ2N2BH.js → exitPlanMode-N6QTNH7W.js} +5 -5
- package/chunks/fr-RFJP3KVL.js +25 -0
- package/chunks/{geminiContentGenerator-Y5BT63HW.js → geminiContentGenerator-43SN6GVF.js} +1 -1
- package/chunks/{glob-ZZX5YQEW.js → glob-OEEUST65.js} +1 -1
- package/chunks/{grep-RITQSEH3.js → grep-L4HQ4A7H.js} +1 -1
- package/chunks/ja-UTJHPL3M.js +25 -0
- package/chunks/{matildaAgentContentGenerator-UATDDKKZ.js → matildaAgentContentGenerator-JBPIHSWA.js} +1 -1
- package/chunks/{matildaContentGenerator-4EWO3QKC.js → matildaContentGenerator-QVTUJHUK.js} +1 -1
- package/chunks/{monitor-DNWGCVNF.js → monitor-NLFSDFES.js} +1 -1
- package/chunks/{notebook-edit-FNCOZCKQ.js → notebook-edit-JWGU34L7.js} +1 -1
- package/chunks/{openaiContentGenerator-FEVSJC7Q.js → openaiContentGenerator-C6UDFUXT.js} +1 -1
- package/chunks/pt-KXMOTADP.js +25 -0
- package/chunks/{ripGrep-6EYEXCRW.js → ripGrep-3UP22VG3.js} +1 -1
- package/chunks/ru-EWGWZPQH.js +25 -0
- package/chunks/{scheduler-WIJWPRZD.js → scheduler-3YLJNH3E.js} +1 -1
- package/chunks/{serve-UUEBKOVV.js → serve-WKHTKFAX.js} +2 -2
- package/chunks/{shell-CTE2Z3PU.js → shell-6SGFFRHM.js} +1 -1
- package/chunks/{skill-ZEEJW7MU.js → skill-3YWNUBGS.js} +1 -1
- package/chunks/src-I27JVKLX.js +3 -0
- package/chunks/{team-create-XO32YS6Q.js → team-create-JS7YWPUT.js} +1 -1
- package/chunks/{workflow-UFWS3C22.js → workflow-2GZDCAAA.js} +2 -2
- package/chunks/{write-file-4K5POBXD.js → write-file-WFXSVG5M.js} +1 -1
- package/cli.js +477 -467
- package/locales/ca.js +26 -19
- package/locales/de.js +26 -19
- package/locales/en.js +30 -21
- package/locales/fr.js +26 -19
- package/locales/ja.js +26 -19
- package/locales/pt.js +26 -19
- package/locales/ru.js +26 -19
- package/package.json +2 -2
- package/sandbox-macos-restrictive-open.sb +5 -0
- package/chunks/ca-UW3G7H5I.js +0 -25
- package/chunks/de-QSFN3SRK.js +0 -25
- package/chunks/en-2BILXSUL.js +0 -25
- package/chunks/fr-FKTJ4COX.js +0 -25
- package/chunks/ja-GKS4GLZP.js +0 -25
- package/chunks/pt-VIW62ZAE.js +0 -25
- package/chunks/ru-FSSACF4A.js +0 -25
- package/chunks/src-CPPHVZMK.js +0 -3
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{b as E}from"./chunk-7ZATDBWL.js";import{xa as P}from"./chunk-
|
|
3
|
+
import{b as E}from"./chunk-7ZATDBWL.js";import{xa as P}from"./chunk-4TV7Y2I2.js";import"./chunk-TZIDSCTF.js";import"./chunk-ROETRE5J.js";import"./chunk-INAZKGGR.js";import"./chunk-DCQKJTAX.js";import"./chunk-LSDMWVW6.js";import"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-VYTYYCBR.js";import"./chunk-TISQNFB5.js";import"./chunk-34DXSYJZ.js";import"./chunk-47XR7IMP.js";import"./chunk-FWIVFCKF.js";import"./chunk-QKYGQLWC.js";import"./chunk-FRL6KOLY.js";import"./chunk-VWWEEU4V.js";import"./chunk-RNKDFE2S.js";import"./chunk-Q2I3ARPJ.js";import"./chunk-CRGV5RTO.js";import"./chunk-QHA3ZBRO.js";import"./chunk-ZYUCUBVQ.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-S7G6QPEP.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-B3NVKOSU.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-32PTAACU.js";import"./chunk-32T6RWWT.js";import"./chunk-6B5BDE7S.js";import"./chunk-RJX7DK4Y.js";import"./chunk-XCJYORZX.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-EQEQPZLQ.js";import{P as l,aa as c}from"./chunk-VLYRNOD3.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as s}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";s();import{stat as V}from"node:fs/promises";import{join as p}from"node:path";s();import{readdir as N,stat as H,rm as F,rmdir as A}from"node:fs/promises";import{join as y}from"node:path";var k=c("HOUSEKEEPING"),U=24*60*60*1e3,$=60*60*1e3,_=20;function T(e){let t=e>0?e*U:$;return new Date(Date.now()-t)}async function b(e){let t={removed:0,errors:0},r=y(l.getGlobalMatildaDir(),P),i=e.excludeSessionIds??new Set,o;try{o=await N(r,{withFileTypes:!0})}catch(n){return G(n)||k.error("readdir failed",n),t}let a=o.filter(n=>n.isDirectory()&&!i.has(n.name)).map(n=>y(r,n.name));for(let n=0;n<a.length;n+=_){let v=a.slice(n,n+_);await Promise.all(v.map(async g=>{try{(await H(g)).mtime<e.cutoffDate&&(await F(g,{recursive:!0,force:!0}),t.removed++)}catch(w){t.errors++,k.error(`failed to sweep ${g}`,w)}}))}return await A(r).catch(()=>{}),t}function G(e){return e?.code==="ENOENT"}s();import{mkdir as Y,open as K,stat as I,unlink as D,writeFile as j}from"node:fs/promises";import{dirname as B}from"node:path";var m=c("HOUSEKEEPING"),q=24*60*60*1e3,J=60*60*1e3;async function R(e,t){let r=e.minIntervalMs??q,i=e.staleLockMs??J;if(await Y(B(e.lockPath),{recursive:!0,mode:448}).catch(()=>{}),await C(e.markerPath,r,e.name))return!1;let o=await h(e.lockPath);if(!o){try{let a=await I(e.lockPath);Date.now()-a.mtimeMs>i&&(await D(e.lockPath).catch(()=>{}),o=await h(e.lockPath))}catch{o=await h(e.lockPath)}if(!o)return m.debug(`${e.name}: skipping, lock held`),!1}try{if(await C(e.markerPath,r,e.name))return!1;let a=!1;try{await t(),a=!0}finally{if(a)try{await j(e.markerPath,new Date().toISOString())}catch(n){m.debug(`${e.name}: marker write failed (cleanup succeeded)`,n)}}return a}finally{await D(e.lockPath).catch(()=>{m.debug(`${e.name}: lock unlink failed (harmless)`)})}}async function C(e,t,r){try{let i=await I(e),o=Date.now()-i.mtimeMs;if(o<t)return m.debug(`${r}: skipping, ran ${o}ms ago`),!0}catch{}return!1}async function h(e){try{return await(await K(e,"wx")).close(),!0}catch(t){if(t?.code==="EEXIST")return!1;throw t}}var u=c("HOUSEKEEPING"),O=10*60*1e3,W=24*60*60*1e3,X=60*1e3,z=7*24*60*60*1e3,Q=60*1e3,f=".file-history-cleanup",d=!1;function pe(e,t){d||(d=!0,Z(e,t).catch(r=>{d=!1,u.error("scheduleFirstPass failed; chain will retry on next start",r)}))}async function Z(e,t){let r=p(l.getGlobalMatildaDir(),f),i=await L(r)?Q:O;u.debug(`first pass in ${i/1e3}s`),setTimeout(()=>S(e,t),i).unref()}async function L(e){try{let t=await V(e);return Date.now()-t.mtimeMs>z}catch{return!0}}async function M(e,t){if(E()<X){u.debug("user active, deferring 10 min"),setTimeout(()=>S(e,t),O).unref();return}try{await x(e,t)}catch(r){u.error("housekeeping pass failed; will retry next cycle",r)}setTimeout(()=>S(e,t),W).unref()}function S(e,t){M(e,t).catch(r=>{u.error("runPass rejected unexpectedly",r)})}async function x(e,t){let r=t.merged.general?.cleanupPeriodDays??30,i=T(r),o=e.getSessionId(),a=l.getGlobalMatildaDir();await R({name:"file-history-cleanup",markerPath:p(a,f),lockPath:p(a,f+".lock")},async()=>{let n=await b({cutoffDate:i,excludeSessionIds:new Set([o])});u.debug(`file-history: removed=${n.removed} errors=${n.errors}`)})}function Se(){d=!1}var we=L,Pe=x,Ee=M,ye=f;export{ye as _FILE_HISTORY_MARKER_FOR_TESTING,we as _needsCatchUpForTesting,Se as _resetForTesting,Pe as _runHousekeepingForTesting,Ee as _runPassForTesting,pe as startBackgroundHousekeeping};
|
|
4
4
|
/**
|
|
5
5
|
* @license
|
|
6
6
|
* Copyright 2025 Google LLC
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{a as Pu}from"./chunk-PA6532AY.js";import{a as Sv}from"./chunk-XMZIY7XX.js";import{$a as Zi,Aa as Tr,B as ns,Ba as Ki,Ca as or,D as ku,Da as an,Ea as ar,Fa as Pr,Ga as mt,Ha as cr,Ia as Mr,Ja as Or,Ka as cn,La as dn,Ma as un,Na as ot,Oa as Ev,Pa as Ji,Qa as ss,Ra as Fu,Sa as ke,Ta as le,Ua as Iv,Va as ln,W as Au,Wa as pn,Xa as Lu,Y as Tt,Ya as Xi,Za as Qi,_a as Yi,ab as xv,bb as eo,cb as Mt,db as Nu,eb as is,fb as $u,ha as Ru,ia as Mu,ja as Pt,jb as Bu,ka as Ou,kb as qu,la as Gi,ma as Qe,na as wt,pa as Du,qa as ie,ra as nn,sa as sn,ta as sr,ua as Rr,va as on,wa as Cr,x as Vi,xa as bt,ya as St,za as ir}from"./chunk-
|
|
3
|
+
import{a as Pu}from"./chunk-PA6532AY.js";import{a as Sv}from"./chunk-XMZIY7XX.js";import{$a as Zi,Aa as Tr,B as ns,Ba as Ki,Ca as or,D as ku,Da as an,Ea as ar,Fa as Pr,Ga as mt,Ha as cr,Ia as Mr,Ja as Or,Ka as cn,La as dn,Ma as un,Na as ot,Oa as Ev,Pa as Ji,Qa as ss,Ra as Fu,Sa as ke,Ta as le,Ua as Iv,Va as ln,W as Au,Wa as pn,Xa as Lu,Y as Tt,Ya as Xi,Za as Qi,_a as Yi,ab as xv,bb as eo,cb as Mt,db as Nu,eb as is,fb as $u,ha as Ru,ia as Mu,ja as Pt,jb as Bu,ka as Ou,kb as qu,la as Gi,ma as Qe,na as wt,pa as Du,qa as ie,ra as nn,sa as sn,ta as sr,ua as Rr,va as on,wa as Cr,x as Vi,xa as bt,ya as St,za as ir}from"./chunk-3YQUDBZO.js";import{a as xu,b as D,d as _u}from"./chunk-ZT5FM6LA.js";import{a as Cu,b as rn,d as Tu,e as zi}from"./chunk-JSFA3NEP.js";import{Bf as yu,Cf as wu,Df as bu,Nl as Ar,Oa as au,Oi as bv,Pa as tn,Qe as hu,Qk as es,Rk as ts,Sk as rs,Tf as kr,Uf as Ve,Xe as mu,Xh as Su,Yj as tt,Zj as Zn,_a as cu,af as Ui,bb as du,bf as gu,cb as uu,cf as vu,db as lu,lg as Yn,qb as Hi,sb as pu,ti as Eu,wb as fu}from"./chunk-4TV7Y2I2.js";import"./chunk-TZIDSCTF.js";import"./chunk-ROETRE5J.js";import"./chunk-INAZKGGR.js";import"./chunk-DCQKJTAX.js";import"./chunk-LSDMWVW6.js";import{e as Iu}from"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-VYTYYCBR.js";import"./chunk-TISQNFB5.js";import"./chunk-34DXSYJZ.js";import"./chunk-47XR7IMP.js";import"./chunk-FWIVFCKF.js";import"./chunk-QKYGQLWC.js";import"./chunk-FRL6KOLY.js";import"./chunk-VWWEEU4V.js";import"./chunk-RNKDFE2S.js";import"./chunk-Q2I3ARPJ.js";import"./chunk-CRGV5RTO.js";import{b as Zd,e as eu}from"./chunk-QHA3ZBRO.js";import{C as jd,D as Wd,E as Hd,F as Ud,G as Vd,H as zd,I as Gd,J as Kd,K as Jd,L as Xd,U as Qd,V as Yd,n as Nd,o as Bi,p as qi,q as Qn,s as $d,u as Bd,v as qd,w as ji,x as _r}from"./chunk-ZYUCUBVQ.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-S7G6QPEP.js";import"./chunk-4J6DC24J.js";import{b as Td}from"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import{Cb as Dd,Eb as Fd,Fb as Ld,Y as Md,da as xr,ea as Od,j as He,t as Pd}from"./chunk-B3NVKOSU.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-32PTAACU.js";import"./chunk-32T6RWWT.js";import"./chunk-6B5BDE7S.js";import{f as tu,h as Wi,i as ru,j as nu,k as su,m as iu,r as ou}from"./chunk-RJX7DK4Y.js";import"./chunk-XCJYORZX.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-EQEQPZLQ.js";import{P as Xn,Q as Cd}from"./chunk-VLYRNOD3.js";import{a as ht}from"./chunk-G7R2XEEF.js";import{a as wv}from"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as w}from"./chunk-GZPNIYVZ.js";import{a as se,d as L,f as yv}from"./chunk-OWGSC52X.js";var fn=L((R_,Uu)=>{w();var _v=se("path").relative;Uu.exports=Tv;var kv=process.cwd();function Wu(t,e){for(var r=t.split(/[ ,]+/),n=String(e).toLowerCase(),s=0;s<r.length;s++){var i=r[s];if(i&&(i==="*"||i.toLowerCase()===n))return!0}return!1}function Av(t,e,r){var n=Object.getOwnPropertyDescriptor(t,e),s=n.value;return n.get=function(){return s},n.writable&&(n.set=function(o){return s=o}),delete n.value,delete n.writable,Object.defineProperty(t,e,n),n}function Rv(t){for(var e="",r=0;r<t;r++)e+=", arg"+r;return e.substr(2)}function Cv(t){var e=this.name+": "+this.namespace;this.message&&(e+=" deprecated "+this.message);for(var r=0;r<t.length;r++)e+=`
|
|
4
4
|
at `+t[r].toString();return e}function Tv(t){if(!t)throw new TypeError("argument namespace is required");var e=as(),r=Dr(e[1]),n=r[0];function s(i){os.call(s,i)}return s._file=n,s._ignored=Mv(t),s._namespace=t,s._traced=Ov(t),s._warned=Object.create(null),s.function=Nv,s.property=$v,s}function Pv(t,e){var r=typeof t.listenerCount!="function"?t.listeners(e).length:t.listenerCount(e);return r>0}function Mv(t){if(process.noDeprecation)return!0;var e=process.env.NO_DEPRECATION||"";return Wu(e,t)}function Ov(t){if(process.traceDeprecation)return!0;var e=process.env.TRACE_DEPRECATION||"";return Wu(e,t)}function os(t,e){var r=Pv(process,"deprecation");if(!(!r&&this._ignored)){var n,s,i,o,a=0,c=!1,d=as(),u=this._file;for(e?(o=e,i=Dr(d[1]),i.name=o.name,u=i[0]):(a=2,o=Dr(d[a]),i=o);a<d.length;a++)if(n=Dr(d[a]),s=n[0],s===u)c=!0;else if(s===this._file)u=this._file;else if(c)break;var l=n?o.join(":")+"__"+n.join(":"):void 0;if(!(l!==void 0&&l in this._warned)){this._warned[l]=!0;var p=t;if(p||(p=i===o||!i.name?ju(o):ju(i)),r){var f=Hu(this._namespace,p,d.slice(a));process.emit("deprecation",f);return}var g=process.stderr.isTTY?Fv:Dv,v=g.call(this,p,n,d.slice(a));process.stderr.write(v+`
|
|
5
5
|
`,"utf8")}}}function Dr(t){var e=t.getFileName()||"<anonymous>",r=t.getLineNumber(),n=t.getColumnNumber();t.isEval()&&(e=t.getEvalOrigin()+", "+e);var s=[e,r,n];return s.callSite=t,s.name=t.getFunctionName(),s}function ju(t){var e=t.callSite,r=t.name;r||(r="<anonymous@"+to(t)+">");var n=e.getThis(),s=n&&e.getTypeName();return s==="Object"&&(s=void 0),s==="Function"&&(s=n.name||s),s&&e.getMethodName()?s+"."+r:r}function Dv(t,e,r){var n=new Date().toUTCString(),s=n+" "+this._namespace+" deprecated "+t;if(this._traced){for(var i=0;i<r.length;i++)s+=`
|
|
6
6
|
at `+r[i].toString();return s}return e&&(s+=" at "+to(e)),s}function Fv(t,e,r){var n="\x1B[36;1m"+this._namespace+"\x1B[22;39m \x1B[33;1mdeprecated\x1B[22;39m \x1B[0m"+t+"\x1B[39m";if(this._traced){for(var s=0;s<r.length;s++)n+=`
|
|
@@ -712,7 +712,7 @@ return fn.apply(this, arguments)
|
|
|
712
712
|
</body>
|
|
713
713
|
</html>`}w();w();import*as u0 from"node:path";var Je=256*1024,l0=5*1024*1024;function At(t,e,r,n="file"){let s=u0.relative(e,t);if(s===""||s.startsWith(".."))return{ignored:!1};let i=r.getFileFilter(),o=r.getDirectoryFilter();if(n==="directory"){let a=s.endsWith("/")?s:`${s}/`;return o(a)?{ignored:!0,category:"directory"}:i(s)?{ignored:!0,category:"file"}:{ignored:!1}}return i(s)?{ignored:!0,category:"file"}:o(s)?{ignored:!0,category:"directory"}:{ignored:!1}}function pt(t,e){if(!t)switch(e){case"read":case"list":case"glob":case"stat":return;case"write":case"edit":throw new B("untrusted_workspace",`workspace is not trusted; ${e} operations are forbidden`,{hint:"mark the folder as trusted in the daemon configuration to allow writes"});default:{let r=e;throw new B("untrusted_workspace",`workspace is not trusted; intent "${String(r)}" is not classified`,{hint:"unknown intent reached the trust gate; classify it in policy.ts"})}}}function Zc(t,e=Je){return t<=e?{bytesToRead:t,truncated:!1}:{bytesToRead:e,truncated:!0}}function Qt(t,e=l0){if(t>e)throw new B("file_too_large",`payload of ${t} bytes exceeds write limit of ${e} bytes`,{hint:"split the write into smaller chunks or raise the daemon limit"})}async function ed(t){return Od(t)}w();import{createHash as TI}from"node:crypto";import*as Yt from"node:path";var td="fs.access",rd="fs.denied";function p0(t){return TI("sha256").update(t).digest("hex").slice(0,16)}var PI="<cross-drive>";function f0(t,e){let r=Yt.isAbsolute(t)?Yt.relative(e,t):t;return Yt.isAbsolute(r)?PI:r}function MI(){return process.env.MATILDA_AUDIT_RAW_PATHS==="1"}function nd(t){let e=t.includeRawPaths??MI(),{emit:r,boundWorkspace:n}=t;return{recordAccess(s,i){let o=String(i.absolute),a={kind:td,intent:i.intent,route:s.route,pathHash:p0(o),durationMs:i.durationMs};s.sessionId&&(a.sessionId=s.sessionId),i.sizeBytes!==void 0&&(a.sizeBytes=i.sizeBytes),i.truncated&&(a.truncated=!0),i.matchedIgnore&&(a.matchedIgnore=i.matchedIgnore),i.pattern!==void 0&&e&&(a.pattern=i.pattern),e&&(a.relPath=f0(o,n)),r({v:1,type:td,data:a,originatorClientId:s.originatorClientId})},recordDenied(s,i){let o=Yt.isAbsolute(i.input)?i.input:Yt.resolve(n,i.input),a={kind:rd,intent:i.intent,route:s.route,pathHash:p0(o),errorKind:i.errorKind};s.sessionId&&(a.sessionId=s.sessionId),i.hint&&(a.hint=i.hint),i.message&&e&&(a.message=i.message),i.pattern!==void 0&&e&&(a.pattern=i.pattern),e&&(a.relPath=f0(i.input,n)),r({v:1,type:rd,data:a,originatorClientId:s.originatorClientId})}}}w();import{createHash as w0,randomBytes as OI}from"node:crypto";import{promises as ye}from"node:fs";import*as Xe from"node:path";function dd(t){let e=Qe(t.boundWorkspace),r=t.ignore??Iu({projectRoot:e,useGitignore:!0,useMatildaignore:!0,ignoreDirs:[]});Object.freeze(r);let n=nd({emit:t.emit,boundWorkspace:e,includeRawPaths:t.includeRawPaths}),s=new vu,i=new ad;return{forRequest(o){return new od({boundWorkspace:e,trusted:t.trusted,ignore:r,audit:n,ctx:o,lowFs:s,pathLocks:i})}}}var od=class{constructor(e){this.deps=e}async resolve(e,r){try{return await Dc(e,this.deps.boundWorkspace,r)}catch(n){throw this.recordAndWrap(n,r,e)}}async stat(e){let r=performance.now();try{pt(this.deps.trusted,"stat");let n=await ye.lstat(e),s={kind:y0(n),sizeBytes:n.size,modifiedMs:n.mtimeMs};return this.deps.audit.recordAccess(this.deps.ctx,{intent:"stat",absolute:e,durationMs:performance.now()-r,sizeBytes:n.size}),s}catch(n){throw this.recordAndWrap(n,"stat",e)}}async readText(e,r={}){let n=performance.now();try{if(pt(this.deps.trusted,"read"),r.line!==void 0&&(!Number.isSafeInteger(r.line)||r.line<1))throw new B("parse_error",`line must be a positive integer, got ${r.line}`);let s=await cd(e,r),i=At(e,this.deps.boundWorkspace,this.deps.ignore,"file"),o=s.meta;return i.ignored&&(o.matchedIgnore=i.category),this.deps.audit.recordAccess(this.deps.ctx,{intent:"read",absolute:e,durationMs:performance.now()-n,sizeBytes:o.sizeBytes,truncated:o.truncated,matchedIgnore:o.matchedIgnore}),{content:s.content,meta:o}}catch(s){throw this.recordAndWrap(s,"read",e)}}async readBytes(e,r={}){return(await this.readBytesWindow(e,r)).buffer}async readBytesWindow(e,r={}){let n=performance.now();try{pt(this.deps.trusted,"read");let s=r.offset??0,i=r.maxBytes??Je;if(!Number.isSafeInteger(s)||s<0)throw new B("parse_error",`offset must be a non-negative integer, got ${s}`);if(!Number.isSafeInteger(i)||i<1||i>Je)throw new B("parse_error",`maxBytes must be a positive integer in [1, ${Je}], got ${i}`);let o=await ye.lstat(e);if(!o.isFile())throw new B("parse_error",`path is not a regular file: ${e}`);let a=await ye.open(e,"r"),c,d;try{c=await a.stat(),jt(o,c,e,"read");let p=Math.max(0,c.size-s),f=Math.min(i,p);if(d=Buffer.allocUnsafe(f),f>0){let v=await a.read(d,0,f,s);d=v.bytesRead===f?d:d.subarray(0,v.bytesRead)}let g=await a.stat();if(jt(c,g,e,"read"),g.size!==c.size||g.mtimeMs!==c.mtimeMs)throw new B("hash_mismatch",`file changed during read: ${e}`,{hint:"retry after re-reading the latest file hash"})}finally{await a.close()}await g0(e,c.ino);let u=s===0&&d.length===c.size,l={buffer:d,sizeBytes:c.size,returnedBytes:d.length,offset:s,truncated:!u,...u?{hash:ud(d)}:{}};return this.deps.audit.recordAccess(this.deps.ctx,{intent:"read",absolute:e,durationMs:performance.now()-n,sizeBytes:d.length,truncated:l.truncated}),l}catch(s){throw this.recordAndWrap(s,"read",e)}}async list(e,r={}){let n=performance.now();try{pt(this.deps.trusted,"list");let s=[],i=await ye.opendir(e);for await(let o of i){let a=Xe.join(e,o.name),c=y0(o),d=At(a,this.deps.boundWorkspace,this.deps.ignore,c==="directory"?"directory":"file");if(!(d.ignored&&!r.includeIgnored)&&(s.push({name:o.name,kind:c,ignored:d.ignored}),r.maxEntries!==void 0&&s.length>=r.maxEntries))break}return this.deps.audit.recordAccess(this.deps.ctx,{intent:"list",absolute:e,durationMs:performance.now()-n,sizeBytes:s.length,truncated:r.maxEntries!==void 0&&s.length>=r.maxEntries}),s}catch(s){throw this.recordAndWrap(s,"list",e)}}async glob(e,r={}){let n=performance.now();try{if(pt(this.deps.trusted,"glob"),e.split(/[\\/]/).some(p=>p===".."))throw new B("parse_error",`glob pattern may not contain '..' segments: ${e}`);if(Xe.isAbsolute(e)||/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("\\\\")||e.startsWith("//"))throw new B("parse_error",`glob pattern must be workspace-relative: ${e}`,{hint:'pass a relative pattern such as "src/**/*.ts"'});let s=r.cwd??this.deps.boundWorkspace,i;if(s===this.deps.boundWorkspace)i=s;else try{i=await ye.realpath(Xe.resolve(s))}catch(p){throw p?.code==="ENOENT"?new B("path_not_found",`glob cwd does not exist: ${s}`,{cause:p}):p}if(!xr(i,this.deps.boundWorkspace))throw new B("path_outside_workspace",`glob cwd is outside workspace: ${s}`,{hint:"opts.cwd must be a path obtained from fs.resolve()"});let o=await mu(e,{cwd:i,nodir:!1,absolute:!0,dot:!0,ignore:["**/node_modules/**","**/.git/**"]}),a=[],c=r.maxResults??Number.POSITIVE_INFINITY,d=0,u=0,l=0;for(let p of o){if(a.length>=c)break;let f=Xe.resolve(p),g;try{g=await ye.realpath(f)}catch(q){let U=q?.code;U==="ENOENT"||U==="ELOOP"?d+=1:U==="EACCES"||U==="EPERM"?u+=1:l+=1;continue}let v=Xe.relative(this.deps.boundWorkspace,g);if(v.startsWith("..")||Xe.isAbsolute(v)){d+=1;continue}let x=null;try{x=await ye.lstat(g)}catch{x=null}let O=x?.isDirectory()?"directory":"file";At(g,this.deps.boundWorkspace,this.deps.ignore,O).ignored&&!r.includeIgnored||a.push(g)}return d>0&&this.deps.audit.recordDenied(this.deps.ctx,{intent:"glob",input:e,errorKind:"symlink_escape",hint:`glob filtered ${d} hit(s) that resolved outside workspace`,pattern:e}),u>0&&this.deps.audit.recordDenied(this.deps.ctx,{intent:"glob",input:e,errorKind:"permission_denied",hint:`glob skipped ${u} hit(s) due to EACCES/EPERM`,pattern:e}),l>0&&this.deps.audit.recordDenied(this.deps.ctx,{intent:"glob",input:e,errorKind:"io_error",hint:`glob skipped ${l} hit(s) due to transient I/O errors (EIO/EBUSY/ENAMETOOLONG/EMFILE)`,pattern:e}),this.deps.audit.recordAccess(this.deps.ctx,{intent:"glob",absolute:this.deps.boundWorkspace,durationMs:performance.now()-n,sizeBytes:a.length,pattern:e}),a}catch(s){throw this.recordAndWrap(s,"glob",e)}}async writeTextAtomic(e,r,n){let s=performance.now();try{pt(this.deps.trusted,"write"),FI(n);let i=Buffer.byteLength(r,"utf-8");return Qt(i),await this.deps.pathLocks.runExclusive(e,async()=>{let a=n.mode==="replace"?await h0(e,n.expectedHash):void 0;n.mode==="create"&&await b0(e);let c=sd(a,n),d=await id({target:e,content:r,mode:n.mode,expectedHash:n.expectedHash,meta:c}),u=At(e,this.deps.boundWorkspace,this.deps.ignore,"file");return u.ignored&&(c.matchedIgnore=u.category),c.sizeBytes=d.sizeBytes,c.hash=d.hash,this.deps.audit.recordAccess(this.deps.ctx,{intent:"write",absolute:e,durationMs:performance.now()-s,sizeBytes:d.sizeBytes,matchedIgnore:c.matchedIgnore}),{created:n.mode==="create",sizeBytes:d.sizeBytes,hash:d.hash,meta:c}})}catch(i){throw this.recordAndWrap(i,"write",e)}}async writeTextOverwrite(e,r,n={}){let s=performance.now();try{pt(this.deps.trusted,"write");let i=Buffer.byteLength(r,"utf-8");return Qt(i),await this.deps.pathLocks.runExclusive(e,async()=>{let a=!1;try{await ye.lstat(e),a=!0}catch(p){if(p?.code!=="ENOENT")throw p}let c;try{c=await h0(e)}catch(p){let f=p?.code,g=p?.kind;if(f!=="ENOENT"&&f!=="EACCES"&&f!=="EPERM"&&g!=="file_too_large"&&g!=="binary_file")throw p}let d=sd(c,n),u=await id({target:e,content:r,mode:"overwrite",meta:d}),l=At(e,this.deps.boundWorkspace,this.deps.ignore,"file");return l.ignored&&(d.matchedIgnore=l.category),d.sizeBytes=u.sizeBytes,d.hash=u.hash,this.deps.audit.recordAccess(this.deps.ctx,{intent:"write",absolute:e,durationMs:performance.now()-s,sizeBytes:u.sizeBytes,matchedIgnore:d.matchedIgnore}),{created:!a,sizeBytes:u.sizeBytes,hash:u.hash,meta:d}})}catch(i){throw this.recordAndWrap(i,"write",e)}}async writeText(e,r,n){let s=performance.now();try{pt(this.deps.trusted,"write");let i=Buffer.byteLength(r,"utf-8");Qt(i),await v0(e),await this.deps.lowFs.writeTextFile({path:e,content:r,_meta:n?S0(n):void 0});let o=At(e,this.deps.boundWorkspace,this.deps.ignore,"file");this.deps.audit.recordAccess(this.deps.ctx,{intent:"write",absolute:e,durationMs:performance.now()-s,sizeBytes:i,matchedIgnore:o.ignored?o.category:void 0})}catch(i){throw this.recordAndWrap(i,"write",e)}}async editAtomic(e,r,n,s){let i=performance.now();try{if(pt(this.deps.trusted,"edit"),!wr(s.expectedHash))throw new B("parse_error","expectedHash must match sha256:<64 lowercase hex chars>");if(typeof r!="string"||r.length===0)throw new B("parse_error",`oldText must be a non-empty string for edit on ${e}`);if(typeof n!="string")throw new B("parse_error","newText must be a string");return await this.deps.pathLocks.runExclusive(e,async()=>{let a=await cd(e);if(a.meta.hash!==s.expectedHash)throw new B("hash_mismatch",`expected ${s.expectedHash}, found ${a.meta.hash}`,{hint:"re-read the file and retry with the latest hash"});let c=a.content,d=KI(c,r);if(d===0){let v=r.length>80?r.slice(0,80)+"...":r;throw new B("text_not_found",`oldText not found in ${e}`,{hint:`searched for: ${JSON.stringify(v)}`})}if(d>1)throw new B("ambiguous_text_match",`oldText appears ${d} times in ${e}`,{hint:"pass a larger oldText span that occurs exactly once"});let u=c.indexOf(r),l=c.slice(0,u)+n+c.slice(u+r.length);Qt(Buffer.byteLength(l,"utf-8"));let p=sd(a.meta,{}),f=await id({target:e,content:l,mode:"replace",expectedHash:s.expectedHash,meta:p}),g=At(e,this.deps.boundWorkspace,this.deps.ignore,"file");return g.ignored&&(p.matchedIgnore=g.category),p.sizeBytes=f.sizeBytes,p.hash=f.hash,this.deps.audit.recordAccess(this.deps.ctx,{intent:"edit",absolute:e,durationMs:performance.now()-i,sizeBytes:f.sizeBytes,matchedIgnore:p.matchedIgnore}),{writtenBytes:f.sizeBytes,hash:f.hash,meta:p}})}catch(o){throw this.recordAndWrap(o,"edit",e)}}async edit(e,r,n,s){if(s?.expectedHash!==void 0)return this.editAtomic(e,r,n,{expectedHash:s.expectedHash});let i=performance.now();try{pt(this.deps.trusted,"edit");let o=await ye.stat(e);if(o.size>Je)throw new B("file_too_large",`file of ${o.size} bytes exceeds edit cap of ${Je} bytes`,{hint:"split large edits into bounded readBytes/writeText sequences"});if(await ed(e))throw new B("binary_file",`cannot edit binary file: ${e}`,{hint:"edit() works on text files only"});if(r.length===0)throw new B("parse_error",`oldText must be a non-empty string for edit on ${e}`,{hint:"empty oldText would match at position 0 and silently prepend newText"});let a=await this.deps.lowFs.readTextFile({path:e,limit:Number.POSITIVE_INFINITY,line:0}),c=a.content;await g0(e,o.ino);let d=c.indexOf(r);if(d===-1){let f=r.length>80?r.slice(0,80)+"\u2026":r;throw new B("parse_error",`oldText not found in ${e}`,{hint:`edit() expects oldText to appear verbatim; searched for: ${JSON.stringify(f)}`})}let u=c.slice(0,d)+n+c.slice(d+r.length),l=Buffer.byteLength(u,"utf-8");Qt(l),await v0(e),await this.deps.lowFs.writeTextFile({path:e,content:u,_meta:a._meta});let p=At(e,this.deps.boundWorkspace,this.deps.ignore,"file");return this.deps.audit.recordAccess(this.deps.ctx,{intent:"edit",absolute:e,durationMs:performance.now()-i,sizeBytes:l,matchedIgnore:p.ignored?p.category:void 0}),{writtenBytes:l}}catch(o){throw this.recordAndWrap(o,"edit",e)}}recordAndWrap(e,r,n){let s=Sg(e);return this.deps.audit.recordDenied(this.deps.ctx,{intent:r,input:n,errorKind:s.kind,hint:s.hint,message:s.message,pattern:r==="glob"?n:void 0}),s}},DI=/^sha256:[0-9a-f]{64}$/;function wr(t){return typeof t=="string"&&DI.test(t)}var ad=class{tails=new Map;async runExclusive(e,r){let n=this.tails.get(e)??Promise.resolve(),s,i=new Promise(a=>{s=a}),o=n.catch(()=>{}).then(()=>i);this.tails.set(e,o),await n.catch(()=>{});try{return await r()}finally{s(),this.tails.get(e)===o&&this.tails.delete(e)}}};function FI(t){if(t.mode!=="create"&&t.mode!=="replace")throw new B("parse_error",'mode must be either "create" or "replace" (use writeTextOverwrite() for unconditional overwrites)');if(t.expectedHash!==void 0&&!wr(t.expectedHash))throw new B("parse_error","expectedHash must match sha256:<64 lowercase hex chars>");if(t.mode==="replace"&&t.expectedHash===void 0)throw new B("parse_error",'expectedHash is required when mode is "replace"');if(t.lineEnding!==void 0&&t.lineEnding!=="lf"&&t.lineEnding!=="crlf")throw new B("parse_error",'lineEnding must be "lf" or "crlf"')}async function cd(t,e={}){let r=await ye.lstat(t);if(r.isSymbolicLink())throw new B("symlink_escape",`path is a symlink: ${t}`,{hint:"re-resolve the target file instead of reading through a link"});if(!r.isFile())throw new B("parse_error",`path is not a regular file: ${t}`);if(r.size>Je)throw new B("file_too_large",`file of ${r.size} bytes exceeds read cap of ${Je} bytes`,{hint:"use readBytes for explicit byte-windowed access on large files"});let n=await LI(t,r);if($I(n))throw new B("binary_file",`binary file: ${t}`,{hint:"use readBytes for binary content"});let s=Md(n),i=e.line!==void 0?e.line-1:0,o=NI(s.content,i,e.limit??Number.POSITIVE_INFINITY),a=Zc(n.length,e.maxBytes),c=o.content,d={encoding:s.encoding,bom:s.bom,lineEnding:Ui(c),sizeBytes:n.length,originalLineCount:o.originalLineCount,hash:ud(n)};if(a.truncated){let u=Buffer.from(c,"utf-8");u.length>a.bytesToRead&&(c=JI(u,a.bytesToRead).toString("utf-8"),d.lineEnding=Ui(c)),d.truncated=!0}return e.limit!==void 0&&Number.isFinite(e.limit)&&o.originalLineCount>e.limit+i&&(d.truncated=!0),{content:c,meta:d}}async function LI(t,e){let r=await ye.open(t,"r"),n;try{if(n=await r.stat(),jt(e,n,t,"read"),n.size>Je)throw new B("file_too_large",`file of ${n.size} bytes exceeds read cap of ${Je} bytes`,{hint:"use readBytes for explicit byte-windowed access on large files"});let s=Buffer.alloc(n.size),i=0;for(;i<n.size;){let c=await r.read(s,i,n.size-i,i);if(c.bytesRead===0)break;i+=c.bytesRead}let o=await r.stat();if(jt(n,o,t,"read"),o.size!==n.size||o.mtimeMs!==n.mtimeMs)throw new B("hash_mismatch",`file changed during read: ${t}`,{hint:"retry after re-reading the latest file hash"});let a=await ye.lstat(t);if(jt(e,a,t,"read"),a.size!==n.size||a.mtimeMs!==n.mtimeMs)throw new B("hash_mismatch",`file changed during read: ${t}`,{hint:"retry after re-reading the latest file hash"});return i===s.length?s:s.subarray(0,i)}finally{await r.close()}}function NI(t,e,r){let n=t.split(`
|
|
714
714
|
`),s=n.length,i=Math.min(e+r,s),o=Math.min(e,s);return{content:n.slice(o,i).join(`
|
|
715
|
-
`),originalLineCount:s}}function $I(t){if(t.length===0)return!1;let e=t.subarray(0,Math.min(4,t.length));if(e.length>=4&&(e[0]===255&&e[1]===254&&e[2]===0&&e[3]===0||e[0]===0&&e[1]===0&&e[2]===254&&e[3]===255)||e.length>=3&&e[0]===239&&e[1]===187&&e[2]===191||e.length>=2&&(e[0]===255&&e[1]===254||e[0]===254&&e[1]===255))return!1;let n=Math.min(4096,t.length),s=0;for(let i=0;i<n;i++){if(t[i]===0)return!0;(t[i]<9||t[i]>13&&t[i]<32)&&s++}return s/n>.3}async function h0(t,e){let r=await cd(t);if(e!==void 0&&r.meta.hash!==e)throw new B("hash_mismatch",`expected ${e}, found ${r.meta.hash}`,{hint:"re-read the file and retry with the latest hash"});return r.meta}function sd(t,e){return{encoding:e.encoding??t?.encoding??"utf-8",bom:e.bom??t?.bom??!1,lineEnding:e.lineEnding??t?.lineEnding??"lf"}}async function id(t){let e=t.target,r=Xe.dirname(e),n=await ye.lstat(r);if(n.isSymbolicLink())throw new B("symlink_escape",`parent path is a symlink: ${r}`,{hint:"re-resolve the target after detecting parent-symlink swaps"});if(!n.isDirectory())throw new B("parse_error",`parent path is not a directory: ${r}`);let s=Xe.join(r,`.${Xe.basename(e)}.${process.pid}.${OI(6).toString("hex")}.tmp`),i=!1,o,a;try{o=await BI(s),i=!0;let c=await qI({targetPath:e,tmpPath:s,content:t.content,meta:t.meta,handle:o});a=c.stat;let d=await jI({target:e,mode:t.mode,expectedHash:t.expectedHash});return await VI(o,d.mode??384),await m0(s,a),await o.close(),o=void 0,await m0(s,a),t.mode==="create"?await zI(s,e):await GI(s,e,3,50),i=!1,await UI(r),c}catch(c){if(await o?.close().catch(()=>{}),i)try{await ye.unlink(s)}catch{}throw c}}async function BI(t){return ye.open(t,"wx",384)}async function qI(t){let e=gu(t.targetPath,t.content,S0(t.meta));Qt(e.length),await t.handle.writeFile(e),await HI(t.handle);let r=await ye.lstat(t.tmpPath),n=await t.handle.stat();if(jt(n,r,t.tmpPath,"write"),r.isSymbolicLink())throw new B("symlink_escape",`temporary path became a symlink: ${t.tmpPath}`,{hint:"temp-file race detected before final rename"});if(!r.isFile())throw new B("parse_error",`temporary path is not a regular file: ${t.tmpPath}`);return{sizeBytes:e.length,hash:ud(e),stat:r}}async function b0(t){try{throw(await ye.lstat(t)).isSymbolicLink()?new B("symlink_escape",`path is a symlink and cannot be created over: ${t}`,{hint:"remove the symlink or resolve the target explicitly"}):new B("file_already_exists",`file already exists: ${t}`)}catch(e){if(e?.code==="ENOENT")return;throw e}}async function jI(t){if(t.mode==="create")return await b0(t.target),{};if(t.mode==="overwrite"){let n;try{n=await ye.lstat(t.target)}catch(s){if(s?.code==="ENOENT")return{};throw s}if(n.isSymbolicLink())throw new B("symlink_escape",`path is a symlink and cannot be overwritten atomically: ${t.target}`,{hint:"re-resolve the target file instead of writing through a link"});if(!n.isFile())throw new B("parse_error",`path is not a regular file: ${t.target}`);return{mode:n.mode&4095}}if(!wr(t.expectedHash))throw new B("parse_error",'expectedHash is required when mode is "replace"');let e=await ye.lstat(t.target);if(e.isSymbolicLink())throw new B("symlink_escape",`path is a symlink and cannot be replaced atomically: ${t.target}`,{hint:"re-resolve the target file instead of writing through a link"});if(!e.isFile())throw new B("parse_error",`path is not a regular file: ${t.target}`);let r=await WI(t.target,e);if(r!==t.expectedHash)throw new B("hash_mismatch",`expected ${t.expectedHash}, found ${r}`,{hint:"re-read the file and retry with the latest hash"});return{mode:e.mode&4095}}async function WI(t,e){let r=await ye.open(t,"r"),n=w0("sha256"),s;try{s=await r.stat(),jt(e,s,t,"read");let o=Buffer.allocUnsafe(64*1024),a=0;for(;a<s.size;){let c=await r.read(o,0,Math.min(o.length,s.size-a),a);if(c.bytesRead===0)break;n.update(o.subarray(0,c.bytesRead)),a+=c.bytesRead}}finally{await r.close()}if(s===void 0)throw new B("internal_error",`failed to stat opened file: ${t}`);let i=await ye.lstat(t);if(jt(e,i,t,"read"),i.size!==s.size||i.mtimeMs!==s.mtimeMs)throw new B("hash_mismatch",`file changed during hash: ${t}`,{hint:"retry after re-reading the latest file hash"});return`sha256:${n.digest("hex")}`}function ud(t){return`sha256:${w0("sha256").update(t).digest("hex")}`}function jt(t,e,r,n){let s=Jr(t.dev),i=Jr(e.dev),o=Jr(t.ino),a=Jr(e.ino);if(s!==0n&&i!==0n&&o!==0n&&a!==0n&&(s!==i||o!==a))throw new B("symlink_escape",`path changed during ${n}: ${r}`,{hint:"TOCTOU swap detected via device/inode comparison"})}function Jr(t){return typeof t=="bigint"?t:BigInt(t)}async function HI(t){try{await t.sync()}catch{}}async function UI(t){let e;try{e=await ye.open(t,"r"),await e.sync()}catch{}finally{await e?.close().catch(()=>{})}}async function VI(t,e){try{await t.chmod(e)}catch{}}async function m0(t,e){let r=await ye.lstat(t);if(r.isSymbolicLink())throw new B("symlink_escape",`temporary path is a symlink: ${t}`,{hint:"temp-file race detected before final rename"});if(!r.isFile())throw new B("parse_error",`temporary path is not a regular file: ${t}`);jt(e,r,t,"write")}async function zI(t,e){try{await ye.link(t,e)}catch(r){throw r?.code==="EEXIST"?new B("file_already_exists",`file already exists: ${e}`):r}await ye.unlink(t).catch(()=>{})}async function GI(t,e,r,n){for(let s=0;s<=r;s++)try{await ye.rename(t,e);return}catch(i){let o=i?.code;if(!(o==="EPERM"||o==="EACCES")||s===r)throw i;await new Promise(c=>setTimeout(c,n*2**s))}}function KI(t,e){let r=0,n=0;for(;;){let s=t.indexOf(e,n);if(s===-1)return r;r+=1,n=s+e.length}}function JI(t,e){if(t.length<=e)return t;let r=e;for(;r>0&&(t[r]&192)===128;)r--;return t.subarray(0,r)}async function g0(t,e){let r=await ye.lstat(t);if(r.isSymbolicLink())throw new B("symlink_escape",`path was replaced with a symlink during read: ${t}`,{hint:"TOCTOU swap detected via post-read lstat"});let n=Jr(e),s=Jr(r.ino);if(n!==0n&&s!==0n&&n!==s)throw new B("symlink_escape",`path inode changed during read: ${t}`,{hint:"TOCTOU swap detected via inode comparison"})}async function v0(t){let e;try{e=await ye.lstat(t)}catch(r){if(r?.code==="ENOENT")return;throw r}if(e.isSymbolicLink())throw new B("symlink_escape",`path was replaced with a symlink before write: ${t}`,{hint:"TOCTOU swap detected via pre-write lstat \u2014 re-resolve before retrying"})}function y0(t){return t.isSymbolicLink()?"symlink":t.isDirectory()?"directory":t.isFile()?"file":"other"}function S0(t){let e={};return t.bom!==void 0&&(e.bom=t.bom),t.encoding&&(e.encoding=t.encoding),t.lineEnding&&(e.lineEnding=t.lineEnding),Object.keys(e).length>0?e:void 0}w();import*as $n from"node:path";var ld=2e3,E0=2e3,XI=64*1024,QI=5e3,I0=5e4;function Pe(t){t.set("Cache-Control","no-store"),t.set("X-Content-Type-Options","nosniff")}function Zt(t,e,r){if(Pe(t),Oc(e)){let n=e;t.status(n.status).json({errorKind:n.kind,error:n.message,hint:n.hint,status:n.status});return}D(`matilda serve: ${r} unexpected error: ${e instanceof Error?e.message:String(e)}`),t.status(500).json({errorKind:"internal_error",error:e instanceof Error?e.message:String(e),status:500})}function Xr(t,e,r){if(t===void 0)return;if(typeof t!="string"||!/^\d+$/.test(t))return null;let n=Number.parseInt(t,10);return!Number.isSafeInteger(n)||n<e||n>r?null:n}function x0(t){return t==="1"||t==="true"}function Bn(t,e,r,n){return typeof e!="string"||e.length===0?(Pe(t),t.status(400).json({errorKind:"parse_error",error:`${r} query parameter is required`,status:400}),D(`matilda serve: ${n} rejected request missing required ?${r}`),null):e}function qn(t,e){let r=t.app.locals.fsFactory;return r||(Pe(e),e.status(500).json({errorKind:"internal_error",error:"workspace filesystem factory is not configured",status:500}),null)}async function YI(t,e,r){let n="GET /file",s=qn(t,e);if(!s)return;let i=r.parseClientId(t,e);if(i===null)return;let o=Bn(e,t.query.path,"path",n);if(o===null)return;let a=Xr(t.query.maxBytes,1,256*1024);if(a===null){Pe(e),e.status(400).json({errorKind:"parse_error",error:"`maxBytes` must be a positive integer in [1, 262144]",status:400});return}let c=Xr(t.query.line,1,Number.MAX_SAFE_INTEGER);if(c===null){Pe(e),e.status(400).json({errorKind:"parse_error",error:"`line` must be a positive integer",status:400});return}let d=Xr(t.query.limit,1,E0);if(d===null){Pe(e),e.status(400).json({errorKind:"parse_error",error:`\`limit\` must be a positive integer in [1, ${E0}]`,status:400});return}let u=s.forRequest({originatorClientId:i??void 0,route:n});try{let l=await u.resolve(o,"read"),p=await u.readText(l,{maxBytes:a,line:c,limit:d}),f=Buffer.byteLength(p.content,"utf-8");Pe(e),e.status(200).json({kind:"file",path:er(t,l),content:p.content,encoding:p.meta.encoding??"utf-8",bom:p.meta.bom===!0,lineEnding:p.meta.lineEnding,sizeBytes:p.meta.sizeBytes??f,returnedBytes:f,truncated:p.meta.truncated===!0,hash:p.meta.hash,matchedIgnore:p.meta.matchedIgnore??null,originalLineCount:p.meta.originalLineCount??null})}catch(l){Zt(e,l,n)}}async function ZI(t,e,r){let n="GET /file/bytes",s=qn(t,e);if(!s)return;let i=r.parseClientId(t,e);if(i===null)return;let o=Bn(e,t.query.path,"path",n);if(o===null)return;let a=Xr(t.query.offset,0,Number.MAX_SAFE_INTEGER);if(a===null){Pe(e),e.status(400).json({errorKind:"parse_error",error:"`offset` must be a non-negative safe integer",status:400});return}let c=Xr(t.query.maxBytes,1,Je);if(c===null){Pe(e),e.status(400).json({errorKind:"parse_error",error:`\`maxBytes\` must be a positive integer in [1, ${Je}]`,status:400});return}let d=s.forRequest({originatorClientId:i??void 0,route:n});try{let u=await d.resolve(o,"read"),l=await d.readBytesWindow(u,{offset:a??0,maxBytes:c??XI});Pe(e),e.status(200).json({kind:"file_bytes",path:er(t,u),offset:l.offset,sizeBytes:l.sizeBytes,returnedBytes:l.returnedBytes,truncated:l.truncated,contentBase64:l.buffer.toString("base64"),...l.hash?{hash:l.hash}:{}})}catch(u){Zt(e,u,n)}}async function ex(t,e,r){let n="GET /stat",s=qn(t,e);if(!s)return;let i=r.parseClientId(t,e);if(i===null)return;let o=Bn(e,t.query.path,"path",n);if(o===null)return;let a=s.forRequest({originatorClientId:i??void 0,route:n});try{let c=await a.resolve(o,"stat"),d=await a.stat(c);Pe(e),e.status(200).json({kind:"stat",path:er(t,c),type:d.kind,sizeBytes:d.sizeBytes,modifiedMs:d.modifiedMs})}catch(c){Zt(e,c,n)}}async function tx(t,e,r){let n="GET /list",s=qn(t,e);if(!s)return;let i=r.parseClientId(t,e);if(i===null)return;let o=Bn(e,t.query.path,"path",n);if(o===null)return;let a=x0(t.query.includeIgnored),c=s.forRequest({originatorClientId:i??void 0,route:n});try{let d=await c.resolve(o,"list"),u=await c.list(d,{includeIgnored:a,maxEntries:ld+1}),l=!1,p=u;p.length>ld&&(p=p.slice(0,ld),l=!0),Pe(e),e.status(200).json({kind:"list",path:er(t,d),entries:p,truncated:l,matchedIgnore:null})}catch(d){Zt(e,d,n)}}async function rx(t,e,r){let n="GET /glob",s=qn(t,e);if(!s)return;let i=r.parseClientId(t,e);if(i===null)return;let o=Bn(e,t.query.pattern,"pattern",n);if(o===null)return;let a=x0(t.query.includeIgnored),c=Xr(t.query.maxResults,1,I0);if(c===null){Pe(e),e.status(400).json({errorKind:"parse_error",error:`\`maxResults\` must be a positive integer in [1, ${I0}]`,status:400});return}let d=t.query.cwd,u=typeof d=="string"&&d.length>0?d:void 0,l=s.forRequest({originatorClientId:i??void 0,route:n}),p=performance.now();try{let f=u?await l.resolve(u,"list"):void 0,g=c??QI,v=await l.glob(o,{cwd:f,includeIgnored:a,maxResults:g+1}),x=v.length>g,P=(x?v.slice(0,g):v).map(q=>er(t,q));Pe(e),e.status(200).json({kind:"glob",pattern:o,cwd:u??"",matches:P,count:P.length,truncated:x,durationMs:Math.round(performance.now()-p)})}catch(f){Zt(e,f,n)}}function er(t,e){let r=t.app.locals.boundWorkspace;if(!r)throw new Error("bound workspace is not configured");let n=$n.relative(r,e);return n===""?".":$n.sep==="/"?n:n.split($n.sep).join("/")}function _0(t,e){t.get("/file",(r,n)=>YI(r,n,e)),t.get("/file/bytes",(r,n)=>ZI(r,n,e)),t.get("/stat",(r,n)=>ex(r,n,e)),t.get("/list",(r,n)=>tx(r,n,e)),t.get("/glob",(r,n)=>rx(r,n,e))}w();function k0(t,e){let r=t.app.locals.fsFactory;return r||(Pe(e),e.status(500).json({errorKind:"internal_error",error:"workspace filesystem factory is not configured",status:500}),null)}function Rt(t,e,r){return Pe(t),t.status(400).json({errorKind:"parse_error",error:r,status:400}),null}function A0(t,e,r,n){let s=t[e];return typeof s!="string"||s.length===0?Rt(r,n,`\`${e}\` must be a non-empty string`):s}function nx(t,e,r,n){let s=t[e];if(s!==void 0)return typeof s!="boolean"?Rt(r,n,`\`${e}\` must be a boolean`):s}function sx(t,e,r,n){let s=t[e];if(s!==void 0)return typeof s!="string"||s.length===0?Rt(r,n,`\`${e}\` must be a non-empty string`):s}function ix(t,e,r){let n=t.lineEnding;if(n!==void 0)return n!=="crlf"&&n!=="lf"?Rt(e,r,'`lineEnding` must be "lf" or "crlf"'):n}function R0(t,e,r){let n=t.expectedHash;return wr(n)?n:Rt(e,r,"`expectedHash` must match sha256:<64 lowercase hex chars>")}function ox(t,e,r){let n=t.expectedHash;if(n!==void 0)return wr(n)?n:Rt(e,r,"`expectedHash` must match sha256:<64 lowercase hex chars>")}function C0(t,e,r){if(t!==void 0)return e.bridge.knownClientIds().has(t)?t:(Pe(r),r.status(400).json({error:`Client id "${t}" is not registered for this workspace`,code:"invalid_client_id",clientId:t}),null)}async function ax(t,e,r){let n="POST /file/write",s=k0(t,e);if(!s)return;let i=r.safeBody(t),o=A0(i,"path",e,n);if(o===null)return;let a=i.content;if(typeof a!="string"){Rt(e,n,"`content` must be a string");return}let c=i.mode;if(c!=="create"&&c!=="replace"){Rt(e,n,'`mode` must be "create" or "replace"');return}let d=c,u=d==="replace"?R0(i,e,n):ox(i,e,n);if(u===null)return;let l=nx(i,"bom",e,n);if(l===null)return;let p=sx(i,"encoding",e,n);if(p===null)return;let f=ix(i,e,n);if(f===null)return;let g=r.parseClientId(t,e);if(g===null)return;let v=C0(g,r,e);if(v===null)return;let x=s.forRequest({originatorClientId:v,route:n});try{let O=await x.resolve(o,"write"),P=await x.writeTextAtomic(O,a,{mode:d,...u?{expectedHash:u}:{},...l!==void 0?{bom:l}:{},...p!==void 0?{encoding:p}:{},...f!==void 0?{lineEnding:f}:{}});Pe(e),e.status(P.created?201:200).json({kind:"file_write",path:er(t,O),mode:d,created:P.created,sizeBytes:P.sizeBytes,hash:P.hash,encoding:P.meta.encoding??"utf-8",bom:P.meta.bom===!0,lineEnding:P.meta.lineEnding,matchedIgnore:P.meta.matchedIgnore??null})}catch(O){Zt(e,O,n)}}async function cx(t,e,r){let n="POST /file/edit",s=k0(t,e);if(!s)return;let i=r.safeBody(t),o=A0(i,"path",e,n);if(o===null)return;let a=i.oldText;if(typeof a!="string"){Rt(e,n,"`oldText` must be a string");return}let c=i.newText;if(typeof c!="string"){Rt(e,n,"`newText` must be a string");return}let d=R0(i,e,n);if(d===null)return;let u=r.parseClientId(t,e);if(u===null)return;let l=C0(u,r,e);if(l===null)return;let p=s.forRequest({originatorClientId:l,route:n});try{let f=await p.resolve(o,"edit"),g=await p.editAtomic(f,a,c,{expectedHash:d});Pe(e),e.status(200).json({kind:"file_edit",path:er(t,f),replacements:1,sizeBytes:g.writtenBytes,hash:g.hash,encoding:g.meta?.encoding??"utf-8",bom:g.meta?.bom===!0,lineEnding:g.meta?.lineEnding??"lf",matchedIgnore:g.meta?.matchedIgnore??null})}catch(f){Zt(e,f,n)}}function T0(t,e){t.post("/file/write",e.mutate({strict:!0}),(r,n)=>ax(r,n,e)),t.post("/file/edit",e.mutate({strict:!0}),(r,n)=>cx(r,n,e))}w();import{promises as Qr,constants as P0}from"node:fs";import*as Ct from"node:path";async function O0(t){let e=t;for(;;)try{return await Qr.realpath(e)}catch(r){let n=r?.code;if(n!=="ENOENT"&&n!=="ENOTDIR"&&n!=="ELOOP")throw r;let s=Ct.dirname(e);if(s===e)throw r;e=s}}async function M0(t,e,r){let n=await O0(Ct.dirname(t));if(!(n===e||n.startsWith(e+Ct.sep)))throw new mt(t,"parent",`Workspace context file ${JSON.stringify(t)}'s parent moved outside the workspace between the pre-open canonicalize and the post-open verify (parent canonicalizes to ${JSON.stringify(n)}, workspace canonicalizes to ${JSON.stringify(e)}). Refusing to write \u2014 investigate the concurrent writer or the parent-directory permissions.`)}function Ci(t){let{boundWorkspace:e,contextFilename:r,statusProvider:n,isChannelLive:s,persistDisabledTools:i,queryWorkspaceStatus:o,invokeWorkspaceCommand:a,publishWorkspaceEvent:c}=t;return{async getWorkspaceMcpStatus(d){return o(ke.workspaceMcp,()=>Xi(e))},async getWorkspaceSkillsStatus(d){return o(ke.workspaceSkills,()=>Qi(e))},async getWorkspaceProvidersStatus(d){return o(ke.workspaceProviders,()=>Yi(e))},async getWorkspaceEnvStatus(d){let u=s?.()??!1;if(!n)return Zi(e,u);try{return await n.getEnvStatus(e,u)}catch(l){return D(`matilda serve: getEnvStatus failed: ${l instanceof Error?l.message:String(l)}`),Zi(e,u)}},async getWorkspacePreflightStatus(d){let u=s?.()??!1,l=eo(),p=[];if(n)try{p=await n.getDaemonPreflightCells(e)}catch(v){D(`matilda serve: getDaemonPreflightCells failed: ${v instanceof Error?v.message:String(v)}`)}let f=l,g;if(u)try{let v=await o(ke.workspacePreflight,()=>({cells:l}));if(v&&"cells"in v){let x=v;f=x.cells.filter(O=>O.locality!=="daemon"),g=x.errors}}catch(v){f=l;let x=Mt(v);g=[{kind:"preflight",status:"error",error:v instanceof Error?v.message:String(v),...x?{errorKind:x}:{}}]}return{v:ot,workspaceCwd:e,initialized:!0,acpChannelLive:u,cells:[...p,...f],...g&&g.length>0?{errors:g}:{}}},async getWorkspaceHooksStatus(d){return o(ke.workspaceHooks,()=>pn(e))},async getWorkspaceExtensionsStatus(d){return o(ke.workspaceExtensions,()=>ln(e))},async setWorkspaceToolEnabled(d,u,l){return await i(e,u,l),c({type:"tool_toggled",data:{toolName:u,enabled:l},originatorClientId:d.originatorClientId}),{toolName:u,enabled:l}},async initWorkspace(d,u){let l=r,p=Ct.resolve(e,l);if(!(p===e||p.startsWith(e+Ct.sep)))throw new Pr(l,e);let g=await Qr.realpath(e),v=await O0(Ct.dirname(p));if(!(v===g||v.startsWith(g+Ct.sep)))throw new mt(p,"parent",`Configured workspace context filename ${JSON.stringify(l)} has a parent path that resolves outside the bound workspace (parent canonicalizes to ${JSON.stringify(v)}, workspace canonicalizes to ${JSON.stringify(g)}). Refusing to write \u2014 replace any symlinked parent directory with a real directory before re-running init.`);try{let P=await Qr.lstat(p);if(P.isSymbolicLink())throw new mt(p,"target",`Workspace context file ${JSON.stringify(p)} is a symlink. Refusing to follow it for write \u2014 replace the symlink with a regular file (or remove it) before re-running init.`);if(!P.isFile())throw new mt(p,"target",`Workspace context file ${JSON.stringify(p)} is not a regular file (mode=${P.mode.toString(8)}). Refusing to proceed \u2014 FIFOs, sockets, and device nodes can block or misbehave on read/write.`)}catch(P){if(P instanceof mt||P?.code!=="ENOENT")throw P}let O="created";try{let P=await Qr.readFile(p,"utf8");if(P.trim().length>0){let q=Buffer.byteLength(P,"utf8");if(u.force!==!0)throw new ar(p,q);O="overwrote"}else O="noop"}catch(P){if(P instanceof ar||P?.code!=="ENOENT")throw P}if(O==="created"){let P;try{P=await Qr.open(p,"wx")}catch(q){throw q?.code==="EEXIST"?new cr(p,"eexist",`Workspace context file ${JSON.stringify(p)} appeared between our absence check and the create \u2014 refusing to proceed (a regular file or symlink was just placed at the target path, and following it could escape the workspace).`):q}try{await M0(p,g,P),await P.writeFile("","utf8")}finally{await P.close()}}else if(O==="overwrote"){let P;try{P=await Qr.open(p,P0.O_WRONLY|(P0.O_NOFOLLOW??0))}catch(q){let U=q?.code;throw U==="ELOOP"?new mt(p,"target",`Workspace context file ${JSON.stringify(p)} could not be opened with O_NOFOLLOW (ELOOP); the path may have been swapped to a symlink between the content check and the overwrite. Refusing to follow it.`):U==="ENOENT"?new cr(p,"enoent",`Workspace context file ${JSON.stringify(p)} was deleted between the content check and the overwrite (likely a concurrent writer). Refusing to recreate blindly; rerun init.`):q}try{await M0(p,g,P),await P.truncate(0)}finally{await P.close()}}return c({type:"workspace_initialized",data:{path:p,action:O},originatorClientId:d.originatorClientId}),{path:p,action:O}},async restartMcpServer(d,u,l){let p={serverName:u};l?.entryIndex!==void 0&&(p.entryIndex=l.entryIndex);let f;try{f=await a(le.workspaceMcpRestart,p,{timeoutMs:3e5})}catch(g){let v=g?.data;if(v&&typeof v=="object"){let x=v.errorKind,O=v.serverName;if(x==="mcp_server_not_found"&&typeof O=="string")throw new Mr(O);if(x==="mcp_restart_failed"&&typeof O=="string"){let P=v.mcpStatus;throw new Or(O,typeof P=="string"?P:"unknown")}}throw g}if("entries"in f){let g=Array.isArray(f.entries)?f.entries:[];Array.isArray(f.entries)||D(`matilda serve: pool restart response carried 'entries' field but it is not an array (server=${u}); treating as empty.`);for(let v of g){if(typeof v!="object"||v===null||typeof v.entryIndex!="number"){D(`matilda serve: skipping malformed pool restart entry (server=${u}): ${JSON.stringify(v)}`);continue}v.restarted?c({type:"mcp_server_restarted",data:{serverName:f.serverName,durationMs:v.durationMs??0,entryIndex:v.entryIndex},originatorClientId:d.originatorClientId}):c({type:"mcp_server_restart_refused",data:{serverName:f.serverName,reason:"restart_failed",entryIndex:v.entryIndex,...v.reason?{details:v.reason}:{}},originatorClientId:d.originatorClientId})}}else f.restarted===!0?c({type:"mcp_server_restarted",data:{serverName:f.serverName,durationMs:f.durationMs},originatorClientId:d.originatorClientId}):c({type:"mcp_server_restart_refused",data:{serverName:f.serverName,reason:f.reason},originatorClientId:d.originatorClientId});return f},async reload(d){if(t.reloadDaemonEnv)try{await t.reloadDaemonEnv(e)}catch(x){D(`matilda serve: daemon reload failed: ${x instanceof Error?x.message:String(x)}`)}let u=!1,l={updatedKeys:[],removedKeys:[]},p=[],f,g,v;try{let x=await a(le.workspaceReload,{cwd:e},{timeoutMs:3e4});u=!0,l=x.env,p=x.changedKeys,f=x.sessionsRefreshed,g=x.sessionsSkipped}catch(x){x instanceof ie?v="ACP child not running":(v=x instanceof Error?x.message:String(x),D(`matilda serve: reload failed: ${v}`))}return c({type:"settings_reloaded",data:{env:l,changedKeys:p,childReloaded:u,sessionsRefreshed:f,sessionsSkipped:g,childError:v},originatorClientId:d.originatorClientId}),{env:l,changedKeys:p,childReloaded:u,sessionsRefreshed:f,sessionsSkipped:g,childError:v}}}}w();var ux=new Set(["general.vimMode","general.terminalBell","general.preferredEditor","general.outputLanguage","ide.enabled","ui.showLineNumbers","ui.renderMode","ui.useTerminalBuffer","ui.hideBanner","ui.accessibility.enableLoadingPhrases","ui.enableWelcomeBack"]),lx=new Set(["ui.compactMode"]),pd=new Set(["workspace"]),D0=1024,px=new Set(["tools.approvalMode"]);function fx(){let t=new Set(ku().filter(e=>!ux.has(e)&&!px.has(e)));for(let e of lx)t.add(e);return t}function hx(t,e){let r=Tt(t),n=[];for(let i of e){let o=Vi(i);if(!o)continue;let a=ns(r.merged,i),c=ns(r.user.settings,i),d=ns(r.workspace.settings,i),u={effective:a!==void 0?a:o.default};c!==void 0&&(u.user=c),d!==void 0&&(u.workspace=d),n.push({key:i,type:o.type,label:o.label,category:o.category,...o.description?{description:o.description}:{},requiresRestart:o.requiresRestart,default:o.default,...o.options?.length?{options:o.options}:{},values:u})}let s=[];return r.corruptedPath&&s.push({type:"corrupted",recovered:r.wasRecovered}),{v:1,...s.length?{warnings:s}:{},settings:n}}function mx(t,e){switch(t.type){case"boolean":if(typeof e!="boolean")return"Value must be a boolean";break;case"number":if(typeof e!="number"||!Number.isFinite(e))return"Value must be a finite number";break;case"string":if(typeof e!="string")return"Value must be a string";if(e.length>D0)return`Value exceeds ${D0}-character limit`;break;case"enum":if(!t.options?.some(r=>r.value===e))return`Value must be one of: ${t.options?.map(n=>n.value).join(", ")??""}`;break;default:return`Settings of type '${t.type}' cannot be modified via this API`}}var gx={workspace:"Workspace"};function F0(t,e){let{boundWorkspace:r,mutate:n,safeBody:s,persistSetting:i,broadcastSettingsChanged:o,parseAndValidateClientId:a}=e,c=fx();t.get("/workspace/settings",(d,u)=>{try{let l=hx(r,c);u.status(200).json(l)}catch(l){D(`matilda serve: GET /workspace/settings error: ${l instanceof Error?l.message:String(l)}`),u.status(500).json({error:"Failed to load settings",code:"internal_error"})}}),t.post("/workspace/settings",n({strict:!0}),async(d,u)=>{let l=s(d),p=l.scope,f=l.key,g=l.value;if(typeof p!="string"||!pd.has(p)){u.status(400).json({error:`scope must be one of: ${[...pd].join(", ")}`,code:"invalid_scope"});return}if(typeof f!="string"||!f){u.status(400).json({error:"key is required and must be a string",code:"invalid_key"});return}if(!c.has(f)){u.status(400).json({error:`Setting "${f}" is not modifiable via this API`,code:"disallowed_key"});return}if(g==null){u.status(400).json({error:"value is required",code:"missing_value"});return}let v=Vi(f);if(!v){u.status(400).json({error:`Unknown setting: ${f}`,code:"unknown_key"});return}let x=mx(v,g);if(x){u.status(400).json({error:x,code:"invalid_value"});return}let O=a(d,u);if(O!==null){try{let P=gx[p];if(!P){u.status(400).json({error:`scope must be one of: ${[...pd].join(", ")}`,code:"invalid_scope"});return}await i(r,P,f,g)}catch(P){D(`matilda serve: POST /workspace/settings persist error (key=${f}, scope=${p}, workspace=${r}): ${P instanceof Error?P.message:String(P)}`),u.status(500).json({error:"Failed to persist setting",code:"persist_error"});return}try{o(f,g,p,O)}catch(P){D(`matilda serve: POST /workspace/settings broadcast error (key=${f}, scope=${p}): ${P instanceof Error?P.message:String(P)}`)}u.status(200).json({key:f,scope:p,value:g,requiresRestart:v.requiresRestart})}})}w();import*as N0 from"node:fs/promises";import*as $0 from"node:path";var vx="application/a2ui+json",yx="action",L0=15e3;function B0(t){return!!t&&(typeof t.command=="string"||typeof t.httpUrl=="string")}async function wx(t){try{let e=await N0.readFile($0.join(t,".matilda","settings.json"),"utf8"),r=JSON.parse(e);for(let[n,s]of Object.entries(r.mcpServers??{}))if(n.toLowerCase().includes("a2ui")&&B0(s))return s}catch{}return null}function bx(t){return typeof t.httpUrl=="string"?new wu(new URL(t.httpUrl)):new bu({command:t.command,args:t.args??[],...t.env?{env:{...process.env,...t.env}}:{},cwd:t.cwd})}function Sx(t){if(t.isError){let n=(t.content??[]).filter(s=>s.type==="text"&&typeof s.text=="string").map(s=>s.text).join("");throw new Error(`a2ui action tool returned error: ${n||"unknown error"}`)}let e=null,r="";for(let n of t.content??[])if(e===null&&n.type==="resource"&&n.resource?.mimeType===vx&&typeof n.resource.text=="string")try{let s=JSON.parse(n.resource.text);Array.isArray(s)&&(e=s)}catch{}else n.type==="text"&&typeof n.text=="string"&&(r+=n.text);return{commands:e,fallback:r}}async function Ex(t,e){let r=bx(t),n=new yu({name:"matilda-serve-a2ui",version:"0.0.1"});try{await n.connect(r,{timeout:L0});let s=await n.callTool({name:yx,arguments:{...e}},void 0,{timeout:L0});return Sx(s)}finally{await r.close().catch(()=>{}),await n.close().catch(()=>{})}}function q0(t,e){let{boundWorkspace:r,mutate:n,safeBody:s,getMcpServers:i}=e,o=e.callAction??Ex;t.post("/session/:id/a2ui-action",n(),async(a,c)=>{let d=s(a),u=d.name;if(typeof u!="string"||u.trim().length===0){c.status(400).json({error:"`name` is required"});return}let l=typeof d.surfaceId=="string"?d.surfaceId:void 0,p=d.context&&typeof d.context=="object"&&!Array.isArray(d.context)?d.context:void 0,f=null;try{let g=(await i(a)).filter(x=>x.name.toLowerCase().includes("a2ui")&&B0(x.config));f=(g.find(x=>x.mcpStatus==="connected")??g[0])?.config??null}catch{}if(f||(f=await wx(r)),!f){c.status(503).json({error:"no a2ui MCP server found (neither runtime-registered nor in workspace settings mcpServers)"});return}try{let{commands:g,fallback:v}=await o(f,{name:u.trim(),surfaceId:l,context:p});c.status(200).json({commands:g,fallback:v})}catch(g){D(`a2ui-action proxy failed: ${g instanceof Error?g.message:String(g)}`),c.status(502).json({error:"a2ui action call failed"})}})}w();var Ix=1e4,xx=1e3,_x=5*60*1e3;function kx(t,e){let r=e.endsWith("/")&&e.length>1?e.slice(0,-1):e;return t==="OPTIONS"||(t==="GET"||t==="HEAD")&&(r==="/health"||r==="/demo")||t==="POST"&&r.startsWith("/session/")&&r.endsWith("/heartbeat")||t==="GET"&&r.startsWith("/session/")&&r.endsWith("/events")||r==="/acp"||r.startsWith("/acp/")?null:t==="POST"&&r.startsWith("/session/")&&r.endsWith("/prompt")?"prompt":t!=="GET"&&t!=="HEAD"?"mutation":"read"}var Ax=128,Rx=/^[A-Za-z0-9._:-]+$/;function Cx(t){return t.startsWith("::ffff:")?t.slice(7):t}function Tx(t){let e=_t(t);return r=>{let n=r.get("x-matilda-client-id"),s=n&&n.length<=Ax&&Rx.test(n)?n:void 0;if(e)return s?`cid:${s}`:"anonymous";let i=Cx(r.socket?.remoteAddress??"unknown");return s?`${i}:${s}`:i}}var Px=100;function Mx(t){let e=new Map;return{log(r,n){let s=`${r}:${n}`,i=e.get(s);i||(i={count:0,suppressed:0},e.set(s,i)),i.count++,i.count===1||i.count%Px===0?(t(r,n,i.suppressed),i.suppressed=0):i.suppressed++},clear(){e.clear()}}}function j0(t){for(let[p,f]of Object.entries(t.tiers)){if(!Number.isFinite(f.max)||f.max<=0)throw new Error(`rate limit: ${p}.max must be a positive number, got ${f.max}`);if(!Number.isFinite(f.windowMs)||f.windowMs<=0)throw new Error(`rate limit: ${p}.windowMs must be a positive number, got ${f.windowMs}`)}let e=new Map,r=Tx(t.hostname),n={prompt:0,mutation:0,read:0},s={prompt:t.tiers.prompt.max/t.tiers.prompt.windowMs,mutation:t.tiers.mutation.max/t.tiers.mutation.windowMs,read:t.tiers.read.max/t.tiers.read.windowMs},i=!1,o=0,a=t.onLimitReached?Mx(t.onLimitReached):void 0;function c(){let p=Date.now();for(let[f,g]of e){let v=!0;for(let[x,O]of g)if(p-O.lastRefill<t.tiers[x].windowMs*2){v=!1;break}v&&e.delete(f)}}let d=setInterval(c,_x);d.unref();let u=(p,f,g)=>{try{if(i){g();return}let v=kx(p.method,p.path);if(v===null){g();return}o++,o%xx===0&&c();let x=r(p);if(l(x,v))g();else{let O=t.tiers[v],P=s[v],q=e.get(x)?.get(v),U=Math.ceil((1-(q?.tokens??0))/P),ae=Math.ceil(U/1e3);f.setHeader("Retry-After",String(ae)),f.setHeader("X-RateLimit-Limit",String(O.max)),f.setHeader("X-RateLimit-Remaining","0"),f.setHeader("X-RateLimit-Reset",String(Math.ceil((Date.now()+U)/1e3))),f.status(429).json({error:"Rate limit exceeded",code:"rate_limit_exceeded",tier:v,retryAfterMs:U})}}catch(v){t.onError?.(v,p.path),g()}};function l(p,f){if(i)return!0;let g=t.tiers[f],v=s[f],x=Date.now(),O=e.get(p);if(!O){if(e.size>=Ix)return t.onError?.(new Error(`rate limit bucket overflow: ${e.size} keys`),`tryConsume:${f}`),!0;O=new Map,e.set(p,O)}let P=O.get(f);P||(P={tokens:g.max,lastRefill:x},O.set(f,P));let q=Math.max(0,x-P.lastRefill);return P.tokens=Math.min(g.max,P.tokens+q*v),P.lastRefill=x,P.tokens>=1?(P.tokens-=1,!0):(n[f]++,a&&a.log(f,p),!1)}return{middleware:u,checkRate:l,reset(){e.clear(),n.prompt=0,n.mutation=0,n.read=0,o=0,a?.clear()},setDraining(p){i=p},dispose(){clearInterval(d),e.clear(),a?.clear()},getHitCounts(){return{...n}}}}var W0="_rateLimiter";function H0(t,e){t.locals[W0]=e}function U0(t){return t.locals[W0]}var wd=0;function Sd(){return wd}var Ox="MATILDA_CODE_BENCHMARK_API",Dx=1e3,V0=2e5;function Fx(){let e=0;return r=>{if(e+=1,e===1||e%100===0){let n=r.data,s=[];n?.errorKind&&s.push(`errorKind=${n.errorKind}`),n?.intent&&s.push(`intent=${n.intent}`),n?.pathHash&&s.push(`pathHash=${n.pathHash}`);let i=s.length>0?` (${s.join(" ")})`:"";D(`matilda serve: fs audit emit is the default no-op \u2014 ${e} event(s) dropped so far. Latest type=${r.type}${i}. Inject deps.fsFactory in createServeApp to wire audit into the EventBus.`)}}}var z0=!1;function Ed(t){return t.injected?t.injected:dd({boundWorkspace:t.boundWorkspace,trusted:t.trusted,emit:t.emit??Fx()})}var Lx=20,Nx=100,Kr=class extends Error{constructor(e){super(`Invalid cursor: "${e}" is not a valid session cursor`),this.name="InvalidCursorError"}};async function zc(t,e,r){let n=Math.min(Math.max(r?.size??Lx,1),Nx),s=r?.cursor===void 0,i=new tn(e),o;try{o=await i.listSessions({cursor:r?.cursor,size:n})}catch(l){throw l instanceof au&&r?.cursor!==void 0?new Kr(r.cursor):l}let a=new Map;for(let l of o.items)a.set(l.sessionId,{sessionId:l.sessionId,workspaceCwd:l.cwd,createdAt:l.startTime,updatedAt:new Date(l.mtime).toISOString(),title:l.customTitle??l.prompt,clientCount:0,hasActivePrompt:!1});let c=t.listWorkspaceSessions(e);for(let l of c){let p=a.get(l.sessionId);p?a.set(l.sessionId,{...p,...l,createdAt:p.createdAt,title:l.title??p.title,updatedAt:l.updatedAt??p.updatedAt,clientCount:l.clientCount,hasActivePrompt:l.hasActivePrompt}):s&&!await i.sessionExists(l.sessionId)&&a.set(l.sessionId,{...l,createdAt:l.createdAt,clientCount:l.clientCount,hasActivePrompt:l.hasActivePrompt})}let d=[...a.values()].sort((l,p)=>{let f=Date.parse(l.updatedAt??l.createdAt);return Date.parse(p.updatedAt??p.createdAt)-f}),u=o.nextCursor!=null?String(o.nextCursor):void 0;return{sessions:d,nextCursor:u}}var $x=["protocol","baseUrl","apiKey","models","advancedConfig"];function Bx(t){let e=$x.filter(r=>lu(t,r));return{id:t.id,label:t.label,description:t.description,...t.uiGroup?{uiGroup:t.uiGroup}:{},protocol:t.protocol,...t.protocolOptions?{protocolOptions:[...t.protocolOptions]}:{},...t.baseUrl!==void 0?{baseUrl:t.baseUrl}:{},...typeof t.envKey=="string"?{envKey:t.envKey}:{},...t.models?{models:t.models.map(r=>({id:r.id,...r.contextWindowSize!==void 0?{contextWindowSize:r.contextWindowSize}:{},...r.enableThinking!==void 0?{enableThinking:r.enableThinking}:{},...r.modalities?{modalities:r.modalities}:{},...r.description?{description:r.description}:{}}))}:{},...t.modelsEditable!==void 0?{modelsEditable:t.modelsEditable}:{},...t.apiKeyPlaceholder?{apiKeyPlaceholder:t.apiKeyPlaceholder}:{},...typeof t.documentationUrl=="string"?{documentationUrl:t.documentationUrl}:{},...t.showAdvancedConfig!==void 0?{showAdvancedConfig:t.showAdvancedConfig}:{},...t.uiLabels?{uiLabels:t.uiLabels}:{},steps:e}}function qx(t){let e=Hi.map(Bx),r=n=>e.filter(s=>s.uiGroup===n).map(s=>s.id);return{v:1,workspaceCwd:t,providers:e,groups:[{id:"third-party",label:"Third-party Providers",description:"Choose a built-in provider and connect with an API key",providerIds:r("third-party")},{id:"custom",label:"Custom Provider",description:"Manually connect a local server, proxy, or unsupported provider",providerIds:r("custom")}]}}function jx(t){if(!Array.isArray(t))return;let e=t.map(r=>typeof r=="string"?r.trim():"").filter(r=>r.length>0);return e.length>0?[...new Set(e)]:void 0}function G0(t,e){if(!(typeof t!="number"||!Number.isInteger(t)||!Number.isFinite(t)||t<=0||t>e))return t}function Wx(t){let e=t.split(":");if(e.length!==2)return;let[r,n]=e;if(!/^[0-9a-f]{1,4}$/i.test(r)||!/^[0-9a-f]{1,4}$/i.test(n))return;let s=Number.parseInt(r,16),i=Number.parseInt(n,16);return`${s>>8&255}.${s&255}.${i>>8&255}.${i&255}`}function Hx(t){let e=t.split(":",1)[0];if(!(!e||!/^[0-9a-f]{1,4}$/i.test(e)))return Number.parseInt(e,16)}function bd(t){let r=(t.endsWith(".")?t.slice(0,-1):t).toLowerCase();if(r==="localhost"||r.endsWith(".localhost"))return!0;let n=r.startsWith("[")&&r.endsWith("]")?r.slice(1,-1):r,s=vd.isIP(n);if(s===4){let i=n.split(".").map(c=>Number(c)),[o,a]=i;return o===0||o===10||o===127||o===100&&a!==void 0&&a>=64&&a<=127||o===169&&a===254||o===172&&a!==void 0&&a>=16&&a<=31||o===192&&a===168}if(s===6){if(n==="::"||n==="::1")return!0;let i=Hx(n);if(i!==void 0&&(i>=65152&&i<=65215||(i&65024)===64512))return!0;if(n.startsWith("::ffff:")){let o=n.slice(7);if(vd.isIP(o)===4)return bd(o);let a=Wx(o);return a?bd(a):!0}}return!1}function Ux(t,e){if(t==null)return;if(typeof t!="string")return null;let r=t.trim();if(!r)return;let n;try{n=new URL(r)}catch{return null}return n.protocol!=="http:"&&n.protocol!=="https:"||n.username||n.password||!e&&bd(n.hostname)?null:n.toString().replace(/\/$/,"")}function Vx(t,e){let r=t.providerId,n=t.apiKey;if(typeof r!="string"||r.trim().length===0||typeof n!="string"||n.trim().length===0)return{ok:!1,code:"invalid_request",error:"`providerId` and `apiKey` are required"};let s=t.protocol,i=Ux(t.baseUrl,e?.allowPrivateBaseUrl===!0);if(i===null)return{ok:!1,code:"invalid_base_url",error:"`baseUrl` must be an http(s) URL without credentials or blocked private-network host"};let o=jx(t.modelIds),a=t.advancedConfig&&typeof t.advancedConfig=="object"?t.advancedConfig:void 0,c=a?.multimodal&&typeof a.multimodal=="object"?a.multimodal:void 0,d=G0(a?.contextWindowSize,1e7),u=G0(a?.maxTokens,1e7),l=a?{...typeof a.enableThinking=="boolean"?{enableThinking:a.enableThinking}:{},...c?{multimodal:{...typeof c.image=="boolean"?{image:c.image}:{},...typeof c.pdf=="boolean"?{pdf:c.pdf}:{},...typeof c.audio=="boolean"?{audio:c.audio}:{},...typeof c.video=="boolean"?{video:c.video}:{}}}:{},...d!==void 0?{contextWindowSize:d}:{},...u!==void 0?{maxTokens:u}:{}}:void 0;return{ok:!0,value:{providerId:r.trim(),...typeof s=="string"&&s.trim()?{protocol:s.trim()}:{},...i?{baseUrl:i}:{},apiKey:n,...o?{modelIds:o}:{},...l?{advancedConfig:l}:{}}}}function zx(t){let e=t.path.replace(/\/$/,"")||"/";if(t.method==="POST"&&e==="/session")return{route:"POST /session"};if(t.method==="POST"&&e==="/sessions/delete")return{route:"POST /sessions/delete"};if(t.method==="GET"&&e==="/daemon/status")return{route:"GET /daemon/status"};let r=e.match(/^\/session\/([^/]+)\/(load|resume|prompt|cancel|recap|btw|mid-turn-message|model|shell|detach|rewind|approval-mode|language|a2ui-action)$/),n=r?.[1],s=r?.[2];if(n&&s&&t.method==="POST")return{route:`POST /session/:id/${s}`,sessionId:n};let i=e.match(/^\/session\/([^/]+)\/metadata$/);if(i?.[1]&&t.method==="PATCH")return{route:"PATCH /session/:id/metadata",sessionId:i[1]};let o=e.match(/^\/session\/([^/]+)\/permission\/([^/]+)$/);if(o?.[1]&&o?.[2]&&t.method==="POST"){let g=o[2];return{route:"POST /session/:id/permission/:requestId",sessionId:o[1],...g.length<=Mi&&Oi.test(g)?{permissionRequestId:g}:{}}}let a=e.match(/^\/permission\/([^/]+)$/);if(a?.[1]&&t.method==="POST"){let g=a[1];return{route:"POST /permission/:requestId",...g.length<=Mi&&Oi.test(g)?{permissionRequestId:g}:{}}}let d=e.match(/^\/session\/([^/]+)$/)?.[1];if(d&&t.method==="DELETE")return{route:"DELETE /session/:id",sessionId:d};if(t.method==="GET"&&/^\/workspace\/[^/]+\/sessions$/.test(e))return{route:"GET /workspace/:id/sessions"};if(t.method==="POST"&&e==="/workspace/init")return{route:"POST /workspace/init"};if(t.method==="POST"&&e==="/workspace/reload")return{route:"POST /workspace/reload"};if(e.match(/^\/workspace\/mcp\/([^/]+)\/restart$/)?.[1]&&t.method==="POST")return{route:"POST /workspace/mcp/:server/restart"};if(t.method==="POST"&&e==="/workspace/mcp/servers")return{route:"POST /workspace/mcp/servers"};if(e.match(/^\/workspace\/mcp\/servers\/([^/]+)$/)?.[1]&&t.method==="DELETE")return{route:"DELETE /workspace/mcp/servers/:name"};if(t.method==="POST"&&e==="/workspace/auth/device-flow")return{route:"POST /workspace/auth/device-flow"};if(e.match(/^\/workspace\/auth\/device-flow\/([^/]+)$/)?.[1]&&t.method==="DELETE")return{route:"DELETE /workspace/auth/device-flow/:id"};if(e.match(/^\/workspace\/tools\/([^/]+)\/enable$/)?.[1]&&t.method==="POST")return{route:"POST /workspace/tools/:name/enable"};if(e==="/workspace/settings"){if(t.method==="GET")return{route:"GET /workspace/settings"};if(t.method==="POST")return{route:"POST /workspace/settings"}}}function Gx(t){let e=Qn(t);return(r,n,s)=>{let i=zx(r);if(!i){s();return}let o=r.get(ev),a=o!==void 0&&o!==""&&o.length<=Mi&&Oi.test(o)?o:void 0,c=Date.now();$d({method:r.method,route:i.route,workspaceHash:e,...i.sessionId?{sessionId:i.sessionId}:{},...i.permissionRequestId?{permissionRequestId:i.permissionRequestId}:{},...a?{clientId:a}:{}},async d=>await new Promise((u,l)=>{let p=!1,f=()=>{p||(p=!0,Bd(d,n.statusCode),Ud(Date.now()-c,i.route,n.statusCode),u())};n.once("finish",f),n.once("close",f);try{s()}catch(g){ji(d,g),l(g)}})).catch(s)}}var Pi=class extends Error{deadlineMs;constructor(e){super(`prompt exceeded the ${e}ms deadline`),this.name="PromptDeadlineExceededError",this.deadlineMs=e}};function K0(t,e){if(!(t===void 0||!Number.isFinite(t)||t<=0))return e===void 0||!Number.isFinite(e)||e<=0?t:Math.min(t,e)}var Kx=5;function Jx(t){return t===void 0?Kx:t===0||t===Number.POSITIVE_INFINITY?null:t}function Id(t,e=()=>t.port,r={}){let n=(0,yd.default)(),s=r.boundWorkspace??Qe(t.workspace??process.cwd());!r.fsFactory&&!r.bridge&&!z0&&(z0=!0,process.stderr.write(`matilda serve: createServeApp default fsFactory uses trusted=false \u2014 agent ACP writeTextFile calls will reject with untrusted_workspace. Inject deps.fsFactory (with explicit trust) or deps.bridge to override.
|
|
715
|
+
`),originalLineCount:s}}function $I(t){if(t.length===0)return!1;let e=t.subarray(0,Math.min(4,t.length));if(e.length>=4&&(e[0]===255&&e[1]===254&&e[2]===0&&e[3]===0||e[0]===0&&e[1]===0&&e[2]===254&&e[3]===255)||e.length>=3&&e[0]===239&&e[1]===187&&e[2]===191||e.length>=2&&(e[0]===255&&e[1]===254||e[0]===254&&e[1]===255))return!1;let n=Math.min(4096,t.length),s=0;for(let i=0;i<n;i++){if(t[i]===0)return!0;(t[i]<9||t[i]>13&&t[i]<32)&&s++}return s/n>.3}async function h0(t,e){let r=await cd(t);if(e!==void 0&&r.meta.hash!==e)throw new B("hash_mismatch",`expected ${e}, found ${r.meta.hash}`,{hint:"re-read the file and retry with the latest hash"});return r.meta}function sd(t,e){return{encoding:e.encoding??t?.encoding??"utf-8",bom:e.bom??t?.bom??!1,lineEnding:e.lineEnding??t?.lineEnding??"lf"}}async function id(t){let e=t.target,r=Xe.dirname(e),n=await ye.lstat(r);if(n.isSymbolicLink())throw new B("symlink_escape",`parent path is a symlink: ${r}`,{hint:"re-resolve the target after detecting parent-symlink swaps"});if(!n.isDirectory())throw new B("parse_error",`parent path is not a directory: ${r}`);let s=Xe.join(r,`.${Xe.basename(e)}.${process.pid}.${OI(6).toString("hex")}.tmp`),i=!1,o,a;try{o=await BI(s),i=!0;let c=await qI({targetPath:e,tmpPath:s,content:t.content,meta:t.meta,handle:o});a=c.stat;let d=await jI({target:e,mode:t.mode,expectedHash:t.expectedHash});return await VI(o,d.mode??384),await m0(s,a),await o.close(),o=void 0,await m0(s,a),t.mode==="create"?await zI(s,e):await GI(s,e,3,50),i=!1,await UI(r),c}catch(c){if(await o?.close().catch(()=>{}),i)try{await ye.unlink(s)}catch{}throw c}}async function BI(t){return ye.open(t,"wx",384)}async function qI(t){let e=gu(t.targetPath,t.content,S0(t.meta));Qt(e.length),await t.handle.writeFile(e),await HI(t.handle);let r=await ye.lstat(t.tmpPath),n=await t.handle.stat();if(jt(n,r,t.tmpPath,"write"),r.isSymbolicLink())throw new B("symlink_escape",`temporary path became a symlink: ${t.tmpPath}`,{hint:"temp-file race detected before final rename"});if(!r.isFile())throw new B("parse_error",`temporary path is not a regular file: ${t.tmpPath}`);return{sizeBytes:e.length,hash:ud(e),stat:r}}async function b0(t){try{throw(await ye.lstat(t)).isSymbolicLink()?new B("symlink_escape",`path is a symlink and cannot be created over: ${t}`,{hint:"remove the symlink or resolve the target explicitly"}):new B("file_already_exists",`file already exists: ${t}`)}catch(e){if(e?.code==="ENOENT")return;throw e}}async function jI(t){if(t.mode==="create")return await b0(t.target),{};if(t.mode==="overwrite"){let n;try{n=await ye.lstat(t.target)}catch(s){if(s?.code==="ENOENT")return{};throw s}if(n.isSymbolicLink())throw new B("symlink_escape",`path is a symlink and cannot be overwritten atomically: ${t.target}`,{hint:"re-resolve the target file instead of writing through a link"});if(!n.isFile())throw new B("parse_error",`path is not a regular file: ${t.target}`);return{mode:n.mode&4095}}if(!wr(t.expectedHash))throw new B("parse_error",'expectedHash is required when mode is "replace"');let e=await ye.lstat(t.target);if(e.isSymbolicLink())throw new B("symlink_escape",`path is a symlink and cannot be replaced atomically: ${t.target}`,{hint:"re-resolve the target file instead of writing through a link"});if(!e.isFile())throw new B("parse_error",`path is not a regular file: ${t.target}`);let r=await WI(t.target,e);if(r!==t.expectedHash)throw new B("hash_mismatch",`expected ${t.expectedHash}, found ${r}`,{hint:"re-read the file and retry with the latest hash"});return{mode:e.mode&4095}}async function WI(t,e){let r=await ye.open(t,"r"),n=w0("sha256"),s;try{s=await r.stat(),jt(e,s,t,"read");let o=Buffer.allocUnsafe(64*1024),a=0;for(;a<s.size;){let c=await r.read(o,0,Math.min(o.length,s.size-a),a);if(c.bytesRead===0)break;n.update(o.subarray(0,c.bytesRead)),a+=c.bytesRead}}finally{await r.close()}if(s===void 0)throw new B("internal_error",`failed to stat opened file: ${t}`);let i=await ye.lstat(t);if(jt(e,i,t,"read"),i.size!==s.size||i.mtimeMs!==s.mtimeMs)throw new B("hash_mismatch",`file changed during hash: ${t}`,{hint:"retry after re-reading the latest file hash"});return`sha256:${n.digest("hex")}`}function ud(t){return`sha256:${w0("sha256").update(t).digest("hex")}`}function jt(t,e,r,n){let s=Jr(t.dev),i=Jr(e.dev),o=Jr(t.ino),a=Jr(e.ino);if(s!==0n&&i!==0n&&o!==0n&&a!==0n&&(s!==i||o!==a))throw new B("symlink_escape",`path changed during ${n}: ${r}`,{hint:"TOCTOU swap detected via device/inode comparison"})}function Jr(t){return typeof t=="bigint"?t:BigInt(t)}async function HI(t){try{await t.sync()}catch{}}async function UI(t){let e;try{e=await ye.open(t,"r"),await e.sync()}catch{}finally{await e?.close().catch(()=>{})}}async function VI(t,e){try{await t.chmod(e)}catch{}}async function m0(t,e){let r=await ye.lstat(t);if(r.isSymbolicLink())throw new B("symlink_escape",`temporary path is a symlink: ${t}`,{hint:"temp-file race detected before final rename"});if(!r.isFile())throw new B("parse_error",`temporary path is not a regular file: ${t}`);jt(e,r,t,"write")}async function zI(t,e){try{await ye.link(t,e)}catch(r){throw r?.code==="EEXIST"?new B("file_already_exists",`file already exists: ${e}`):r}await ye.unlink(t).catch(()=>{})}async function GI(t,e,r,n){for(let s=0;s<=r;s++)try{await ye.rename(t,e);return}catch(i){let o=i?.code;if(!(o==="EPERM"||o==="EACCES")||s===r)throw i;await new Promise(c=>setTimeout(c,n*2**s))}}function KI(t,e){let r=0,n=0;for(;;){let s=t.indexOf(e,n);if(s===-1)return r;r+=1,n=s+e.length}}function JI(t,e){if(t.length<=e)return t;let r=e;for(;r>0&&(t[r]&192)===128;)r--;return t.subarray(0,r)}async function g0(t,e){let r=await ye.lstat(t);if(r.isSymbolicLink())throw new B("symlink_escape",`path was replaced with a symlink during read: ${t}`,{hint:"TOCTOU swap detected via post-read lstat"});let n=Jr(e),s=Jr(r.ino);if(n!==0n&&s!==0n&&n!==s)throw new B("symlink_escape",`path inode changed during read: ${t}`,{hint:"TOCTOU swap detected via inode comparison"})}async function v0(t){let e;try{e=await ye.lstat(t)}catch(r){if(r?.code==="ENOENT")return;throw r}if(e.isSymbolicLink())throw new B("symlink_escape",`path was replaced with a symlink before write: ${t}`,{hint:"TOCTOU swap detected via pre-write lstat \u2014 re-resolve before retrying"})}function y0(t){return t.isSymbolicLink()?"symlink":t.isDirectory()?"directory":t.isFile()?"file":"other"}function S0(t){let e={};return t.bom!==void 0&&(e.bom=t.bom),t.encoding&&(e.encoding=t.encoding),t.lineEnding&&(e.lineEnding=t.lineEnding),Object.keys(e).length>0?e:void 0}w();import*as $n from"node:path";var ld=2e3,E0=2e3,XI=64*1024,QI=5e3,I0=5e4;function Pe(t){t.set("Cache-Control","no-store"),t.set("X-Content-Type-Options","nosniff")}function Zt(t,e,r){if(Pe(t),Oc(e)){let n=e;t.status(n.status).json({errorKind:n.kind,error:n.message,hint:n.hint,status:n.status});return}D(`matilda serve: ${r} unexpected error: ${e instanceof Error?e.message:String(e)}`),t.status(500).json({errorKind:"internal_error",error:e instanceof Error?e.message:String(e),status:500})}function Xr(t,e,r){if(t===void 0)return;if(typeof t!="string"||!/^\d+$/.test(t))return null;let n=Number.parseInt(t,10);return!Number.isSafeInteger(n)||n<e||n>r?null:n}function x0(t){return t==="1"||t==="true"}function Bn(t,e,r,n){return typeof e!="string"||e.length===0?(Pe(t),t.status(400).json({errorKind:"parse_error",error:`${r} query parameter is required`,status:400}),D(`matilda serve: ${n} rejected request missing required ?${r}`),null):e}function qn(t,e){let r=t.app.locals.fsFactory;return r||(Pe(e),e.status(500).json({errorKind:"internal_error",error:"workspace filesystem factory is not configured",status:500}),null)}async function YI(t,e,r){let n="GET /file",s=qn(t,e);if(!s)return;let i=r.parseClientId(t,e);if(i===null)return;let o=Bn(e,t.query.path,"path",n);if(o===null)return;let a=Xr(t.query.maxBytes,1,256*1024);if(a===null){Pe(e),e.status(400).json({errorKind:"parse_error",error:"`maxBytes` must be a positive integer in [1, 262144]",status:400});return}let c=Xr(t.query.line,1,Number.MAX_SAFE_INTEGER);if(c===null){Pe(e),e.status(400).json({errorKind:"parse_error",error:"`line` must be a positive integer",status:400});return}let d=Xr(t.query.limit,1,E0);if(d===null){Pe(e),e.status(400).json({errorKind:"parse_error",error:`\`limit\` must be a positive integer in [1, ${E0}]`,status:400});return}let u=s.forRequest({originatorClientId:i??void 0,route:n});try{let l=await u.resolve(o,"read"),p=await u.readText(l,{maxBytes:a,line:c,limit:d}),f=Buffer.byteLength(p.content,"utf-8");Pe(e),e.status(200).json({kind:"file",path:er(t,l),content:p.content,encoding:p.meta.encoding??"utf-8",bom:p.meta.bom===!0,lineEnding:p.meta.lineEnding,sizeBytes:p.meta.sizeBytes??f,returnedBytes:f,truncated:p.meta.truncated===!0,hash:p.meta.hash,matchedIgnore:p.meta.matchedIgnore??null,originalLineCount:p.meta.originalLineCount??null})}catch(l){Zt(e,l,n)}}async function ZI(t,e,r){let n="GET /file/bytes",s=qn(t,e);if(!s)return;let i=r.parseClientId(t,e);if(i===null)return;let o=Bn(e,t.query.path,"path",n);if(o===null)return;let a=Xr(t.query.offset,0,Number.MAX_SAFE_INTEGER);if(a===null){Pe(e),e.status(400).json({errorKind:"parse_error",error:"`offset` must be a non-negative safe integer",status:400});return}let c=Xr(t.query.maxBytes,1,Je);if(c===null){Pe(e),e.status(400).json({errorKind:"parse_error",error:`\`maxBytes\` must be a positive integer in [1, ${Je}]`,status:400});return}let d=s.forRequest({originatorClientId:i??void 0,route:n});try{let u=await d.resolve(o,"read"),l=await d.readBytesWindow(u,{offset:a??0,maxBytes:c??XI});Pe(e),e.status(200).json({kind:"file_bytes",path:er(t,u),offset:l.offset,sizeBytes:l.sizeBytes,returnedBytes:l.returnedBytes,truncated:l.truncated,contentBase64:l.buffer.toString("base64"),...l.hash?{hash:l.hash}:{}})}catch(u){Zt(e,u,n)}}async function ex(t,e,r){let n="GET /stat",s=qn(t,e);if(!s)return;let i=r.parseClientId(t,e);if(i===null)return;let o=Bn(e,t.query.path,"path",n);if(o===null)return;let a=s.forRequest({originatorClientId:i??void 0,route:n});try{let c=await a.resolve(o,"stat"),d=await a.stat(c);Pe(e),e.status(200).json({kind:"stat",path:er(t,c),type:d.kind,sizeBytes:d.sizeBytes,modifiedMs:d.modifiedMs})}catch(c){Zt(e,c,n)}}async function tx(t,e,r){let n="GET /list",s=qn(t,e);if(!s)return;let i=r.parseClientId(t,e);if(i===null)return;let o=Bn(e,t.query.path,"path",n);if(o===null)return;let a=x0(t.query.includeIgnored),c=s.forRequest({originatorClientId:i??void 0,route:n});try{let d=await c.resolve(o,"list"),u=await c.list(d,{includeIgnored:a,maxEntries:ld+1}),l=!1,p=u;p.length>ld&&(p=p.slice(0,ld),l=!0),Pe(e),e.status(200).json({kind:"list",path:er(t,d),entries:p,truncated:l,matchedIgnore:null})}catch(d){Zt(e,d,n)}}async function rx(t,e,r){let n="GET /glob",s=qn(t,e);if(!s)return;let i=r.parseClientId(t,e);if(i===null)return;let o=Bn(e,t.query.pattern,"pattern",n);if(o===null)return;let a=x0(t.query.includeIgnored),c=Xr(t.query.maxResults,1,I0);if(c===null){Pe(e),e.status(400).json({errorKind:"parse_error",error:`\`maxResults\` must be a positive integer in [1, ${I0}]`,status:400});return}let d=t.query.cwd,u=typeof d=="string"&&d.length>0?d:void 0,l=s.forRequest({originatorClientId:i??void 0,route:n}),p=performance.now();try{let f=u?await l.resolve(u,"list"):void 0,g=c??QI,v=await l.glob(o,{cwd:f,includeIgnored:a,maxResults:g+1}),x=v.length>g,P=(x?v.slice(0,g):v).map(q=>er(t,q));Pe(e),e.status(200).json({kind:"glob",pattern:o,cwd:u??"",matches:P,count:P.length,truncated:x,durationMs:Math.round(performance.now()-p)})}catch(f){Zt(e,f,n)}}function er(t,e){let r=t.app.locals.boundWorkspace;if(!r)throw new Error("bound workspace is not configured");let n=$n.relative(r,e);return n===""?".":$n.sep==="/"?n:n.split($n.sep).join("/")}function _0(t,e){t.get("/file",(r,n)=>YI(r,n,e)),t.get("/file/bytes",(r,n)=>ZI(r,n,e)),t.get("/stat",(r,n)=>ex(r,n,e)),t.get("/list",(r,n)=>tx(r,n,e)),t.get("/glob",(r,n)=>rx(r,n,e))}w();function k0(t,e){let r=t.app.locals.fsFactory;return r||(Pe(e),e.status(500).json({errorKind:"internal_error",error:"workspace filesystem factory is not configured",status:500}),null)}function Rt(t,e,r){return Pe(t),t.status(400).json({errorKind:"parse_error",error:r,status:400}),null}function A0(t,e,r,n){let s=t[e];return typeof s!="string"||s.length===0?Rt(r,n,`\`${e}\` must be a non-empty string`):s}function nx(t,e,r,n){let s=t[e];if(s!==void 0)return typeof s!="boolean"?Rt(r,n,`\`${e}\` must be a boolean`):s}function sx(t,e,r,n){let s=t[e];if(s!==void 0)return typeof s!="string"||s.length===0?Rt(r,n,`\`${e}\` must be a non-empty string`):s}function ix(t,e,r){let n=t.lineEnding;if(n!==void 0)return n!=="crlf"&&n!=="lf"?Rt(e,r,'`lineEnding` must be "lf" or "crlf"'):n}function R0(t,e,r){let n=t.expectedHash;return wr(n)?n:Rt(e,r,"`expectedHash` must match sha256:<64 lowercase hex chars>")}function ox(t,e,r){let n=t.expectedHash;if(n!==void 0)return wr(n)?n:Rt(e,r,"`expectedHash` must match sha256:<64 lowercase hex chars>")}function C0(t,e,r){if(t!==void 0)return e.bridge.knownClientIds().has(t)?t:(Pe(r),r.status(400).json({error:`Client id "${t}" is not registered for this workspace`,code:"invalid_client_id",clientId:t}),null)}async function ax(t,e,r){let n="POST /file/write",s=k0(t,e);if(!s)return;let i=r.safeBody(t),o=A0(i,"path",e,n);if(o===null)return;let a=i.content;if(typeof a!="string"){Rt(e,n,"`content` must be a string");return}let c=i.mode;if(c!=="create"&&c!=="replace"){Rt(e,n,'`mode` must be "create" or "replace"');return}let d=c,u=d==="replace"?R0(i,e,n):ox(i,e,n);if(u===null)return;let l=nx(i,"bom",e,n);if(l===null)return;let p=sx(i,"encoding",e,n);if(p===null)return;let f=ix(i,e,n);if(f===null)return;let g=r.parseClientId(t,e);if(g===null)return;let v=C0(g,r,e);if(v===null)return;let x=s.forRequest({originatorClientId:v,route:n});try{let O=await x.resolve(o,"write"),P=await x.writeTextAtomic(O,a,{mode:d,...u?{expectedHash:u}:{},...l!==void 0?{bom:l}:{},...p!==void 0?{encoding:p}:{},...f!==void 0?{lineEnding:f}:{}});Pe(e),e.status(P.created?201:200).json({kind:"file_write",path:er(t,O),mode:d,created:P.created,sizeBytes:P.sizeBytes,hash:P.hash,encoding:P.meta.encoding??"utf-8",bom:P.meta.bom===!0,lineEnding:P.meta.lineEnding,matchedIgnore:P.meta.matchedIgnore??null})}catch(O){Zt(e,O,n)}}async function cx(t,e,r){let n="POST /file/edit",s=k0(t,e);if(!s)return;let i=r.safeBody(t),o=A0(i,"path",e,n);if(o===null)return;let a=i.oldText;if(typeof a!="string"){Rt(e,n,"`oldText` must be a string");return}let c=i.newText;if(typeof c!="string"){Rt(e,n,"`newText` must be a string");return}let d=R0(i,e,n);if(d===null)return;let u=r.parseClientId(t,e);if(u===null)return;let l=C0(u,r,e);if(l===null)return;let p=s.forRequest({originatorClientId:l,route:n});try{let f=await p.resolve(o,"edit"),g=await p.editAtomic(f,a,c,{expectedHash:d});Pe(e),e.status(200).json({kind:"file_edit",path:er(t,f),replacements:1,sizeBytes:g.writtenBytes,hash:g.hash,encoding:g.meta?.encoding??"utf-8",bom:g.meta?.bom===!0,lineEnding:g.meta?.lineEnding??"lf",matchedIgnore:g.meta?.matchedIgnore??null})}catch(f){Zt(e,f,n)}}function T0(t,e){t.post("/file/write",e.mutate({strict:!0}),(r,n)=>ax(r,n,e)),t.post("/file/edit",e.mutate({strict:!0}),(r,n)=>cx(r,n,e))}w();import{promises as Qr,constants as P0}from"node:fs";import*as Ct from"node:path";async function O0(t){let e=t;for(;;)try{return await Qr.realpath(e)}catch(r){let n=r?.code;if(n!=="ENOENT"&&n!=="ENOTDIR"&&n!=="ELOOP")throw r;let s=Ct.dirname(e);if(s===e)throw r;e=s}}async function M0(t,e,r){let n=await O0(Ct.dirname(t));if(!(n===e||n.startsWith(e+Ct.sep)))throw new mt(t,"parent",`Workspace context file ${JSON.stringify(t)}'s parent moved outside the workspace between the pre-open canonicalize and the post-open verify (parent canonicalizes to ${JSON.stringify(n)}, workspace canonicalizes to ${JSON.stringify(e)}). Refusing to write \u2014 investigate the concurrent writer or the parent-directory permissions.`)}function Ci(t){let{boundWorkspace:e,contextFilename:r,statusProvider:n,isChannelLive:s,persistDisabledTools:i,queryWorkspaceStatus:o,invokeWorkspaceCommand:a,publishWorkspaceEvent:c}=t;return{async getWorkspaceMcpStatus(d){return o(ke.workspaceMcp,()=>Xi(e))},async getWorkspaceSkillsStatus(d){return o(ke.workspaceSkills,()=>Qi(e))},async getWorkspaceProvidersStatus(d){return o(ke.workspaceProviders,()=>Yi(e))},async getWorkspaceEnvStatus(d){let u=s?.()??!1;if(!n)return Zi(e,u);try{return await n.getEnvStatus(e,u)}catch(l){return D(`matilda serve: getEnvStatus failed: ${l instanceof Error?l.message:String(l)}`),Zi(e,u)}},async getWorkspacePreflightStatus(d){let u=s?.()??!1,l=eo(),p=[];if(n)try{p=await n.getDaemonPreflightCells(e)}catch(v){D(`matilda serve: getDaemonPreflightCells failed: ${v instanceof Error?v.message:String(v)}`)}let f=l,g;if(u)try{let v=await o(ke.workspacePreflight,()=>({cells:l}));if(v&&"cells"in v){let x=v;f=x.cells.filter(O=>O.locality!=="daemon"),g=x.errors}}catch(v){f=l;let x=Mt(v);g=[{kind:"preflight",status:"error",error:v instanceof Error?v.message:String(v),...x?{errorKind:x}:{}}]}return{v:ot,workspaceCwd:e,initialized:!0,acpChannelLive:u,cells:[...p,...f],...g&&g.length>0?{errors:g}:{}}},async getWorkspaceHooksStatus(d){return o(ke.workspaceHooks,()=>pn(e))},async getWorkspaceExtensionsStatus(d){return o(ke.workspaceExtensions,()=>ln(e))},async setWorkspaceToolEnabled(d,u,l){return await i(e,u,l),c({type:"tool_toggled",data:{toolName:u,enabled:l},originatorClientId:d.originatorClientId}),{toolName:u,enabled:l}},async initWorkspace(d,u){let l=r,p=Ct.resolve(e,l);if(!(p===e||p.startsWith(e+Ct.sep)))throw new Pr(l,e);let g=await Qr.realpath(e),v=await O0(Ct.dirname(p));if(!(v===g||v.startsWith(g+Ct.sep)))throw new mt(p,"parent",`Configured workspace context filename ${JSON.stringify(l)} has a parent path that resolves outside the bound workspace (parent canonicalizes to ${JSON.stringify(v)}, workspace canonicalizes to ${JSON.stringify(g)}). Refusing to write \u2014 replace any symlinked parent directory with a real directory before re-running init.`);try{let P=await Qr.lstat(p);if(P.isSymbolicLink())throw new mt(p,"target",`Workspace context file ${JSON.stringify(p)} is a symlink. Refusing to follow it for write \u2014 replace the symlink with a regular file (or remove it) before re-running init.`);if(!P.isFile())throw new mt(p,"target",`Workspace context file ${JSON.stringify(p)} is not a regular file (mode=${P.mode.toString(8)}). Refusing to proceed \u2014 FIFOs, sockets, and device nodes can block or misbehave on read/write.`)}catch(P){if(P instanceof mt||P?.code!=="ENOENT")throw P}let O="created";try{let P=await Qr.readFile(p,"utf8");if(P.trim().length>0){let q=Buffer.byteLength(P,"utf8");if(u.force!==!0)throw new ar(p,q);O="overwrote"}else O="noop"}catch(P){if(P instanceof ar||P?.code!=="ENOENT")throw P}if(O==="created"){let P;try{P=await Qr.open(p,"wx")}catch(q){throw q?.code==="EEXIST"?new cr(p,"eexist",`Workspace context file ${JSON.stringify(p)} appeared between our absence check and the create \u2014 refusing to proceed (a regular file or symlink was just placed at the target path, and following it could escape the workspace).`):q}try{await M0(p,g,P),await P.writeFile("","utf8")}finally{await P.close()}}else if(O==="overwrote"){let P;try{P=await Qr.open(p,P0.O_WRONLY|(P0.O_NOFOLLOW??0))}catch(q){let U=q?.code;throw U==="ELOOP"?new mt(p,"target",`Workspace context file ${JSON.stringify(p)} could not be opened with O_NOFOLLOW (ELOOP); the path may have been swapped to a symlink between the content check and the overwrite. Refusing to follow it.`):U==="ENOENT"?new cr(p,"enoent",`Workspace context file ${JSON.stringify(p)} was deleted between the content check and the overwrite (likely a concurrent writer). Refusing to recreate blindly; rerun init.`):q}try{await M0(p,g,P),await P.truncate(0)}finally{await P.close()}}return c({type:"workspace_initialized",data:{path:p,action:O},originatorClientId:d.originatorClientId}),{path:p,action:O}},async restartMcpServer(d,u,l){let p={serverName:u};l?.entryIndex!==void 0&&(p.entryIndex=l.entryIndex);let f;try{f=await a(le.workspaceMcpRestart,p,{timeoutMs:3e5})}catch(g){let v=g?.data;if(v&&typeof v=="object"){let x=v.errorKind,O=v.serverName;if(x==="mcp_server_not_found"&&typeof O=="string")throw new Mr(O);if(x==="mcp_restart_failed"&&typeof O=="string"){let P=v.mcpStatus;throw new Or(O,typeof P=="string"?P:"unknown")}}throw g}if("entries"in f){let g=Array.isArray(f.entries)?f.entries:[];Array.isArray(f.entries)||D(`matilda serve: pool restart response carried 'entries' field but it is not an array (server=${u}); treating as empty.`);for(let v of g){if(typeof v!="object"||v===null||typeof v.entryIndex!="number"){D(`matilda serve: skipping malformed pool restart entry (server=${u}): ${JSON.stringify(v)}`);continue}v.restarted?c({type:"mcp_server_restarted",data:{serverName:f.serverName,durationMs:v.durationMs??0,entryIndex:v.entryIndex},originatorClientId:d.originatorClientId}):c({type:"mcp_server_restart_refused",data:{serverName:f.serverName,reason:"restart_failed",entryIndex:v.entryIndex,...v.reason?{details:v.reason}:{}},originatorClientId:d.originatorClientId})}}else f.restarted===!0?c({type:"mcp_server_restarted",data:{serverName:f.serverName,durationMs:f.durationMs},originatorClientId:d.originatorClientId}):c({type:"mcp_server_restart_refused",data:{serverName:f.serverName,reason:f.reason},originatorClientId:d.originatorClientId});return f},async reload(d){if(t.reloadDaemonEnv)try{await t.reloadDaemonEnv(e)}catch(x){D(`matilda serve: daemon reload failed: ${x instanceof Error?x.message:String(x)}`)}let u=!1,l={updatedKeys:[],removedKeys:[]},p=[],f,g,v;try{let x=await a(le.workspaceReload,{cwd:e},{timeoutMs:3e4});u=!0,l=x.env,p=x.changedKeys,f=x.sessionsRefreshed,g=x.sessionsSkipped}catch(x){x instanceof ie?v="ACP child not running":(v=x instanceof Error?x.message:String(x),D(`matilda serve: reload failed: ${v}`))}return c({type:"settings_reloaded",data:{env:l,changedKeys:p,childReloaded:u,sessionsRefreshed:f,sessionsSkipped:g,childError:v},originatorClientId:d.originatorClientId}),{env:l,changedKeys:p,childReloaded:u,sessionsRefreshed:f,sessionsSkipped:g,childError:v}}}}w();var ux=new Set(["general.vimMode","general.terminalBell","general.preferredEditor","general.outputLanguage","ide.enabled","ui.showLineNumbers","ui.renderMode","ui.useTerminalBuffer","ui.hideBanner","ui.accessibility.enableLoadingPhrases","ui.enableWelcomeBack"]),lx=new Set(["ui.compactMode"]),pd=new Set(["workspace"]),D0=1024,px=new Set(["tools.approvalMode"]);function fx(){let t=new Set(ku().filter(e=>!ux.has(e)&&!px.has(e)));for(let e of lx)t.add(e);return t}function hx(t,e){let r=Tt(t),n=[];for(let i of e){let o=Vi(i);if(!o)continue;let a=ns(r.merged,i),c=ns(r.user.settings,i),d=ns(r.workspace.settings,i),u={effective:a!==void 0?a:o.default};c!==void 0&&(u.user=c),d!==void 0&&(u.workspace=d),n.push({key:i,type:o.type,label:o.label,category:o.category,...o.description?{description:o.description}:{},requiresRestart:o.requiresRestart,default:o.default,...o.options?.length?{options:o.options}:{},values:u})}let s=[];return r.corruptedPath&&s.push({type:"corrupted",recovered:r.wasRecovered}),{v:1,...s.length?{warnings:s}:{},settings:n}}function mx(t,e){switch(t.type){case"boolean":if(typeof e!="boolean")return"Value must be a boolean";break;case"number":if(typeof e!="number"||!Number.isFinite(e))return"Value must be a finite number";break;case"string":if(typeof e!="string")return"Value must be a string";if(e.length>D0)return`Value exceeds ${D0}-character limit`;break;case"enum":if(!t.options?.some(r=>r.value===e))return`Value must be one of: ${t.options?.map(n=>n.value).join(", ")??""}`;break;default:return`Settings of type '${t.type}' cannot be modified via this API`}}var gx={workspace:"Workspace"};function F0(t,e){let{boundWorkspace:r,mutate:n,safeBody:s,persistSetting:i,broadcastSettingsChanged:o,parseAndValidateClientId:a}=e,c=fx();t.get("/workspace/settings",(d,u)=>{try{let l=hx(r,c);u.status(200).json(l)}catch(l){D(`matilda serve: GET /workspace/settings error: ${l instanceof Error?l.message:String(l)}`),u.status(500).json({error:"Failed to load settings",code:"internal_error"})}}),t.post("/workspace/settings",n({strict:!0}),async(d,u)=>{let l=s(d),p=l.scope,f=l.key,g=l.value;if(typeof p!="string"||!pd.has(p)){u.status(400).json({error:`scope must be one of: ${[...pd].join(", ")}`,code:"invalid_scope"});return}if(typeof f!="string"||!f){u.status(400).json({error:"key is required and must be a string",code:"invalid_key"});return}if(!c.has(f)){u.status(400).json({error:`Setting "${f}" is not modifiable via this API`,code:"disallowed_key"});return}if(g==null){u.status(400).json({error:"value is required",code:"missing_value"});return}let v=Vi(f);if(!v){u.status(400).json({error:`Unknown setting: ${f}`,code:"unknown_key"});return}let x=mx(v,g);if(x){u.status(400).json({error:x,code:"invalid_value"});return}let O=a(d,u);if(O!==null){try{let P=gx[p];if(!P){u.status(400).json({error:`scope must be one of: ${[...pd].join(", ")}`,code:"invalid_scope"});return}await i(r,P,f,g)}catch(P){D(`matilda serve: POST /workspace/settings persist error (key=${f}, scope=${p}, workspace=${r}): ${P instanceof Error?P.message:String(P)}`),u.status(500).json({error:"Failed to persist setting",code:"persist_error"});return}try{o(f,g,p,O)}catch(P){D(`matilda serve: POST /workspace/settings broadcast error (key=${f}, scope=${p}): ${P instanceof Error?P.message:String(P)}`)}u.status(200).json({key:f,scope:p,value:g,requiresRestart:v.requiresRestart})}})}w();import*as N0 from"node:fs/promises";import*as $0 from"node:path";var vx="application/a2ui+json",yx="action",L0=15e3;function B0(t){return!!t&&(typeof t.command=="string"||typeof t.httpUrl=="string")}async function wx(t){try{let e=await N0.readFile($0.join(t,".matilda","settings.json"),"utf8"),r=JSON.parse(e);for(let[n,s]of Object.entries(r.mcpServers??{}))if(n.toLowerCase().includes("a2ui")&&B0(s))return s}catch{}return null}function bx(t){return typeof t.httpUrl=="string"?new wu(new URL(t.httpUrl)):new bu({command:t.command,args:t.args??[],...t.env?{env:{...process.env,...t.env}}:{},cwd:t.cwd})}function Sx(t){if(t.isError){let n=(t.content??[]).filter(s=>s.type==="text"&&typeof s.text=="string").map(s=>s.text).join("");throw new Error(`a2ui action tool returned error: ${n||"unknown error"}`)}let e=null,r="";for(let n of t.content??[])if(e===null&&n.type==="resource"&&n.resource?.mimeType===vx&&typeof n.resource.text=="string")try{let s=JSON.parse(n.resource.text);Array.isArray(s)&&(e=s)}catch{}else n.type==="text"&&typeof n.text=="string"&&(r+=n.text);return{commands:e,fallback:r}}async function Ex(t,e){let r=bx(t),n=new yu({name:"matilda-serve-a2ui",version:"0.0.1"});try{await n.connect(r,{timeout:L0});let s=await n.callTool({name:yx,arguments:{...e}},void 0,{timeout:L0});return Sx(s)}finally{await r.close().catch(()=>{}),await n.close().catch(()=>{})}}function q0(t,e){let{boundWorkspace:r,mutate:n,safeBody:s,getMcpServers:i}=e,o=e.callAction??Ex;t.post("/session/:id/a2ui-action",n(),async(a,c)=>{let d=s(a),u=d.name;if(typeof u!="string"||u.trim().length===0){c.status(400).json({error:"`name` is required"});return}let l=typeof d.surfaceId=="string"?d.surfaceId:void 0,p=d.context&&typeof d.context=="object"&&!Array.isArray(d.context)?d.context:void 0,f=null;try{let g=(await i(a)).filter(x=>x.name.toLowerCase().includes("a2ui")&&B0(x.config));f=(g.find(x=>x.mcpStatus==="connected")??g[0])?.config??null}catch{}if(f||(f=await wx(r)),!f){c.status(503).json({error:"no a2ui MCP server found (neither runtime-registered nor in workspace settings mcpServers)"});return}try{let{commands:g,fallback:v}=await o(f,{name:u.trim(),surfaceId:l,context:p});c.status(200).json({commands:g,fallback:v})}catch(g){D(`a2ui-action proxy failed: ${g instanceof Error?g.message:String(g)}`),c.status(502).json({error:"a2ui action call failed"})}})}w();var Ix=1e4,xx=1e3,_x=5*60*1e3;function kx(t,e){let r=e.endsWith("/")&&e.length>1?e.slice(0,-1):e;return t==="OPTIONS"||(t==="GET"||t==="HEAD")&&(r==="/health"||r==="/demo")||t==="POST"&&r.startsWith("/session/")&&r.endsWith("/heartbeat")||t==="GET"&&r.startsWith("/session/")&&r.endsWith("/events")||r==="/acp"||r.startsWith("/acp/")?null:t==="POST"&&r.startsWith("/session/")&&r.endsWith("/prompt")?"prompt":t!=="GET"&&t!=="HEAD"?"mutation":"read"}var Ax=128,Rx=/^[A-Za-z0-9._:-]+$/;function Cx(t){return t.startsWith("::ffff:")?t.slice(7):t}function Tx(t){let e=_t(t);return r=>{let n=r.get("x-matilda-client-id"),s=n&&n.length<=Ax&&Rx.test(n)?n:void 0;if(e)return s?`cid:${s}`:"anonymous";let i=Cx(r.socket?.remoteAddress??"unknown");return s?`${i}:${s}`:i}}var Px=100;function Mx(t){let e=new Map;return{log(r,n){let s=`${r}:${n}`,i=e.get(s);i||(i={count:0,suppressed:0},e.set(s,i)),i.count++,i.count===1||i.count%Px===0?(t(r,n,i.suppressed),i.suppressed=0):i.suppressed++},clear(){e.clear()}}}function j0(t){for(let[p,f]of Object.entries(t.tiers)){if(!Number.isFinite(f.max)||f.max<=0)throw new Error(`rate limit: ${p}.max must be a positive number, got ${f.max}`);if(!Number.isFinite(f.windowMs)||f.windowMs<=0)throw new Error(`rate limit: ${p}.windowMs must be a positive number, got ${f.windowMs}`)}let e=new Map,r=Tx(t.hostname),n={prompt:0,mutation:0,read:0},s={prompt:t.tiers.prompt.max/t.tiers.prompt.windowMs,mutation:t.tiers.mutation.max/t.tiers.mutation.windowMs,read:t.tiers.read.max/t.tiers.read.windowMs},i=!1,o=0,a=t.onLimitReached?Mx(t.onLimitReached):void 0;function c(){let p=Date.now();for(let[f,g]of e){let v=!0;for(let[x,O]of g)if(p-O.lastRefill<t.tiers[x].windowMs*2){v=!1;break}v&&e.delete(f)}}let d=setInterval(c,_x);d.unref();let u=(p,f,g)=>{try{if(i){g();return}let v=kx(p.method,p.path);if(v===null){g();return}o++,o%xx===0&&c();let x=r(p);if(l(x,v))g();else{let O=t.tiers[v],P=s[v],q=e.get(x)?.get(v),U=Math.ceil((1-(q?.tokens??0))/P),ae=Math.ceil(U/1e3);f.setHeader("Retry-After",String(ae)),f.setHeader("X-RateLimit-Limit",String(O.max)),f.setHeader("X-RateLimit-Remaining","0"),f.setHeader("X-RateLimit-Reset",String(Math.ceil((Date.now()+U)/1e3))),f.status(429).json({error:"Rate limit exceeded",code:"rate_limit_exceeded",tier:v,retryAfterMs:U})}}catch(v){t.onError?.(v,p.path),g()}};function l(p,f){if(i)return!0;let g=t.tiers[f],v=s[f],x=Date.now(),O=e.get(p);if(!O){if(e.size>=Ix)return t.onError?.(new Error(`rate limit bucket overflow: ${e.size} keys`),`tryConsume:${f}`),!0;O=new Map,e.set(p,O)}let P=O.get(f);P||(P={tokens:g.max,lastRefill:x},O.set(f,P));let q=Math.max(0,x-P.lastRefill);return P.tokens=Math.min(g.max,P.tokens+q*v),P.lastRefill=x,P.tokens>=1?(P.tokens-=1,!0):(n[f]++,a&&a.log(f,p),!1)}return{middleware:u,checkRate:l,reset(){e.clear(),n.prompt=0,n.mutation=0,n.read=0,o=0,a?.clear()},setDraining(p){i=p},dispose(){clearInterval(d),e.clear(),a?.clear()},getHitCounts(){return{...n}}}}var W0="_rateLimiter";function H0(t,e){t.locals[W0]=e}function U0(t){return t.locals[W0]}var wd=0;function Sd(){return wd}var Ox="MATILDA_CODE_BENCHMARK_API",Dx=1e3,V0=2e5;function Fx(){let e=0;return r=>{if(e+=1,e===1||e%100===0){let n=r.data,s=[];n?.errorKind&&s.push(`errorKind=${n.errorKind}`),n?.intent&&s.push(`intent=${n.intent}`),n?.pathHash&&s.push(`pathHash=${n.pathHash}`);let i=s.length>0?` (${s.join(" ")})`:"";D(`matilda serve: fs audit emit is the default no-op \u2014 ${e} event(s) dropped so far. Latest type=${r.type}${i}. Inject deps.fsFactory in createServeApp to wire audit into the EventBus.`)}}}var z0=!1;function Ed(t){return t.injected?t.injected:dd({boundWorkspace:t.boundWorkspace,trusted:t.trusted,emit:t.emit??Fx()})}var Lx=20,Nx=100,Kr=class extends Error{constructor(e){super(`Invalid cursor: "${e}" is not a valid session cursor`),this.name="InvalidCursorError"}};async function zc(t,e,r){let n=Math.min(Math.max(r?.size??Lx,1),Nx),s=r?.cursor===void 0,i=new tn(e),o;try{o=await i.listSessions({cursor:r?.cursor,size:n})}catch(l){throw l instanceof au&&r?.cursor!==void 0?new Kr(r.cursor):l}let a=new Map;for(let l of o.items)a.set(l.sessionId,{sessionId:l.sessionId,workspaceCwd:l.cwd,createdAt:l.startTime,updatedAt:l.lastMessageAt!==void 0?new Date(l.lastMessageAt).toISOString():l.startTime,title:l.customTitle??l.prompt,clientCount:0,hasActivePrompt:!1});let c=t.listWorkspaceSessions(e);for(let l of c){let p=a.get(l.sessionId);p?a.set(l.sessionId,{...p,...l,createdAt:p.createdAt,title:l.title??p.title,updatedAt:l.updatedAt??p.updatedAt,clientCount:l.clientCount,hasActivePrompt:l.hasActivePrompt}):s&&!await i.sessionExists(l.sessionId)&&a.set(l.sessionId,{...l,createdAt:l.createdAt,clientCount:l.clientCount,hasActivePrompt:l.hasActivePrompt})}let d=[...a.values()].sort((l,p)=>{let f=Date.parse(l.updatedAt??l.createdAt);return Date.parse(p.updatedAt??p.createdAt)-f}),u=o.nextCursor!=null?String(o.nextCursor):void 0;return{sessions:d,nextCursor:u}}var $x=["protocol","baseUrl","apiKey","models","advancedConfig"];function Bx(t){let e=$x.filter(r=>lu(t,r));return{id:t.id,label:t.label,description:t.description,...t.uiGroup?{uiGroup:t.uiGroup}:{},protocol:t.protocol,...t.protocolOptions?{protocolOptions:[...t.protocolOptions]}:{},...t.baseUrl!==void 0?{baseUrl:t.baseUrl}:{},...typeof t.envKey=="string"?{envKey:t.envKey}:{},...t.models?{models:t.models.map(r=>({id:r.id,...r.contextWindowSize!==void 0?{contextWindowSize:r.contextWindowSize}:{},...r.enableThinking!==void 0?{enableThinking:r.enableThinking}:{},...r.modalities?{modalities:r.modalities}:{},...r.description?{description:r.description}:{}}))}:{},...t.modelsEditable!==void 0?{modelsEditable:t.modelsEditable}:{},...t.apiKeyPlaceholder?{apiKeyPlaceholder:t.apiKeyPlaceholder}:{},...typeof t.documentationUrl=="string"?{documentationUrl:t.documentationUrl}:{},...t.showAdvancedConfig!==void 0?{showAdvancedConfig:t.showAdvancedConfig}:{},...t.uiLabels?{uiLabels:t.uiLabels}:{},steps:e}}function qx(t){let e=Hi.map(Bx),r=n=>e.filter(s=>s.uiGroup===n).map(s=>s.id);return{v:1,workspaceCwd:t,providers:e,groups:[{id:"third-party",label:"Third-party Providers",description:"Choose a built-in provider and connect with an API key",providerIds:r("third-party")},{id:"custom",label:"Custom Provider",description:"Manually connect a local server, proxy, or unsupported provider",providerIds:r("custom")}]}}function jx(t){if(!Array.isArray(t))return;let e=t.map(r=>typeof r=="string"?r.trim():"").filter(r=>r.length>0);return e.length>0?[...new Set(e)]:void 0}function G0(t,e){if(!(typeof t!="number"||!Number.isInteger(t)||!Number.isFinite(t)||t<=0||t>e))return t}function Wx(t){let e=t.split(":");if(e.length!==2)return;let[r,n]=e;if(!/^[0-9a-f]{1,4}$/i.test(r)||!/^[0-9a-f]{1,4}$/i.test(n))return;let s=Number.parseInt(r,16),i=Number.parseInt(n,16);return`${s>>8&255}.${s&255}.${i>>8&255}.${i&255}`}function Hx(t){let e=t.split(":",1)[0];if(!(!e||!/^[0-9a-f]{1,4}$/i.test(e)))return Number.parseInt(e,16)}function bd(t){let r=(t.endsWith(".")?t.slice(0,-1):t).toLowerCase();if(r==="localhost"||r.endsWith(".localhost"))return!0;let n=r.startsWith("[")&&r.endsWith("]")?r.slice(1,-1):r,s=vd.isIP(n);if(s===4){let i=n.split(".").map(c=>Number(c)),[o,a]=i;return o===0||o===10||o===127||o===100&&a!==void 0&&a>=64&&a<=127||o===169&&a===254||o===172&&a!==void 0&&a>=16&&a<=31||o===192&&a===168}if(s===6){if(n==="::"||n==="::1")return!0;let i=Hx(n);if(i!==void 0&&(i>=65152&&i<=65215||(i&65024)===64512))return!0;if(n.startsWith("::ffff:")){let o=n.slice(7);if(vd.isIP(o)===4)return bd(o);let a=Wx(o);return a?bd(a):!0}}return!1}function Ux(t,e){if(t==null)return;if(typeof t!="string")return null;let r=t.trim();if(!r)return;let n;try{n=new URL(r)}catch{return null}return n.protocol!=="http:"&&n.protocol!=="https:"||n.username||n.password||!e&&bd(n.hostname)?null:n.toString().replace(/\/$/,"")}function Vx(t,e){let r=t.providerId,n=t.apiKey;if(typeof r!="string"||r.trim().length===0||typeof n!="string"||n.trim().length===0)return{ok:!1,code:"invalid_request",error:"`providerId` and `apiKey` are required"};let s=t.protocol,i=Ux(t.baseUrl,e?.allowPrivateBaseUrl===!0);if(i===null)return{ok:!1,code:"invalid_base_url",error:"`baseUrl` must be an http(s) URL without credentials or blocked private-network host"};let o=jx(t.modelIds),a=t.advancedConfig&&typeof t.advancedConfig=="object"?t.advancedConfig:void 0,c=a?.multimodal&&typeof a.multimodal=="object"?a.multimodal:void 0,d=G0(a?.contextWindowSize,1e7),u=G0(a?.maxTokens,1e7),l=a?{...typeof a.enableThinking=="boolean"?{enableThinking:a.enableThinking}:{},...c?{multimodal:{...typeof c.image=="boolean"?{image:c.image}:{},...typeof c.pdf=="boolean"?{pdf:c.pdf}:{},...typeof c.audio=="boolean"?{audio:c.audio}:{},...typeof c.video=="boolean"?{video:c.video}:{}}}:{},...d!==void 0?{contextWindowSize:d}:{},...u!==void 0?{maxTokens:u}:{}}:void 0;return{ok:!0,value:{providerId:r.trim(),...typeof s=="string"&&s.trim()?{protocol:s.trim()}:{},...i?{baseUrl:i}:{},apiKey:n,...o?{modelIds:o}:{},...l?{advancedConfig:l}:{}}}}function zx(t){let e=t.path.replace(/\/$/,"")||"/";if(t.method==="POST"&&e==="/session")return{route:"POST /session"};if(t.method==="POST"&&e==="/sessions/delete")return{route:"POST /sessions/delete"};if(t.method==="GET"&&e==="/daemon/status")return{route:"GET /daemon/status"};let r=e.match(/^\/session\/([^/]+)\/(load|resume|prompt|cancel|recap|btw|mid-turn-message|model|shell|detach|rewind|approval-mode|language|a2ui-action)$/),n=r?.[1],s=r?.[2];if(n&&s&&t.method==="POST")return{route:`POST /session/:id/${s}`,sessionId:n};let i=e.match(/^\/session\/([^/]+)\/metadata$/);if(i?.[1]&&t.method==="PATCH")return{route:"PATCH /session/:id/metadata",sessionId:i[1]};let o=e.match(/^\/session\/([^/]+)\/permission\/([^/]+)$/);if(o?.[1]&&o?.[2]&&t.method==="POST"){let g=o[2];return{route:"POST /session/:id/permission/:requestId",sessionId:o[1],...g.length<=Mi&&Oi.test(g)?{permissionRequestId:g}:{}}}let a=e.match(/^\/permission\/([^/]+)$/);if(a?.[1]&&t.method==="POST"){let g=a[1];return{route:"POST /permission/:requestId",...g.length<=Mi&&Oi.test(g)?{permissionRequestId:g}:{}}}let d=e.match(/^\/session\/([^/]+)$/)?.[1];if(d&&t.method==="DELETE")return{route:"DELETE /session/:id",sessionId:d};if(t.method==="GET"&&/^\/workspace\/[^/]+\/sessions$/.test(e))return{route:"GET /workspace/:id/sessions"};if(t.method==="POST"&&e==="/workspace/init")return{route:"POST /workspace/init"};if(t.method==="POST"&&e==="/workspace/reload")return{route:"POST /workspace/reload"};if(e.match(/^\/workspace\/mcp\/([^/]+)\/restart$/)?.[1]&&t.method==="POST")return{route:"POST /workspace/mcp/:server/restart"};if(t.method==="POST"&&e==="/workspace/mcp/servers")return{route:"POST /workspace/mcp/servers"};if(e.match(/^\/workspace\/mcp\/servers\/([^/]+)$/)?.[1]&&t.method==="DELETE")return{route:"DELETE /workspace/mcp/servers/:name"};if(t.method==="POST"&&e==="/workspace/auth/device-flow")return{route:"POST /workspace/auth/device-flow"};if(e.match(/^\/workspace\/auth\/device-flow\/([^/]+)$/)?.[1]&&t.method==="DELETE")return{route:"DELETE /workspace/auth/device-flow/:id"};if(e.match(/^\/workspace\/tools\/([^/]+)\/enable$/)?.[1]&&t.method==="POST")return{route:"POST /workspace/tools/:name/enable"};if(e==="/workspace/settings"){if(t.method==="GET")return{route:"GET /workspace/settings"};if(t.method==="POST")return{route:"POST /workspace/settings"}}}function Gx(t){let e=Qn(t);return(r,n,s)=>{let i=zx(r);if(!i){s();return}let o=r.get(ev),a=o!==void 0&&o!==""&&o.length<=Mi&&Oi.test(o)?o:void 0,c=Date.now();$d({method:r.method,route:i.route,workspaceHash:e,...i.sessionId?{sessionId:i.sessionId}:{},...i.permissionRequestId?{permissionRequestId:i.permissionRequestId}:{},...a?{clientId:a}:{}},async d=>await new Promise((u,l)=>{let p=!1,f=()=>{p||(p=!0,Bd(d,n.statusCode),Ud(Date.now()-c,i.route,n.statusCode),u())};n.once("finish",f),n.once("close",f);try{s()}catch(g){ji(d,g),l(g)}})).catch(s)}}var Pi=class extends Error{deadlineMs;constructor(e){super(`prompt exceeded the ${e}ms deadline`),this.name="PromptDeadlineExceededError",this.deadlineMs=e}};function K0(t,e){if(!(t===void 0||!Number.isFinite(t)||t<=0))return e===void 0||!Number.isFinite(e)||e<=0?t:Math.min(t,e)}var Kx=5;function Jx(t){return t===void 0?Kx:t===0||t===Number.POSITIVE_INFINITY?null:t}function Id(t,e=()=>t.port,r={}){let n=(0,yd.default)(),s=r.boundWorkspace??Qe(t.workspace??process.cwd());!r.fsFactory&&!r.bridge&&!z0&&(z0=!0,process.stderr.write(`matilda serve: createServeApp default fsFactory uses trusted=false \u2014 agent ACP writeTextFile calls will reject with untrusted_workspace. Inject deps.fsFactory (with explicit trust) or deps.bridge to override.
|
|
716
716
|
`));let i=Ed({boundWorkspace:s,injected:r.fsFactory,trusted:!1}),o=typeof t.token=="string"&&t.token.length>0,a=t.enableSessionShell===!0&&o,c=r.bridge??gr({maxSessions:t.maxSessions,maxPendingPromptsPerSession:t.maxPendingPromptsPerSession,eventRingSize:t.eventRingSize,boundWorkspace:s,sessionShellCommandEnabled:a,statusProvider:Mn(),fileSystem:fi(i)}),d=-1,u=new Set;n.use((b,h,y)=>{let A=b.headers.origin;if(A){let k=e();k!==d&&(d=k,u=new Set([`http://127.0.0.1:${k}`,`http://localhost:${k}`,`http://[::1]:${k}`,`http://host.docker.internal:${k}`])),u.has(A)&&delete b.headers.origin}y()}),n.locals.fsFactory=i,n.locals.boundWorkspace=s;let l=new Map;for(let b of r.deviceFlowProviders??[])l.set(b.providerId,b);l.has("matilda-oauth")||l.set("matilda-oauth",new pi);let p={publish(b,h){c.publishWorkspaceEvent({type:`auth_device_flow_${b.type}`,data:b.data,...h?{originatorClientId:h}:{}})}},f=r.deviceFlowRegistry??new si({events:p,audit:{record(b){let h=b.deviceFlowId.slice(0,8),y=["[serve] auth.device-flow:",`provider=${b.providerId}`,`deviceFlowId=${h}...`,b.clientId?`clientId=${b.clientId}`:"clientId=-",`status=${b.status}`];if(b.errorKind&&y.push(`errorKind=${b.errorKind}`),b.expiresInMs!==void 0&&y.push(`expiresInMs=${Math.max(0,b.expiresInMs)}`),b.hint){let k=b.hint.length>1024?`${b.hint.slice(0,1024)}\u2026[+${b.hint.length-1024} bytes truncated]`:b.hint;y.push(`hint=${JSON.stringify(k)}`)}D(y.join(" "))}},resolveProvider:b=>l.get(b)});Jm(n,f);let{daemonLog:g}=r,v=(b,h,y)=>tv(b,h,y,g),x=(b,h,y)=>d_(b,h,y,g),O=r.workspace??Ci({boundWorkspace:s,contextFilename:r.contextFilename??"MATILDA.md",statusProvider:Mn(),isChannelLive:()=>c.isChannelLive(),persistDisabledTools:r.persistDisabledTools??(async()=>{throw new Error("setWorkspaceToolEnabled requires persistDisabledTools in ServeAppDeps")}),queryWorkspaceStatus:(b,h)=>c.queryWorkspaceStatus(b,h),invokeWorkspaceCommand:(b,h,y)=>c.invokeWorkspaceCommand(b,h,y),publishWorkspaceEvent:b=>c.publishWorkspaceEvent(b)});if(t.allowOrigins&&t.allowOrigins.length>0){let b=ri(t.allowOrigins);if(b.allowAny&&!t.token)throw new Error("Refusing to start with --allow-origin '*' but no bearer token configured. '*' admits any cross-origin browser to the API; without a token, any local page can drive the daemon. Set a token or list specific origins instead of '*'.");n.use(Vm(b))}else n.use(wc);n.use(bc(t.hostname,e));let P=(b,h)=>{try{h.type("html").set("X-Frame-Options","DENY").set("Content-Security-Policy","default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; frame-ancestors 'none'").send(d0(e()))}catch(y){D(`matilda serve: /demo render failed: ${y instanceof Error?y.message:String(y)}`),h.status(500).json({error:"Failed to render demo page"})}},q=(b,h)=>{let y=b.query.deep;if(!(y==="1"||y==="true"||y==="")){h.status(200).json({status:"ok"});return}try{h.status(200).json({status:"ok",sessions:c.sessionCount,pendingPermissions:c.pendingPermissionCount,...pe?{rateLimitHits:pe.getHitCounts()}:{}})}catch(k){D(`matilda serve: /health deep probe failed: ${k instanceof Error?k.message:String(k)}`),h.status(503).json({status:"degraded"})}},ae=_t(t.hostname)&&!t.requireAuth;if(ae&&(n.get("/health",q),n.get("/demo",P)),g){let b=/\/session\/([^/]+)/;n.use((h,y,A)=>{let{method:k,path:S}=h;if(k==="GET"&&S==="/health"||k==="POST"&&S.endsWith("/heartbeat"))return A();let R=Date.now();y.on("finish",()=>{try{let F=y.statusCode;if(k==="GET"&&S.endsWith("/events")&&F===200)return;let H=Date.now()-R,X=S.match(b)?.[1],fe=h.headers["x-matilda-client-id"],de={route:`${k} ${S}`,...X?{sessionId:X}:{},...fe?{clientId:fe}:{},status:F,durationMs:H};F>=400?g.warn("request completed",de):g.info("request completed",de)}catch{}}),A()})}n.use(Sc(t.token));let pe;if(t.rateLimit){let b=t.rateLimitWindowMs??6e4;pe=j0({tiers:{prompt:{windowMs:b,max:t.rateLimitPrompt??10},mutation:{windowMs:b,max:t.rateLimitMutation??30},read:{windowMs:b,max:t.rateLimitRead??120}},hostname:t.hostname,onLimitReached:g?(h,y,A)=>{g.warn(`rate limit hit${A>0?` (${A} suppressed)`:""}`,{tier:h,key:y.slice(0,64)})}:void 0,onError:g?(h,y)=>{g.warn(`rate limiter error (fail-open): ${h instanceof Error?h.message:String(h)}`,{path:y})}:void 0}),n.use(pe.middleware)}n.use(yd.default.json({limit:"10mb"})),n.use((b,h,y,A)=>{J0(y,b)||A(b)}),ae||(n.get("/health",q),n.get("/demo",P));let V=Ec({tokenConfigured:o,requireAuth:t.requireAuth===!0});n.use(Gx(s));function Se(b,h,y){return{originatorClientId:y,route:h,workspaceCwd:s}}let Te=[..._u.map(b=>b.code),"auto"],Ze=()=>Ai(void 0,{requireAuth:t.requireAuth===!0,mcpPoolActive:t.mcpPoolActive!==!1,allowOriginActive:t.allowOrigins!==void 0&&t.allowOrigins.length>0,...t.promptDeadlineMs!==void 0?{promptDeadlineMs:t.promptDeadlineMs}:{},...t.writerIdleTimeoutMs!==void 0?{writerIdleTimeoutMs:t.writerIdleTimeoutMs}:{},persistSettingAvailable:r.persistSetting!==void 0,sessionShellCommandEnabled:a,rateLimit:t.rateLimit===!0,reloadAvailable:r.workspace!==void 0}),Me={};if(n.get("/daemon/status",async(b,h)=>{let y=s0(b.query.detail);if(!y.ok||!y.detail){h.status(400).json({error:"detail must be one of: summary, full",code:"invalid_detail"});return}try{h.status(200).json(await i0(y.detail,{opts:t,boundWorkspace:s,bridge:c,workspace:O,daemonLog:g,matildaCodeVersion:r.matildaCodeVersion,acpHandle:Me.current,rateLimiter:pe,getRestSseActive:Sd,features:Ze(),protocolVersions:Ri(),supportedDeviceFlowProviders:Array.from(l.keys()),deviceFlowRegistry:f,sessionShellCommandEnabled:a}))}catch(A){D(`matilda serve: /daemon/status failed: ${A instanceof Error?A.message:String(A)}`),h.status(500).json({error:"Failed to build daemon status",code:"daemon_status_failed"})}}),n.get("/capabilities",(b,h)=>{let y={v:Yc,protocolVersions:Ri(),...r.matildaCodeVersion?{matildaCodeVersion:r.matildaCodeVersion}:{},mode:t.mode,features:Ze(),modelServices:[],workspaceCwd:s,transports:["rest"],policy:{permission:c.permissionPolicy},limits:{maxPendingPromptsPerSession:Jx(t.maxPendingPromptsPerSession)},supportedLanguages:Te};h.status(200).json(y)}),n.get("/workspace/mcp",async(b,h)=>{try{let y=Se(b,"GET /workspace/mcp");h.status(200).json(await O.getWorkspaceMcpStatus(y))}catch(y){v(h,y,{route:"GET /workspace/mcp"})}}),n.get("/workspace/mcp/:server/tools",async(b,h)=>{let y=b.params.server;if(!y||typeof y!="string"){h.status(400).json({error:"Server name path parameter is required",code:"invalid_server_name"});return}if(y.length>rr){h.status(400).json({error:`Server name exceeds ${rr}-character limit`,code:"invalid_server_name"});return}try{h.status(200).json(await c.getWorkspaceMcpToolsStatus(y))}catch(A){v(h,A,{route:"GET /workspace/mcp/:server/tools"})}}),n.get("/workspace/skills",async(b,h)=>{try{let y=Se(b,"GET /workspace/skills");h.status(200).json(await O.getWorkspaceSkillsStatus(y))}catch(y){v(h,y,{route:"GET /workspace/skills"})}}),n.get("/workspace/tools",async(b,h)=>{try{h.status(200).json(await c.getWorkspaceToolsStatus())}catch(y){v(h,y,{route:"GET /workspace/tools"})}}),n.get("/workspace/providers",async(b,h)=>{try{let y=Se(b,"GET /workspace/providers");h.status(200).json(await O.getWorkspaceProvidersStatus(y))}catch(y){v(h,y,{route:"GET /workspace/providers"})}}),Ag(n,{bridge:c,boundWorkspace:s,mutate:V,parseClientId:me,safeBody:we}),Lg(n,{bridge:c,boundWorkspace:s,mutate:V,parseClientId:me,safeBody:we}),n.get("/workspace/env",async(b,h)=>{try{let y=Se(b,"GET /workspace/env");h.status(200).json(await O.getWorkspaceEnvStatus(y))}catch(y){v(h,y,{route:"GET /workspace/env"})}}),n.get("/workspace/preflight",async(b,h)=>{try{let y=Se(b,"GET /workspace/preflight");h.status(200).json(await O.getWorkspacePreflightStatus(y))}catch(y){v(h,y,{route:"GET /workspace/preflight"})}}),n.get("/workspace/hooks",async(b,h)=>{try{let y=Se(b,"GET /workspace/hooks");h.status(200).json(await O.getWorkspaceHooksStatus(y))}catch(y){v(h,y,{route:"GET /workspace/hooks"})}}),n.get("/workspace/extensions",async(b,h)=>{try{let y=Se(b,"GET /workspace/extensions");h.status(200).json(await O.getWorkspaceExtensionsStatus(y))}catch(y){v(h,y,{route:"GET /workspace/extensions"})}}),_0(n,{parseClientId:me}),T0(n,{bridge:c,mutate:V,parseClientId:me,safeBody:we}),r.persistSetting){let b=r.persistSetting;F0(n,{boundWorkspace:s,mutate:V,safeBody:we,persistSetting:b,broadcastSettingsChanged:(h,y,A,k)=>{c.publishWorkspaceEvent({type:"settings_changed",data:{key:h,value:y,scope:A},...k?{originatorClientId:k}:{}})},parseAndValidateClientId:(h,y)=>tr(h,y,c)})}q0(n,{boundWorkspace:s,mutate:V,safeBody:we,getMcpServers:async b=>{let h=Se(b,"POST /session/:id/a2ui-action");return(await O.getWorkspaceMcpStatus(h)).servers??[]}}),n.post("/workspace/auth/device-flow",V({strict:!0}),async(b,h)=>{let A=we(b).providerId;if(typeof A!="string"||A.length===0){h.status(400).json({error:"`providerId` must be a non-empty string",code:"invalid_request"});return}if(!l.has(A)){h.status(400).json({error:`Unsupported device-flow provider: ${A}`,code:"unsupported_provider",supportedProviders:Array.from(l.keys())});return}let k=A,S=me(b,h);if(S!==null)try{let{view:R,attached:F}=await f.start({providerId:k,...S!==void 0?{initiatorClientId:S}:{}});h.status(F?200:201).json(s_(R,F,S))}catch(R){if(R instanceof hr){h.status(400).json({error:R.message,code:"unsupported_provider"});return}if(R instanceof mr){h.status(409).json({error:R.message,code:"too_many_active_flows"});return}if(R instanceof vt){h.status(502).json({error:R.message,code:"upstream_error"});return}v(h,R,{route:"POST /workspace/auth/device-flow"})}}),n.get("/workspace/auth/device-flow/:id",V({strict:!0}),async(b,h)=>{let y=b.params.id;if(!y){h.status(404).json({error:"Device-flow id required",code:"device_flow_not_found"});return}let A=f.get(y);if(!A){h.status(404).json({error:`Device-flow ${y} not found`,code:"device_flow_not_found"});return}let k=me(b,h);k!==null&&(!xd(A,k)&&qt()&&D(`matilda serve debug: GET /workspace/auth/device-flow/${y} redacted verification fields \u2014 caller-clientId mismatch (initiator=${A.initiatorClientId??"anonymous"}, caller=${k??"anonymous"})`),h.status(200).json(i_(A,k)))}),n.delete("/workspace/auth/device-flow/:id",V({strict:!0}),(b,h)=>{let y=b.params.id;if(!y){h.status(404).json({error:"Device-flow id required",code:"device_flow_not_found"});return}let A=me(b,h);if(A===null)return;if(f.cancel(y,A)===void 0){h.status(404).json({error:`Device-flow ${y} not found`,code:"device_flow_not_found"});return}h.status(204).end()}),n.get("/workspace/auth/status",(b,h)=>{let y=f.listPending();h.status(200).json({v:1,workspaceCwd:s,providers:[],pendingDeviceFlows:y.map(A=>({deviceFlowId:A.deviceFlowId,providerId:A.providerId,...A.expiresAt!==void 0?{expiresAt:A.expiresAt}:{}})),supportedDeviceFlowProviders:Array.from(l.keys())})}),n.get("/workspace/auth/providers",(b,h)=>{h.status(200).json(qx(s))}),process.env[Ox]==="true"&&n.post("/benchmark/prompt",V({strict:!0}),async(b,h)=>{let y=we(b),A=Yx(y.prompt,h);if(A===void 0)return;let k=y.sessionId,S=typeof k=="string"&&k.length>0?k:void 0;if(k!==void 0&&S===void 0){h.status(400).json({error:"`sessionId` must be a non-empty string when provided",code:"invalid_session_id"});return}let R=y.deadlineMs,F;if(R!=null){if(typeof R!="number"||!Number.isFinite(R)||!Number.isInteger(R)||R<=0){h.status(400).json({error:"`deadlineMs` must be a positive integer (milliseconds)",code:"invalid_deadline_ms"});return}F=R}let H=me(b,h);if(H===null)return;let Z=H,X,fe,de=gd.randomUUID(),re=new AbortController,xe=K0(t.promptDeadlineMs,F),he;xe!==void 0&&(he=setTimeout(()=>{re.signal.aborted||re.abort(new Pi(xe))},xe),he.unref());let K=Date.now();try{let Q=!1;if(S===void 0){let ne=typeof y.modelServiceId=="string"?y.modelServiceId:void 0,ge=await c.spawnOrAttach({workspaceCwd:s,sessionScope:"thread",...ne!==void 0?{modelServiceId:ne}:{},...H!==void 0?{clientId:H}:{}});S=ge.sessionId,Z=ge.clientId,Q=!0,y.keepSession!==!0&&(X=ge.sessionId,fe=ge.clientId)}let Ee=c.getSessionLastEventId(S),et={text:"",eventCount:0},De=new AbortController,Fe=t_(c,S,de,Ee,De.signal,et).catch(ne=>{if(!(ne instanceof DOMException&&(ne.name==="AbortError"||ne.name==="TimeoutError")))throw ne}),Ne=await c.sendPrompt(S,{sessionId:S,prompt:A},re.signal,{...Z!==void 0?{clientId:Z}:{},promptId:de});await Promise.race([Fe,r_(Dx)]),De.abort(),h.status(200).json({v:1,sessionId:S,promptId:de,createdSession:Q,keptSession:X===void 0,latencyMs:Date.now()-K,text:et.text,stopReason:Ne.stopReason,usage:Ne.usage??null,eventCount:et.eventCount,terminalType:et.terminalType??null})}catch(Q){v(h,Q,{route:"POST /benchmark/prompt"})}finally{he!==void 0&&clearTimeout(he),re.abort(),X!==void 0&&c.closeSession(X,fe!==void 0?{clientId:fe}:void 0).catch(Q=>{D(`matilda serve: benchmark session cleanup failed for ${it(X)}: ${it(Q instanceof Error?Q.message:String(Q))}`)})}}),n.post("/workspace/auth/provider",V({strict:!0}),async(b,h)=>{if(!r.installAuthProvider){h.status(501).json({error:"Auth provider installation is not implemented by this daemon",code:"not_implemented"});return}let y=Vx(we(b),{allowPrivateBaseUrl:t.allowPrivateAuthBaseUrl===!0});if(!y.ok){h.status(400).json({error:y.error,code:y.code});return}let A=y.value,k=Hi.find(S=>S.id===A.providerId);if(!k){h.status(400).json({error:`Unsupported auth provider: ${A.providerId}`,code:"unsupported_provider"});return}if(A.protocol){let S=k.protocolOptions&&k.protocolOptions.length?k.protocolOptions:[k.protocol];if(!S.includes(A.protocol)){h.status(400).json({error:`protocol must be one of: ${S.join(", ")}`,code:"unsupported_protocol"});return}}try{h.status(200).json(await r.installAuthProvider(A))}catch(S){v(h,S,{route:"POST /workspace/auth/provider",providerId:A.providerId})}}),n.post("/session",V(),async(b,h)=>{let y=we(b),A="cwd"in y;if(A&&typeof y.cwd!="string"){h.status(400).json({error:"`cwd` must be a string absolute path when provided"});return}if(A&&y.cwd.length>wt){h.status(400).json({error:`\`cwd\` exceeds the ${wt}-character limit`});return}let k=A?y.cwd:s;if(!Ti.isAbsolute(k)){h.status(400).json({error:"`cwd` must be an absolute path when provided"});return}let S=typeof y.modelServiceId=="string"?y.modelServiceId:void 0,R=y.sessionScope,F;if(R!==void 0){if(R!=="single"&&R!=="thread"){h.status(400).json({error:'`sessionScope` must be "single" or "thread" when provided',code:"invalid_session_scope"});return}F=R}let H=me(b,h);if(H!==null)try{let Z=await c.spawnOrAttach({workspaceCwd:k,modelServiceId:S,...H!==void 0?{clientId:H}:{},...F!==void 0?{sessionScope:F}:{}});if(g&&g.info(Z.attached?"session attached":"session spawned",{sessionId:Z.sessionId,clientId:Z.clientId}),!h.writable){g&&g.warn("session reaped (client disconnected before response)",{sessionId:Z.sessionId,attached:Z.attached}),Z.attached?c.detachClient(Z.sessionId,Z.clientId).catch(()=>{}):c.killSession(Z.sessionId,{requireZeroAttaches:!0}).catch(()=>{});return}h.status(200).json(Z)}catch(Z){v(h,Z,{route:"POST /session"})}});let Ue=b=>async(h,y)=>{let A=st(h,y);if(!A)return;let k=we(h),S=n_(k,s,y);if(S===void 0)return;let R=me(h,y);if(R!==null)try{let F=b==="load"?await c.loadSession({sessionId:A,workspaceCwd:S,...R!==void 0?{clientId:R}:{}}):await c.resumeSession({sessionId:A,workspaceCwd:S,...R!==void 0?{clientId:R}:{}});if(g&&g.info(`session ${b}${F.attached?" (attached)":""}`,{sessionId:F.sessionId,clientId:F.clientId}),!y.writable){F.attached?c.detachClient(F.sessionId,F.clientId).catch(()=>{}):c.killSession(F.sessionId,{requireZeroAttaches:!0}).catch(()=>{});return}y.status(200).json(F)}catch(F){v(y,F,{route:`POST /session/:id/${b}`,sessionId:A})}};n.post("/session/:id/load",V(),Ue("load")),n.post("/session/:id/resume",V(),Ue("resume")),n.post("/session/:id/branch",V(),async(b,h)=>{let y=st(b,h);if(y===null)return;let A=we(b),k=typeof A?.name=="string"?A.name:void 0;k&&(k=k.replace(/[\x00-\x1F\x7F-\x9F]/g,""),k.length>200&&(k=k.slice(0,200)));let S=me(b,h);if(S!==null)try{let R=await c.branchSession(y,{name:k},{clientId:S});if(!h.writable){R.attached?c.detachClient(R.sessionId,R.clientId).catch(()=>{}):c.killSession(R.sessionId,{requireZeroAttaches:!0}).catch(()=>{});return}h.status(201).json(R)}catch(R){v(h,R,{route:"POST /session/:id/branch",sessionId:y})}}),n.get("/session/:id/context",async(b,h)=>{let y=st(b,h);if(y!==null)try{h.status(200).json(await c.getSessionContextStatus(y))}catch(A){v(h,A,{route:"GET /session/:id/context",sessionId:y})}}),n.get("/session/:id/context-usage",async(b,h)=>{let y=st(b,h);if(y!==null)try{h.status(200).json(await c.getSessionContextUsageStatus(y,{detail:b.query.detail==="true"}))}catch(A){v(h,A,{route:"GET /session/:id/context-usage",sessionId:y})}}),n.get("/session/:id/stats",async(b,h)=>{let y=st(b,h);if(y!==null)try{h.status(200).json(await c.getSessionStatsStatus(y))}catch(A){v(h,A,{route:"GET /session/:id/stats",sessionId:y})}}),n.get("/session/:id/supported-commands",async(b,h)=>{let y=st(b,h);if(y!==null)try{h.status(200).json(await c.getSessionSupportedCommandsStatus(y))}catch(A){v(h,A,{route:"GET /session/:id/supported-commands",sessionId:y})}}),n.get("/session/:id/tasks",async(b,h)=>{let y=st(b,h);if(y!==null)try{h.status(200).json(await c.getSessionTasksStatus(y))}catch(A){v(h,A,{route:"GET /session/:id/tasks",sessionId:y})}}),n.get("/session/:id/hooks",async(b,h)=>{let y=st(b,h);if(y!==null)try{h.status(200).json(await c.getSessionHooksStatus(y))}catch(A){v(h,A,{route:"GET /session/:id/hooks",sessionId:y})}}),n.post("/session/:id/tasks/:taskId/cancel",V({strict:!0}),async(b,h)=>{let y=b.params.id,A=b.params.taskId;if(!y||!A){h.status(400).json({error:"`sessionId` and `taskId` route parameters are required"});return}let S=we(b).kind;if(S!=="agent"&&S!=="shell"&&S!=="monitor"){h.status(400).json({error:'`kind` must be "agent", "shell", or "monitor"'});return}try{h.status(200).json(await c.cancelSessionTask(y,A,S))}catch(R){v(h,R,{route:"POST /session/:id/tasks/:taskId/cancel",sessionId:y})}}),n.post("/session/:id/goal/clear",V({strict:!0}),async(b,h)=>{let y=b.params.id;if(!y){h.status(400).json({error:"`sessionId` route parameter is required"});return}try{h.status(200).json(await c.clearSessionGoal(y))}catch(A){v(h,A,{route:"POST /session/:id/goal/clear",sessionId:y})}}),n.post("/session/:id/prompt",V(),async(b,h)=>{let y=b.params.id,A=we(b),k=A.prompt;if(!Array.isArray(k)||k.length===0){h.status(400).json({error:"`prompt` is required and must be a non-empty array of content blocks"});return}if(!k.every(he=>typeof he=="object"&&he!==null&&!Array.isArray(he))){h.status(400).json({error:"each `prompt` element must be an object (content block)"});return}let S=A.deadlineMs,R;if(S!=null){if(typeof S!="number"||!Number.isFinite(S)||!Number.isInteger(S)||S<=0){h.status(400).json({error:"`deadlineMs` must be a positive integer (milliseconds)",code:"invalid_deadline_ms"});return}R=S}let F=me(b,h);if(F===null)return;let H=gd.randomUUID(),Z={...A};delete Z.deadlineMs;let X;try{X=c.getSessionLastEventId(y)}catch(he){v(h,he,{route:"POST /session/:id/prompt",sessionId:y});return}qd("matilda-code.prompt_id",H);let fe=new AbortController,de=K0(t.promptDeadlineMs,R),re;de!==void 0&&(re=setTimeout(()=>{fe.signal.aborted||fe.abort(new Pi(de))},de),re.unref());let xe;try{xe=c.sendPrompt(y,{...Z,sessionId:y,prompt:k},fe.signal,{...F!==void 0?{clientId:F}:{},promptId:H})}catch(he){re!==void 0&&clearTimeout(re),g&&he instanceof Rr&&g.warn("prompt admission rejected: queue full",{sessionId:y,promptId:H,...F!==void 0?{clientId:F}:{},limit:he.limit,pendingCount:he.pendingCount}),v(h,he,{route:"POST /session/:id/prompt",sessionId:y});return}xe.then(()=>{g&&g.info("prompt turn completed",{sessionId:y,promptId:H,clientId:F})},he=>{if(g){let K=he instanceof Error?he.name:void 0;g.warn(`prompt turn failed: ${K?`[${K}] `:""}${he instanceof Error?he.message:String(he)}`,{sessionId:y,promptId:H,clientId:F})}}).finally(()=>{re!==void 0&&clearTimeout(re)}).catch(()=>{}),g&&g.info("prompt enqueued",{sessionId:y,promptId:H,clientId:F}),h.status(202).json({promptId:H,lastEventId:X})}),n.post("/session/:id/heartbeat",V(),(b,h)=>{let y=st(b,h);if(y===null)return;let A=me(b,h);if(A!==null)try{let k=c.recordHeartbeat(y,A!==void 0?{clientId:A}:void 0);h.status(200).json(k)}catch(k){v(h,k,{route:"POST /session/:id/heartbeat",sessionId:y})}}),n.post("/session/:id/detach",V(),async(b,h)=>{let y=st(b,h);if(y===null)return;let A=me(b,h);if(A!==null)try{await c.detachClient(y,A),h.status(204).end()}catch(k){v(h,k,{route:"POST /session/:id/detach",sessionId:y})}}),n.post("/session/:id/cancel",V(),async(b,h)=>{let y=b.params.id,A=we(b),k=me(b,h);if(k!==null)try{await c.cancelSession(y,{...A,sessionId:y},k!==void 0?{clientId:k}:void 0),g&&g.info("cancel sent",{sessionId:y,clientId:k}),h.status(204).end()}catch(S){v(h,S,{route:"POST /session/:id/cancel",sessionId:y})}}),n.delete("/session/:id",async(b,h)=>{let y=b.params.id,A=me(b,h);if(A!==null)try{await c.closeSession(y,A!==void 0?{clientId:A}:void 0),h.status(204).end()}catch(k){v(h,k,{route:"DELETE /session/:id",sessionId:y})}}),n.post("/sessions/delete",V(),async(b,h)=>{if(me(b,h)===null)return;let k=we(b).sessionIds;if(!Array.isArray(k)||k.length===0||k.length>100||!k.every(S=>typeof S=="string")){h.status(400).json({error:"`sessionIds` must be a non-empty string array (max 100)",code:"invalid_request"});return}try{let S=[...new Set(k)],R=await Promise.allSettled(S.map(async X=>(await c.closeSession(X),X))),F=[],H=[];for(let X=0;X<R.length;X++){let fe=R[X],de=S[X];if(fe.status==="fulfilled")H.push(de);else{let re=fe.reason;if(re instanceof ie)H.push(de);else{let xe=re instanceof Error?re.message:String(re);D(`matilda serve: closeSession failed for ${it(de)}: ${it(xe)}`),F.push({sessionId:de,error:xe})}}}let Z=await new tn(s).removeSessions(H);for(let X of Z.errors){let fe=X.error instanceof Error?X.error.message:String(X.error);D(`matilda serve: removeSession failed for ${it(X.sessionId)}: ${it(fe)}`)}h.status(200).json({removed:Z.removed,notFound:Z.notFound,errors:[...F,...Z.errors.map(X=>({sessionId:X.sessionId,error:X.error instanceof Error?X.error.message:String(X.error)}))]})}catch(S){let R=S instanceof Error?S.message:String(S);D(`matilda serve: failed to batch delete sessions: ${it(R)}`),h.status(500).json({error:"Failed to delete sessions",code:"sessions_delete_failed"})}}),n.patch("/session/:id/metadata",async(b,h)=>{let y=b.params.id,A=we(b),k=me(b,h);if(k===null)return;let S=A.displayName;if(S!==void 0&&typeof S!="string"){h.status(400).json({error:"`displayName` must be a string",code:"invalid_metadata",field:"displayName"});return}let R=typeof S=="string"?S.slice(0,256):void 0;try{let F=await c.updateSessionMetadata(y,{displayName:R},k!==void 0?{clientId:k}:void 0);h.status(200).json({sessionId:y,...F})}catch(F){v(h,F,{route:"PATCH /session/:id/metadata",sessionId:y})}}),n.get("/workspace/:id/sessions",async(b,h)=>{let y=b.params.id??"";if(!Ti.isAbsolute(y)){h.status(400).json({error:"`:id` must decode to an absolute workspace path"});return}let A=Qe(y);if(A!==s){h.status(400).json({error:`Workspace mismatch: daemon is bound to "${s}"`,code:"workspace_mismatch",boundWorkspace:s,requestedWorkspace:A});return}try{let k=typeof b.query.cursor=="string"?b.query.cursor:void 0,S=b.query.size,R=typeof S=="string"?parseInt(S,10):void 0,F=await zc(c,A,{cursor:k,size:Number.isFinite(R)?R:void 0});h.status(200).json({sessions:F.sessions,...F.nextCursor!=null?{nextCursor:F.nextCursor}:{}})}catch(k){if(k instanceof Kr){h.status(400).json({error:k.message,code:"invalid_cursor"});return}D(`matilda serve: failed to list sessions for workspace ${it(A)}: ${it(k instanceof Error?k.message:String(k))}`),h.status(500).json({error:"Failed to list sessions",code:"session_list_failed"})}}),n.post("/session/:id/model",V(),async(b,h)=>{let y=b.params.id,A=we(b),k=A.modelId;if(typeof k!="string"||!k){h.status(400).json({error:"`modelId` is required and must be a non-empty string"});return}let S=me(b,h);if(S!==null)try{let R=await c.setSessionModel(y,{...A,sessionId:y,modelId:k},S!==void 0?{clientId:S}:void 0);h.status(200).json(R)}catch(R){v(h,R,{route:"POST /session/:id/model",sessionId:y})}}),n.post("/session/:id/recap",V(),async(b,h)=>{let y=st(b,h);if(y===null)return;let A=me(b,h);if(A!==null)try{let k=await c.generateSessionRecap(y,A!==void 0?{clientId:A}:void 0);if(g){let S=k.recap;g.info(S?`recap generated len=${S.length}`:"recap returned null",{sessionId:y,clientId:A})}h.status(200).json(k)}catch(k){v(h,k,{route:"POST /session/:id/recap",sessionId:y})}}),n.post("/session/:id/btw",V(),async(b,h)=>{let y=st(b,h);if(y===null)return;let k=we(b).question;if(typeof k!="string"||k.trim().length===0||k.length>Ar){h.status(400).json({error:`\`question\` is required, must be a non-empty string, and at most ${Ar} characters`});return}let S=new AbortController,R=()=>{h.writableEnded||S.abort()};h.once("close",R);let F=me(b,h);if(F===null){h.off("close",R);return}try{let H=await c.generateSessionBtw(y,k.trim(),S.signal,F!==void 0?{clientId:F}:void 0);h.status(200).json(H)}catch(H){if(H instanceof DOMException&&H.name==="AbortError"&&S.signal.aborted)return;v(h,H,{route:"POST /session/:id/btw",sessionId:y})}finally{h.off("close",R)}});let be=16*1024;n.post("/session/:id/mid-turn-message",V(),(b,h)=>{let y=st(b,h);if(y===null)return;let k=we(b).message,S=typeof k=="string"?k.trim():"";if(S.length===0){h.status(400).json({error:"`message` is required and must be a non-empty string"});return}if(S.length>be){h.status(400).json({error:`\`message\` must be at most ${be} characters`});return}let R=me(b,h);if(R!==null)try{let F=c.enqueueMidTurnMessage(y,S,R!==void 0?{clientId:R}:void 0);h.status(200).json(F)}catch(F){v(h,F,{route:"POST /session/:id/mid-turn-message",sessionId:y})}}),n.post("/session/:id/shell",V({strict:!0}),async(b,h)=>{let y=b.params.id;if(!a){v(h,new bt,{route:"POST /session/:id/shell",sessionId:y});return}let A=me(b,h);if(A===null)return;if(A===void 0){v(h,new St,{route:"POST /session/:id/shell",sessionId:y});return}let S=we(b).command;if(typeof S!="string"||S.trim().length===0){h.status(400).json({error:"`command` is required and must be a non-empty string"});return}let R=new AbortController,F=()=>{h.writableEnded||R.abort()};h.once("close",F);try{let H=await c.executeShellCommand(y,S.trim(),R.signal,{clientId:A});g&&g.info("shell command completed",{sessionId:y,clientId:A,exitCode:H.exitCode}),h.status(200).json(H)}catch(H){if(H instanceof DOMException&&H.name==="AbortError"&&R.signal.aborted)return;v(h,H,{route:"POST /session/:id/shell",sessionId:y})}finally{h.off("close",F)}}),n.get("/session/:id/rewind/snapshots",async(b,h)=>{let y=b.params.id;if(!y){h.status(400).json({error:"`sessionId` route parameter is required"});return}try{h.status(200).json(await c.getRewindSnapshots(y))}catch(A){v(h,A,{route:"GET /session/:id/rewind/snapshots",sessionId:y})}}),n.post("/session/:id/rewind",V({strict:!0}),async(b,h)=>{let y=b.params.id,k=we(b).promptId;if(typeof k!="string"||k.length===0){h.status(400).json({error:"`promptId` is required and must be a non-empty string",code:"missing_prompt_id"});return}let S=me(b,h);if(S!==null)try{let R=await c.rewindSession(y,{promptId:k},S!==void 0?{clientId:S}:void 0);h.status(200).json(R)}catch(R){v(h,R,{route:"POST /session/:id/rewind",sessionId:y})}}),n.post("/session/:id/approval-mode",V({strict:!0}),async(b,h)=>{let y=b.params.id,A=we(b),k=A.mode,S=A.persist;if(typeof k!="string"||!tt.includes(k)){h.status(400).json({error:"`mode` is required and must be one of the allowed values",code:"invalid_approval_mode",allowed:tt});return}if(S!==void 0&&typeof S!="boolean"){h.status(400).json({error:"`persist` must be a boolean when provided",code:"invalid_persist_flag"});return}let R=me(b,h);if(R!==null)try{let F=await c.setSessionApprovalMode(y,k,{persist:S===!0},R!==void 0?{clientId:R}:void 0);h.status(200).json(F)}catch(F){v(h,F,{route:"POST /session/:id/approval-mode",sessionId:y})}}),n.post("/session/:id/language",V(),async(b,h)=>{let y=b.params.id,A=we(b),k=A.language,S=A.syncOutputLanguage;if(typeof k!="string"||!Te.includes(k)){h.status(400).json({error:"`language` is required and must be one of: "+Te.join(", "),code:"invalid_language",allowed:Te});return}if(S!==void 0&&typeof S!="boolean"){h.status(400).json({error:"`syncOutputLanguage` must be a boolean when provided",code:"invalid_sync_flag"});return}let R=me(b,h);if(R!==null)try{let F=await c.setSessionLanguage(y,{language:k,syncOutputLanguage:S===!0},R!==void 0?{clientId:R}:void 0);h.status(200).json(F)}catch(F){v(h,F,{route:"POST /session/:id/language",sessionId:y})}}),n.post("/workspace/mcp/:server/restart",V({strict:!0}),async(b,h)=>{let y=b.params.server;if(!y||typeof y!="string"){h.status(400).json({error:"Server name path parameter is required",code:"invalid_server_name"});return}if(y.length>rr){h.status(400).json({error:`Server name exceeds ${rr}-character limit`,code:"invalid_server_name"});return}let A=tr(b,h,c);if(A===null)return;let k,S=b.query.entryIndex;if(S!==void 0&&S!=="*"){let R=typeof S=="string"?S:void 0,F=R!==void 0?Number.parseInt(R,10):NaN;if(!Number.isInteger(F)||F<0||String(F)!==R){h.status(400).json({error:'`entryIndex` query parameter must be a non-negative integer or "*"',code:"invalid_entry_index"});return}k=F}try{let R=Se(b,"POST /workspace/mcp/:server/restart",A),F=await O.restartMcpServer(R,y,k!==void 0?{entryIndex:k}:void 0);h.status(200).json(F)}catch(R){v(h,R,{route:"POST /workspace/mcp/:server/restart"})}});for(let[b,h]of[["enable","enable"],["disable","disable"],["authenticate","authenticate"],["clear-auth","clear-auth"]])n.post(`/workspace/mcp/:server/${b}`,V({strict:!0}),async(y,A)=>{let k=y.params.server;if(!k||typeof k!="string"){A.status(400).json({error:"Server name path parameter is required",code:"invalid_server_name"});return}if(k.length>rr){A.status(400).json({error:`Server name exceeds ${rr}-character limit`,code:"invalid_server_name"});return}let S=tr(y,A,c);if(S!==null)try{let R=await c.manageMcpServer(k,h,S);A.status(200).json(R)}catch(R){v(A,R,{route:`POST /workspace/mcp/:server/${b}`})}});return n.post("/workspace/mcp/servers",V({strict:!0}),async(b,h)=>{let y=we(b),A=y.name;if(!Y0(A,h))return;let k=y.config;if(typeof k!="object"||k===null||Array.isArray(k)){h.status(400).json({error:"`config` must be a non-null object",code:"missing_required_field",field:"config"});return}let S=tr(b,h,c);if(S!==null){if(!S){h.status(400).json({error:"`X-Matilda-Client-Id` header is required for runtime MCP mutation",code:"missing_client_id"});return}try{let R=await c.addRuntimeMcpServer(A,k,S);h.status(200).json(R)}catch(R){v(h,R,{route:"POST /workspace/mcp/servers"})}}}),n.delete("/workspace/mcp/servers/:name",V({strict:!0}),async(b,h)=>{let y=b.params.name??"";if(!Y0(y,h))return;let A=tr(b,h,c);if(A!==null){if(!A){h.status(400).json({error:"`X-Matilda-Client-Id` header is required for runtime MCP mutation",code:"missing_client_id"});return}try{let k=await c.removeRuntimeMcpServer(y,A);h.status(200).json(k)}catch(k){v(h,k,{route:"DELETE /workspace/mcp/servers/:name"})}}}),n.post("/workspace/init",V({strict:!0}),async(b,h)=>{let A=we(b).force;if(A!==void 0&&typeof A!="boolean"){h.status(400).json({error:"`force` must be a boolean when provided",code:"invalid_force_flag"});return}let k=tr(b,h,c);if(k!==null)try{let S=Se(b,"POST /workspace/init",k),R=await O.initWorkspace(S,{force:A===!0});h.status(200).json(R)}catch(S){v(h,S,{route:"POST /workspace/init"})}}),n.post("/workspace/reload",V({strict:!0}),async(b,h)=>{let y=tr(b,h,c);if(y!==null)try{let A=Se(b,"POST /workspace/reload",y),k=await O.reload(A);h.status(200).json(k)}catch(A){v(h,A,{route:"POST /workspace/reload"})}}),n.post("/workspace/tools/:name/enable",V({strict:!0}),async(b,h)=>{let y=b.params.name;if(!y||typeof y!="string"){h.status(400).json({error:"Tool name path parameter is required",code:"invalid_tool_name"});return}let A=y.trim();if(A.length===0){h.status(400).json({error:"Tool name path parameter is required",code:"invalid_tool_name"});return}if(A.length>X0){h.status(400).json({error:`Tool name exceeds ${X0}-character limit`,code:"invalid_tool_name"});return}let S=we(b).enabled;if(typeof S!="boolean"){h.status(400).json({error:"`enabled` is required and must be a boolean",code:"invalid_enabled_flag"});return}let R=tr(b,h,c);if(R!==null)try{let F=Se(b,"POST /workspace/tools/:name/enable",R),H=await O.setWorkspaceToolEnabled(F,A,S);h.status(200).json(H)}catch(F){v(h,F,{route:"POST /workspace/tools/:name/enable"})}}),n.post("/session/:id/permission/:requestId",V(),(b,h)=>{let y=b.params.id,A=b.params.requestId,k=Z0(b,h);if(k===void 0)return;let S=me(b,h);if(S===null)return;let R=Q0(b),F={...S!==void 0?{clientId:S}:{},fromLoopback:R},H;try{H=c.respondToSessionPermission(y,A,k,F)}catch(Z){x(h,Z,{route:"POST /session/:id/permission/:requestId",sessionId:y});return}if(!H){h.status(404).json({error:"No pending permission request for session",sessionId:y,requestId:A});return}h.status(200).json({})}),n.post("/permission/:requestId",V(),(b,h)=>{let y=b.params.requestId,A=Z0(b,h);if(A===void 0)return;let k=me(b,h);if(k===null)return;let S=Q0(b),R={...k!==void 0?{clientId:k}:{},fromLoopback:S},F;try{F=c.respondToPermission(y,A,R)}catch(H){x(h,H,{route:"POST /permission/:requestId"});return}if(!F){h.status(404).json({error:"No pending permission request",requestId:y});return}h.status(200).json({})}),n.get("/session/:id/events",(b,h)=>{let y=b.params.id,A=c_(b.headers["last-event-id"]),k=a_(b.query.maxQueued,h);if(k===null)return;let S,R=new AbortController;try{let K=b.query.snapshot==="1";S=c.subscribeEvents(y,{signal:R.signal,lastEventId:A,...k!==void 0?{maxQueued:k}:{},...K?{snapshot:!0}:{}})[Symbol.asyncIterator]()}catch(K){if(K instanceof Ou){D(`matilda serve: subscriber limit reached for session ${y} (limit=${K.limit}); rejecting new SSE client with 429`),h.setHeader("Retry-After","5"),h.status(429).json({error:K.message,code:"subscriber_limit_exceeded",limit:K.limit});return}v(h,K,{route:"GET /session/:id/events",sessionId:y});return}if(g){let K=Date.now(),Q=b.headers["x-matilda-client-id"];g.info("SSE stream opened",{sessionId:y,clientId:Q}),h.on("close",()=>{try{g.info("SSE stream closed",{sessionId:y,clientId:Q,durationMs:Date.now()-K})}catch{}})}h.status(200),h.setHeader("Content-Type","text/event-stream"),h.setHeader("Cache-Control","no-cache, no-transform"),h.setHeader("Connection","keep-alive"),h.setHeader("X-Accel-Buffering","no"),h.flushHeaders(),wd++;let F=!0;h.on("close",()=>{F&&(F=!1,wd--)});let H=Promise.resolve(),Z=t.writerIdleTimeoutMs!==void 0&&t.writerIdleTimeoutMs>0,X=Z?Date.now():0,fe=K=>new Promise((Q,Ee)=>{if(h.writableEnded){Q();return}let et;try{et=h.write(K)}catch(ne){Ee(ne);return}if(et){Z&&(X=Date.now()),Q();return}let De=()=>{h.off("close",Fe),h.off("error",Ne),Z&&(X=Date.now()),Q()},Fe=()=>{h.off("drain",De),h.off("error",Ne),Q()},Ne=ne=>{h.off("drain",De),h.off("close",Fe),Ee(ne)};h.once("drain",De),h.once("close",Fe),h.once("error",Ne)}),de=K=>{let Q=H.then(()=>fe(K));return H=Q.catch(()=>{}),Q};de(`retry: 3000
|
|
717
717
|
|
|
718
718
|
`).catch(()=>{});let re=setInterval(()=>{h.writableEnded||de(`: heartbeat
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{
|
|
3
|
+
import{ef as a,ff as b,gf as c,hf as d,if as e,jf as f,kf as g}from"./chunk-4TV7Y2I2.js";import"./chunk-TZIDSCTF.js";import"./chunk-ROETRE5J.js";import"./chunk-INAZKGGR.js";import"./chunk-DCQKJTAX.js";import"./chunk-LSDMWVW6.js";import"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-VYTYYCBR.js";import"./chunk-TISQNFB5.js";import"./chunk-34DXSYJZ.js";import"./chunk-47XR7IMP.js";import"./chunk-FWIVFCKF.js";import"./chunk-QKYGQLWC.js";import"./chunk-FRL6KOLY.js";import"./chunk-VWWEEU4V.js";import"./chunk-RNKDFE2S.js";import"./chunk-Q2I3ARPJ.js";import"./chunk-CRGV5RTO.js";import"./chunk-QHA3ZBRO.js";import"./chunk-ZYUCUBVQ.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-S7G6QPEP.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-B3NVKOSU.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-32PTAACU.js";import"./chunk-32T6RWWT.js";import"./chunk-6B5BDE7S.js";import"./chunk-RJX7DK4Y.js";import"./chunk-XCJYORZX.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-EQEQPZLQ.js";import"./chunk-VLYRNOD3.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";export{b as OUTPUT_UPDATE_INTERVAL_MS,g as ShellTool,f as ShellToolInvocation,c as buildLongRunningForegroundHint,d as detectBlockedSleepPattern,a as parseNumstat,e as repairLeakedShellToolArgMarkup};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{c as p,d as C,f as E,g as I}from"./chunk-FRL6KOLY.js";import"./chunk-VWWEEU4V.js";import"./chunk-
|
|
3
|
+
import{c as p,d as C,f as E,g as I}from"./chunk-FRL6KOLY.js";import"./chunk-VWWEEU4V.js";import"./chunk-ZYUCUBVQ.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-S7G6QPEP.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import{kc as o,ld as a}from"./chunk-B3NVKOSU.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-32PTAACU.js";import"./chunk-32T6RWWT.js";import{g as S,i as v,p as y,q as b}from"./chunk-6B5BDE7S.js";import"./chunk-3YLXGE6T.js";import"./chunk-EQEQPZLQ.js";import{aa as f}from"./chunk-VLYRNOD3.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as u}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";u();import L from"path";var r=f("SKILL"),$=`Execute a skill within the main conversation
|
|
4
4
|
|
|
5
5
|
<skills_instructions>
|
|
6
6
|
When users ask you to perform tasks, check if any of the available skills can help complete the task more effectively. Skills provide specialized capabilities and domain knowledge.
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
// Force strict mode and setup for ESM
|
|
2
|
+
"use strict";
|
|
3
|
+
import{$ as ui,$a as tj,$b as xk,$c as ul,$d as um,$e as fn,$f as go,$g as dq,$h as er,$i as es,$j as ct,$k as cu,A as ah,Aa as Ui,Ab as Uj,Ac as Xk,Ad as Vl,Af as zn,Ag as Bo,Ah as Fq,Ai as Hr,Aj as Cs,Ak as Dt,Al as Du,B as bh,Ba as Vi,Bb as Vj,Bc as Yk,Bd as Wl,Bg as Co,Bh as Gq,Bi as Ir,Bj as Ds,Bk as Et,Bl as Eu,C as ch,Ca as Wi,Cb as Wj,Cc as Zk,Cd as Xl,Cg as Do,Ch as Hq,Ci as Jr,Cj as Es,Ck as Ft,D as dh,Da as Xi,Db as Xj,Dc as _k,Dd as Yl,De as Sm,Dg as Eo,Dh as Iq,Di as Kr,Dj as Fs,Dk as Gt,Dl as Fu,E as eh,Ea as Yi,Eb as Yj,Ec as $k,Ed as Zl,Ee as Tm,Ef as An,Eg as Fo,Eh as Jq,Ei as Lr,Ej as Gs,Ek as Ht,El as Gu,F as fh,Fa as Zi,Fb as Zj,Fc as al,Fd as _l,Fe as Um,Ff as Bn,Fg as No,Fh as Kq,Fi as Mr,Fj as Hs,Fk as It,Fl as Hu,G as gh,Ga as _i,Gb as _j,Gc as bl,Gd as $l,Gf as Cn,Gg as Oo,Gh as Lq,Gi as Nr,Gj as Is,Gk as Jt,Gl as Iu,H as hh,Ha as $i,Hb as $j,Hd as am,He as Vm,Hf as Dn,Hg as Lp,Hh as Mq,Hi as Or,Hj as Js,Hk as Kt,Hl as Ju,Ia as aj,Ib as ak,Ic as cl,Id as bm,Ie as Wm,If as En,Ig as Mp,Ih as Nq,Ii as Pr,Ij as Ks,Ik as Lt,Il as Ku,J as ih,Ja as bj,Jb as bk,Jc as dl,Jd as cm,Je as Xm,Jf as Fn,Jg as Np,Jh as Oq,Ji as Qr,Jj as Ls,Jk as Mt,Jl as Lu,K as jh,Ka as cj,Kb as ck,Kc as el,Kd as dm,Ke as Ym,Kf as Gn,Kg as Op,Kh as Pq,Ki as Rr,Kj as Ms,Kk as Nt,Kl as Mu,L as kh,La as dj,Lb as dk,Lc as fl,Ld as em,Le as Zm,Lf as Hn,Lg as Pp,Lh as Qq,Li as Sr,Lj as Ns,Lk as Ot,Ll as Nu,M as ei,Ma as ej,Mb as ek,Mc as gl,Md as fm,Me as _m,Mf as In,Mg as Qp,Mh as Rq,Mi as Tr,Mj as Os,Mk as Pt,Ml as Ou,N as fi,Na as fj,Nb as fk,Nc as hl,Nd as gm,Ne as $m,Nf as Jn,Ng as Rp,Nh as Sq,Nj as Ps,Nk as Qt,Nl as Pu,O as gi,Oa as gj,Ob as gk,Oc as il,Od as hm,Of as Kn,Og as Sp,Oh as Tq,Oj as Qs,Ok as Rt,Ol as Qu,P as hi,Pa as hj,Pb as hk,Pc as jl,Pd as im,Pe as an,Pf as Ln,Pg as Tp,Ph as Uq,Pi as Ur,Pk as St,Pl as Ru,Q as ii,Qa as ij,Qb as ik,Qd as jm,Qe as bn,Qf as Wn,Qg as Up,Qh as Vq,Qi as Vr,Qk as Tt,Ql as Su,R as ji,Ra as jj,Rb as jk,Rc as kl,Rd as km,Rf as Xn,Rg as Vp,Rh as Wq,Ri as Wr,Rj as Rs,Rk as Ut,Rl as Tu,S as ki,Sa as kj,Sb as kk,Sc as ll,Sd as lm,Sf as Yn,Sg as Wp,Sh as Xq,Si as Xr,Sj as Ss,Sk as Vt,Sl as Uu,T as li,Ta as lj,Tb as lk,Tc as ml,Td as mm,Tf as Zn,Tg as Xp,Th as Yq,Ti as Yr,Tj as Ts,Tk as Wt,Tl as Vu,U as mi,Ua as mj,Ub as mk,Uc as nl,Ud as nm,Uf as _n,Ug as Yp,Uh as Zq,Ui as Zr,Uj as Us,Uk as Xt,Ul as Wu,V as ni,Va as nj,Vb as nk,Vc as ol,Vd as om,Vf as $n,Vg as Zp,Vh as _q,Vi as _r,Vj as Vs,Vk as Yt,Vl as Xu,W as oi,Wa as oj,Wb as qk,Wc as pl,Wd as pm,Wf as ao,Wg as _p,Wh as $q,Wi as $r,Wj as Ws,Wk as Zt,Wl as Yu,X as qi,Xa as pj,Xb as tk,Xc as ql,Xd as qm,Xf as bo,Xg as $p,Xh as ar,Xi as as,Xj as _s,Xk as _t,Xl as Zu,Y as ri,Ya as qj,Yb as uk,Yc as rl,Yd as rm,Ye as cn,Yf as co,Yg as aq,Yh as br,Yi as bs,Yj as $s,Yk as $t,Z as si,Za as rj,Zb as vk,Zc as sl,Zd as sm,Ze as dn,Zf as eo,Zg as bq,Zh as cr,Zi as cs,Zj as at,Zk as au,_ as ti,_a as sj,_b as wk,_c as tl,_d as tm,_e as en,_f as fo,_g as cq,_h as dr,_i as ds,_j as bt,_k as bu,a as ta,aa as vi,ab as uj,ac as yk,ad as vl,ae as vm,af as gn,ag as ho,ah as eq,ai as fr,ak as dt,al as du,b as ua,ba as wi,bb as vj,bc as zk,bd as wl,be as wm,bf as hn,bg as io,bh as fq,bi as gr,bj as fs,bk as et,bl as eu,c as va,ca as xi,cb as wj,cc as Ak,cd as xl,ce as xm,cf as jn,cg as jo,ch as gq,ci as hr,cj as gs,ck as ft,cl as fu,d as wa,da as yi,db as xj,dc as Bk,dd as yl,de as ym,dg as ko,dh as hq,di as ir,dj as hs,dk as gt,dl as gu,e as xa,ea as zi,eb as yj,ec as Ck,ed as zl,ee as zm,eg as lo,eh as iq,ei as jr,ej as is,ek as ht,el as hu,f as ya,fa as Ai,fb as zj,fc as Dk,fd as Al,fe as Am,fg as mo,fh as jq,fi as kr,fj as js,fk as it,fl as iu,g as za,ga as Bi,gb as Aj,gc as Ek,gd as Bl,ge as Bm,gg as no,gh as kq,gi as lr,gj as ks,gk as jt,gl as ju,h as Aa,ha as Ci,hb as Bj,hc as Fk,hd as Cl,he as Cm,hg as oo,hh as lq,hi as mr,hj as ls,hk as kt,hl as ku,i as Ba,ia as Di,ib as Cj,ic as Gk,id as Dl,ie as Dm,ig as po,ih as mq,ii as nr,ik as lt,il as lu,j as Lg,ja as Ei,jb as Dj,jc as Hk,jd as El,je as Em,jg as qo,jh as nq,ji as or,jk as mt,jl as mu,k as Mg,kb as Ej,kc as Ik,kd as Fl,ke as Fm,kg as ro,kh as oq,ki as rr,kj as ms,kk as nt,kl as nu,l as Ng,la as Fi,lb as Fj,lc as Jk,ld as Gl,le as Gm,lf as kn,lg as so,lh as pq,li as sr,lj as ns,lk as ot,ll as ou,m as Og,ma as Gi,mb as Gj,mc as Kk,md as Hl,me as Hm,mf as ln,mh as rq,mi as tr,mj as os,mk as pt,ml as pu,n as Pg,na as Hi,nb as Hj,nc as Lk,nd as Il,ne as Im,nf as mn,nh as sq,ni as ur,nj as ps,nk as qt,nl as qu,o as Qg,oa as Ii,ob as Ij,oc as Mk,od as Jl,oe as Jm,of as nn,oh as tq,oi as vr,oj as qs,ok as rt,ol as ru,p as Rg,pa as Ji,pb as Jj,pc as Nk,pd as Kl,pe as Km,pf as on,ph as uq,pi as wr,pj as rs,pk as st,pl as su,q as Sg,qa as Ki,qb as Kj,qc as Ok,qd as Ll,qe as Lm,qf as pn,qh as vq,qi as xr,qj as ss,qk as tt,ql as tu,r as Tg,ra as Li,rb as Lj,rc as Pk,rd as Ml,re as Mm,rf as qn,rh as wq,ri as yr,rj as ts,rk as ut,rl as uu,s as Ug,sa as Mi,sb as Mj,sc as Qk,sd as Nl,se as Nm,sf as rn,sg as to,sh as xq,si as zr,sj as us,sk as vt,sl as vu,t as Vg,ta as Ni,tb as Nj,tc as Rk,td as Ol,te as Om,tf as sn,tg as uo,th as yq,ti as Ar,tj as vs,tk as wt,tl as wu,u as Wg,ua as Oi,ub as Oj,uc as Sk,ud as Pl,ue as Pm,uf as tn,ug as vo,uh as zq,ui as Br,uj as ws,uk as xt,ul as xu,v as Xg,va as Pi,vb as Pj,vc as Tk,vd as Ql,vf as un,vg as wo,vh as Aq,vi as Cr,vj as xs,vk as yt,vl as yu,w as Yg,wa as Qi,wb as Qj,wc as Uk,wd as Rl,wf as vn,wg as xo,wh as Bq,wi as Dr,wj as ys,wk as zt,wl as zu,x as Zg,xa as Ri,xb as Rj,xd as Sl,xe as Qm,xf as wn,xg as yo,xh as Cq,xi as Er,xj as zs,xk as At,xl as Au,y as _g,ya as Si,yb as Sj,yc as Vk,yd as Tl,ye as Rm,yf as xn,yg as zo,yh as Dq,yi as Fr,yj as As,yk as Bt,yl as Bu,z as $g,za as Ti,zb as Tj,zc as Wk,zd as Ul,zf as yn,zg as Ao,zh as Eq,zi as Gr,zj as Bs,zk as Ct,zl as Cu}from"./chunk-4TV7Y2I2.js";import"./chunk-TZIDSCTF.js";import{a as Po,b as Qo,c as Ro,d as So,e as To,f as mp,g as np,h as op,i as pp,j as qp,k as rp,l as sp,m as tp}from"./chunk-ROETRE5J.js";import{a as up,b as vp,c as wp,d as xp,e as yp,f as zp,g as Ap,h as Bp,i as Cp,j as Dp,k as Ep,l as Fp,m as Gp,n as Hp,o as Ip,p as Jp,q as Kp}from"./chunk-INAZKGGR.js";import{c as Uo,d as Vo,e as Wo,f as Xo,g as Yo,h as Zo,i as _o,j as $o,k as ap,l as bp,m as cp,n as dp,o as ep,p as fp,q as gp,r as hp,s as ip,t as jp,u as kp,v as lp}from"./chunk-DCQKJTAX.js";import{a as pi}from"./chunk-LSDMWVW6.js";import{c as Xs,e as Ys,f as Zs}from"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-VYTYYCBR.js";import"./chunk-TISQNFB5.js";import{b as lh,c as mh,d as nh,e as oh,f as ph,g as qh,h as rh,i as sh,j as th,k as uh,l as vh,m as wh,n as xh,o as Xh,p as Yh,q as Zh,r as _h,s as $h,t as ai,u as bi,v as ci,w as di}from"./chunk-34DXSYJZ.js";import{a as pr,b as qr}from"./chunk-47XR7IMP.js";import{b as qq}from"./chunk-FWIVFCKF.js";import{a as Mn,b as Nn,c as On,d as Pn,e as Qn,f as Rn,g as Sn,h as Tn,i as Un,j as Vn,k as Go,l as Ho,m as Io,n as Jo,o as Ko,p as Lo,q as Mo}from"./chunk-QKYGQLWC.js";import{c as rk,f as sk}from"./chunk-FRL6KOLY.js";import{a as yh,b as zh,c as Ah,d as Bh,e as Ch,f as Dh,g as Eh,h as Fh,i as Gh,j as Hh,k as Ih,l as Jh,m as Kh,n as Lh,o as Mh,p as Nh,q as Oh,r as Ph,s as Qh,t as Rh,u as Sh,v as Th,w as Uh,x as Vh,y as Wh}from"./chunk-VWWEEU4V.js";import{a as ok,b as pk}from"./chunk-RNKDFE2S.js";import"./chunk-Q2I3ARPJ.js";import"./chunk-CRGV5RTO.js";import{b as gg,d as hg,e as ig,g as jg,h as kg,i as lg,j as mg,k as ng}from"./chunk-QHA3ZBRO.js";import{A as Ue,B as Ve,C as We,D as Xe,E as Ye,F as Ze,G as _e,H as $e,I as af,J as bf,K as cf,L as df,P as sf,Q as tf,T as uf,U as vf,V as wf,X as Pf,Y as Qf,Z as Rf,aa as Sf,b as te,c as ue,ca as Tf,d as ve,da as Uf,e as we,ea as Vf,fa as Yf,ga as Zf,ha as _f,i as xe,ia as $f,j as ye,ja as ag,k as ze,ka as bg,l as Fe,la as cg,m as Ge,ma as dg,n as He,na as eg,o as Ie,oa as fg,p as Je,pa as Gg,q as Ke,qa as Hg,r as Le,ra as Ig,s as Me,sa as Jg,t as Ne,ta as Kg,u as Oe,v as Pe,w as Qe,x as Re,y as Se,z as Te}from"./chunk-ZYUCUBVQ.js";import{a as xf,b as yf,c as zf,d as Af}from"./chunk-4F4DA5UI.js";import{a as Lf,e as Mf,f as Nf,g as Of}from"./chunk-DC7LAFZZ.js";import{e as Ae,f as Be,g as Ce,h as De,i as Ee,m as Bf,n as Cf,o as Df,p as Ef,q as Ff,r as Gf,s as Hf,t as If,u as Jf,v as Kf}from"./chunk-S7G6QPEP.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import{b as ef,c as ff,d as gf,e as hf,f as jf,g as kf,h as lf,i as mf,j as nf,k as of,l as pf,m as qf,n as rf}from"./chunk-SDTWBD62.js";import{$ as fb,A as Ta,Aa as Fb,Ab as xc,B as Ua,Ba as Gb,Bb as yc,C as Va,Ca as Hb,Cb as zc,Cc as Hd,D as Wa,Da as Ib,Db as Ac,Dc as Id,E as Xa,Ea as Jb,Eb as Bc,Ec as Jd,F as Ya,Fa as Kb,Fb as Cc,Fc as Kd,G as Za,Ga as Lb,Gb as Dc,Gc as Ld,H as _a,Ha as Mb,Hb as Ec,Hc as Md,I as $a,Ia as Nb,Ib as Fc,Ic as Nd,Ja as Ob,Jb as Gc,Jc as Od,Ka as Pb,Kb as Hc,Kc as Pd,La as Qb,Lc as Qd,Ma as Rb,Mb as Ic,Mc as Rd,Na as Sb,Nb as Jc,Nc as Sd,Ob as Kc,Oc as Td,Pb as Lc,Pc as Ud,Qa as Tb,Qb as Mc,Rb as Nc,Sc as Vd,Ta as Ub,Tc as Wd,Ua as Vb,Ub as Oc,Uc as Xd,Va as Wb,Vb as Pc,Vc as Yd,W as ab,Wa as Xb,Wb as Qc,Wc as Zd,X as bb,Xa as Yb,Xb as Rc,Xc as _d,Y as cb,Ya as Zb,Yb as Sc,Yc as $d,Z as db,Za as _b,Zb as Tc,Zc as ae,_ as eb,_a as $b,aa as gb,ab as ac,b as ba,ba as hb,bb as bc,c as ca,ca as ib,cb as cc,cc as Uc,cd as be,d as da,da as jb,db as dc,dd as ce,e as qa,ea as kb,eb as ec,ec as Vc,ed as de,fa as lb,fb as fc,fc as Wc,g as ra,ga as mb,gb as gc,gc as Xc,gd as ee,h as sa,ha as nb,hb as hc,hc as Yc,hd as fe,ia as ob,ib as ic,ic as Zc,ja as pb,jb as jc,jc as _c,jd as ge,ka as qb,kb as kc,kc as $c,la as rb,lb as lc,lc as ad,ld as he,ma as sb,mb as mc,mc as bd,md as ie,n as Ga,nb as nc,nc as cd,nd as je,o as Ha,oa as tb,ob as oc,oc as dd,od as ke,p as Ia,pa as ub,pb as pc,pc as ed,pd as le,q as Ja,qa as vb,qb as qc,qc as fd,qd as me,r as Ka,ra as wb,rb as rc,rc as gd,rd as ne,s as La,sa as xb,sb as sc,sc as hd,sd as oe,t as Ma,ta as yb,tc as id,td as pe,u as Na,ua as zb,ud as qe,v as Oa,va as Ab,vd as re,w as Pa,wa as Bb,wb as tc,wc as Gd,wd as se,x as Qa,xa as Cb,xb as uc,y as Ra,ya as Db,yb as vc,z as Sa,za as Eb,zb as wc}from"./chunk-B3NVKOSU.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import{a as jd,b as kd,c as ld,d as md,e as nd,f as od,g as pd,h as qd,i as rd,j as sd,k as td,l as ud,m as vd,n as wd,o as xd,p as yd,q as zd,r as Ad,s as Bd,t as Cd,u as Dd,v as Ed,w as Fd}from"./chunk-32PTAACU.js";import"./chunk-32T6RWWT.js";import{a as ea,e as fa,f as ga,g as ha,h as ia,i as ja,j as ka,k as la,l as ma,m as na,n as oa,o as pa,p as Ca,q as Da,r as Ea,s as Fa}from"./chunk-6B5BDE7S.js";import{a as og,b as pg,d as qg,e as rg,f as sg,g as tg,h as ug,i as vg,j as wg,k as xg,l as yg,m as zg,n as Ag,o as Bg,p as Cg,q as Dg,r as Eg,t as Fg}from"./chunk-RJX7DK4Y.js";import"./chunk-XCJYORZX.js";import"./chunk-ESSYHTAZ.js";import{a as Wf,b as Xf}from"./chunk-3YLXGE6T.js";import{a as Y,b as Z,c as _,d as $,e as aa}from"./chunk-EQEQPZLQ.js";import{$ as W,A as z,B as A,C as B,D as C,E as D,F as E,G as F,H as G,I as H,J as I,K as J,L as K,M as L,N as M,P as N,Q as O,U as R,V as S,Y as T,Z as U,_ as V,aa as X,b as a,c as b,d as c,e as d,f as e,g as f,h as g,i as h,j as i,k as j,l as k,m as l,n as m,o as n,p as o,q as p,r as q,s as r,t as s,u as t,v as u,w as v,x as w,y as x,z as y}from"./chunk-VLYRNOD3.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import{c as P,g as Q}from"./chunk-FWDMPRKU.js";import"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";export{Ha as AGENT_CONTEXT_FILENAME,jo as AGENT_WORKTREE_HEX_LENGTH,io as AGENT_WORKTREE_PREFIX,ko as AGENT_WORKTREE_SLUG_PATTERN,Kj as ALL_PROVIDERS,$s as APPROVAL_MODES,bt as APPROVAL_MODE_INFO,ta as ARENA_MAX_AGENTS,nd as AUTO_MEMORY_CONSOLIDATION_LOCK_FILENAME,jd as AUTO_MEMORY_DIRNAME,md as AUTO_MEMORY_EXTRACT_CURSOR_FILENAME,kd as AUTO_MEMORY_INDEX_FILENAME,ld as AUTO_MEMORY_METADATA_FILENAME,Wk as AUTO_MEMORY_SCHEMA_VERSION,Vk as AUTO_MEMORY_TYPES,km as AUTO_MODE_DENIAL_LIMITS,dq as AUTO_SKILL_THRESHOLD,Fu as AbortError,r as AccountRestrictedError,Yn as AgentCore,In as AgentEventEmitter,Hn as AgentEventType,Ln as AgentHeadless,xo as AgentInteractive,ga as AgentStatistics,xa as AgentStatus,wa as AgentTerminateMode,Vh as AgentType,Qd as ApiCancelEvent,Pd as ApiErrorEvent,Od as ApiRequestEvent,sb as ApiRequestPhase,Rd as ApiResponseEvent,_s as ApprovalMode,Ba as ArenaAgentClient,Bo as ArenaEventEmitter,Ao as ArenaEventType,Fo as ArenaManager,ua as ArenaSessionStatus,wo as AsyncMessageQueue,ge as AuthEvent,jt as AuthProviderType,Gg as AuthType,Op as BACKGROUND_AGENT_CONCURRENCY_ENV,go as BASELINE_COMMIT_MESSAGE,Wa as BINARY_EXTENSIONS,Oa as BINARY_FILE_PATTERNS,Pu as BTW_MAX_INPUT_LENGTH,Wq as BUNDLE_CHUNK_DIR,Vp as BackgroundAgentResumeService,Hr as BackgroundShellRegistry,Tp as BackgroundTaskRegistry,q as BadRequestError,ja as BaseDeclarativeTool,ha as BaseToolInvocation,kr as BudgetExhaustedError,so as BuiltinAgentRegistry,Df as CAPPED_DEFAULT_MAX_TOKENS,hu as CODE_ACTION_KIND_LABELS,yl as COMMAND_SUBSTITUTION_WARNING,Qa as COMMON_DIRECTORY_EXCLUDES,Na as COMMON_IGNORE_PATTERNS,pa as CONCURRENCY_SAFE_KINDS,Hj as CUSTOM_API_KEY_ENV_PREFIX,Yj as ChatRecordingService,zn as CloseDiffRequestSchema,Wm as ColorMode,ak as CompressionStatus,Fs as ConditionalRulesRegistry,kt as Config,t as ContentBlockedError,Jn as ContextState,$d as ConversationFinishedEvent,Gn as CoreToolScheduler,tg as CredentialsClearRequiredError,mq as CronScheduler,Ie as DAEMON_TRACEPARENT_META_KEY,Je as DAEMON_TRACESTATE_META_KEY,eq as DEFAULT_AUTO_DREAM_MIN_HOURS,fq as DEFAULT_AUTO_DREAM_MIN_SESSIONS,Up as DEFAULT_BACKGROUND_AGENT_CONTINUATION_MESSAGE,ro as DEFAULT_BUILTIN_SUBAGENT_TYPE,Ga as DEFAULT_CONTEXT_FILENAME,ab as DEFAULT_ENCODING,Ta as DEFAULT_FILE_EXCLUDES,pk as DEFAULT_FILE_FILTERING_OPTIONS,$t as DEFAULT_LSP_COMMAND_CHECK_TIMEOUT_MS,_t as DEFAULT_LSP_DOCUMENT_OPEN_DELAY_MS,bu as DEFAULT_LSP_DOCUMENT_RETRY_DELAY_MS,cu as DEFAULT_LSP_MAX_RESTARTS,Yt as DEFAULT_LSP_REQUEST_TIMEOUT_MS,eu as DEFAULT_LSP_SOCKET_MAX_RETRY_DELAY_MS,du as DEFAULT_LSP_SOCKET_RETRY_DELAY_MS,Xt as DEFAULT_LSP_STARTUP_TIMEOUT_MS,Zt as DEFAULT_LSP_WARMUP_DELAY_MS,au as DEFAULT_LSP_WORKSPACE_SYMBOL_WARMUP_DELAY_MS,zf as DEFAULT_MATILDA_EMBEDDING_MODEL,yf as DEFAULT_MATILDA_FLASH_MODEL,xf as DEFAULT_MATILDA_MODEL,Np as DEFAULT_MAX_CONCURRENT_BACKGROUND_AGENTS,nt as DEFAULT_MAX_INLINE_MEDIA_BYTES,ok as DEFAULT_MEMORY_FILE_FILTERING_OPTIONS,wf as DEFAULT_OTLP_ENDPOINT,Cf as DEFAULT_OUTPUT_TOKEN_LIMIT,ct as DEFAULT_PR_ATTRIBUTION_MESSAGE,ei as DEFAULT_STOP_HOOK_BLOCK_CAP,vf as DEFAULT_TELEMETRY_TARGET,Bf as DEFAULT_TOKEN_LIMIT,ft as DEFAULT_TOOL_OUTPUT_BATCH_BUDGET,kh as DEFAULT_TOOL_RESULTS_TOTAL_CHARS_THRESHOLD,et as DEFAULT_TRUNCATE_TOOL_OUTPUT_LINES,dt as DEFAULT_TRUNCATE_TOOL_OUTPUT_THRESHOLD,gu as DIAGNOSTIC_SEVERITY_LABELS,to as DISPLAY_MODE,bq as DREAM_TASK_TYPE,ia as DeclarativeTool,Hh as DefaultHookOutput,Hd as DiscoveredMCPTool,nr as DiscoveredTool,Ef as ESCALATED_MAX_TOKENS,ca as EVENT_API_ERROR,da as EVENT_API_RESPONSE,ba as EVENT_TOOL_CALL,Wn as EXCLUDED_TOOLS_FOR_SUBAGENTS,Mr as EXTENSIONS_CONFIG_FILENAME,Lr as EXTENSIONS_DIRECTORY_NAME,Or as EXTENSION_SETTINGS_FILENAME,Xn as EXTERNAL_MESSAGE_PREFIX,aq as EXTRACT_TASK_TYPE,Kd as EndSessionEvent,ne as ExtensionDisableEvent,ee as ExtensionEnableEvent,be as ExtensionInstallEvent,us as ExtensionManager,ms as ExtensionSettingScope,de as ExtensionUninstallEvent,ts as ExtensionUpdateState,Ri as FILE_HISTORY_DIR,$n as FORK_SUBAGENT_TYPE,g as FatalAuthenticationError,m as FatalBudgetExceededError,n as FatalCancellationError,j as FatalConfigError,f as FatalError,h as FatalInputError,i as FatalSandboxError,l as FatalToolExecutionError,k as FatalTurnLimitedError,oo as FileDiscoveryService,cn as FileEncoding,Ua as FileExclusions,Ui as FileHistoryService,ob as FileOperation,Kr as FileReadCache,sn as FileSchema,Hu as FileSearchFactory,Sd as FlashFallbackEvent,o as ForbiddenError,$h as GOAL_HOOK_TIMEOUT_MS,_h as GOAL_HOOK_TIMEOUT_SECONDS,w as GOOGLE_ACCOUNTS_FILENAME,Sk as GeminiChat,lq as GeminiClient,$j as GeminiEventType,no as GitIgnoreParser,mo as GitWorktreeService,Bh as HOOKS_CONFIG_FIELDS,zh as HookEventName,Ah as HookPhase,zs as HookRegistry,Bs as HookSystem,Ch as HookType,yh as HooksConfigSource,An as IDEConnectionStatus,kn as IDE_DEFINITIONS,nn as IDE_MAX_OPEN_FILES,on as IDE_MAX_SELECTED_TEXT_LENGTH,pn as IDE_REQUEST_TIMEOUT_MS,Au as IDLE_SPECULATION,Lo as INBOXES_DIR,ru as INITIAL_FOLLOWUP_STATE,Nr as INSTALL_METADATA_FILENAME,vo as ITermBackend,Bn as IdeClient,_d as IdeConnectionEvent,Zd as IdeConnectionType,un as IdeContextNotificationSchema,tn as IdeContextSchema,qn as IdeContextStore,vn as IdeDiffAcceptedNotificationSchema,xn as IdeDiffClosedNotificationSchema,wn as IdeDiffRejectedNotificationSchema,Zs as Ignore,yo as InProcessBackend,pr as InputFormat,hr as InvalidMcpConfigError,gj as InvalidSessionListCursorError,Qk as InvalidStreamError,lt as JsonFormatter,qq as KeychainTokenStorage,na as Kind,ae as KittySequenceOverflowEvent,Ho as LEADER_NAME,Zi as LITE_READ_BUF_SIZE,Ia as LOCAL_CONTEXT_FILENAME,zt as Logger,Ud as LoopType,iu as LspConfigLoader,ju as LspConnectionFactory,ku as LspResponseNormalizer,lu as LspServerManager,Af as MAINLINE_CODER_MODEL,qa as MAIN_SOURCE,Lf as MATILDA_API_KEY_ENV_KEY,mn as MATILDA_CODE_COMPANION_EXTENSION_NAME,Rt as MATILDA_CODE_SIMPLE_ENV_VAR,Dg as MATILDA_CREDENTIAL_FILE_MODE,v as MATILDA_DIR,Sf as MATILDA_OAUTH_MODELS,uc as MATILDA_SESSION_ID_HASH_ATTR,tc as MATILDA_USER_ID_HASH_ATTR,Qp as MAX_CONCURRENT_BACKGROUND_AGENTS,Br as MAX_CONCURRENT_MONITORS,Gi as MAX_DIFF_SIZE_BYTES,Fi as MAX_FILES,Ii as MAX_FILES_FOR_DETAILS,Zh as MAX_GOAL_ITERATIONS,Hi as MAX_LINES_PER_FILE,Fr as MAX_NOTIFICATION_OUTPUT_TAIL_BYTES,Rp as MAX_RETAINED_TERMINAL_AGENTS,Cr as MAX_RETAINED_TERMINAL_MONITORS,Gr as MAX_RETAINED_TERMINAL_SHELLS,Ir as MAX_RETAINED_TERMINAL_WORKFLOWS,Qi as MAX_SNAPSHOTS,Go as MAX_TEAMMATES,im as MAX_TRANSCRIPT_MESSAGES,Eh as MAX_USER_PROMPT_EXPANSION_ADDITIONAL_CONTEXT_LENGTH,zq as MCPDiscoveryState,vq as MCPOAuthProvider,rq as MCPOAuthTokenStorage,ht as MCPServerConfig,yq as MCPServerStatus,jr as MCP_BUDGET_REARM_FRACTION,ir as MCP_BUDGET_WARN_FRACTION,wq as MCP_DEFAULT_TIMEOUT_MSEC,Pa as MEDIA_FILE_PATTERNS,Ja as MEMORY_SECTION_HEADER,Vu as MOCK_TOOL_GET_CONFIRMATION_DETAILS,Uu as MOCK_TOOL_GET_DEFAULT_PERMISSION,Rf as MODEL_GENERATION_CONFIG_FIELDS,oa as MUTATOR_KINDS,zg as MatildaOAuth2Client,Ag as MatildaOAuth2Event,ug as MatildaOAuthPollError,fr as McpBudgetWouldExceedError,Aq as McpClient,mr as McpClientManager,gr as McpServerSpawnFailedError,Bt as McpTransportPool,re as MemoryDreamEvent,qe as MemoryExtractEvent,gq as MemoryManager,qb as MemoryMetricType,se as MemoryRecallEvent,Ds as MessageBus,dl as MessageBusType,wt as MessageSenderType,Xu as MockModifiableTool,Wu as MockModifiableToolInvocation,Tu as MockTool,Uf as ModelRegistry,fe as ModelSlashCommandEvent,Vf as ModelsConfig,Er as MonitorRegistry,mu as NativeLspClient,nu as NativeLspService,Vd as NextSpeakerCheckEvent,Ph as NotificationType,uq as OAUTH_AUTH_URL_EVENT,tq as OAUTH_DISPLAY_MESSAGE_EVENT,sq as OAuthUtils,Bj as OPENROUTER_BASE_URL,Aj as OPENROUTER_ENV_KEY,Ff as OUTPUT_TOKEN_SAFETY_MARGIN,ye as OpenAILogger,yn as OpenDiffRequestSchema,qr as OutputFormat,xu as OverlayFs,z as PATH_ARG_KEYS,cr as POOLED_TRANSPORTS_DEFAULT,rj as PROVIDER_METADATA_NS,Ra as PYTHON_EXCLUDES,pb as PerformanceMetricType,yr as PermissionManager,Rh as PermissionMode,Oh as PermissionRequestHookOutput,Uh as PostCompactTrigger,Mh as PostToolBatchHookOutput,Kh as PostToolUseFailureHookOutput,Jh as PostToolUseHookOutput,Th as PreCompactTrigger,Ih as PreToolUseHookOutput,oe as PromptSuggestionEvent,Pj as ProviderInstallError,up as RECIPROCAL_CALLER,Ur as REDACTED_URL_CREDENTIAL,hf as REPORTED_ATTEMPT_PURPOSES,ff as REPORTED_ATTEMPT_PURPOSE_HEADER,gf as REPORTED_OPERATION_HEADER_NAMES,ef as REPORTED_OPERATION_ID_HEADER,Pf as RUNTIME_SNAPSHOT_PREFIX,Vi as RUNTIME_STATUS_SCHEMA_VERSION,Gd as ReadFileTool,lf as ReportedOperationTracker,Ss as RipGrepTool,Td as RipgrepFallbackEvent,Be as RuntimeDiagnosticsCollector,vm as SAFE_TOOL_ALLOWLIST,fj as SESSION_TITLE_MAX_LENGTH,y as SHELL_SPECIAL_CHARS,Ll as SHELL_TOOL_NAMES,cq as SKILL_REVIEW_TASK_TYPE,fi as STOP_HOOK_BLOCK_CAP_ENV,Xj as STREAM_RECOVERY_PARTIAL_DISPOSITION,Wj as STREAM_RECOVERY_SNAPSHOT_DISPOSITION,tu as SUGGESTION_PROMPT,kg as SUPPORTED_IMAGE_MIME_TYPES,fu as SYMBOL_KIND_LABELS,Sa as SYSTEM_FILE_EXCLUDES,uk as SYSTEM_REMINDER_CLOSE,tk as SYSTEM_REMINDER_OPEN,fa as SchemaValidator,pq as SdkControlClientTransport,Tb as SemanticAttributes,iq as SendMessageType,Sh as SessionEndReason,hj as SessionService,Qh as SessionStartSource,ss as SettingScope,bn as ShellExecutionService,wr as SkillActivationRegistry,tr as SkillError,he as SkillLaunchEvent,xr as SkillManager,Xd as SlashCommandStatus,lk as SleepInhibitor,Q as SpanStatusCode,pe as SpeculationEvent,jn as StandardFileSystemService,Jd as StartSessionEvent,Nh as StopHookOutput,N as Storage,Mk as StreamEventType,Zn as SubagentError,_n as SubagentErrorCode,Ar as SubagentManager,zr as SubagentValidator,Jo as TASKS_DIR,Mo as TEAMMATE_COLORS,Io as TEAMS_DIR,Ko as TEAM_CONFIG_FILENAME,ri as TERMINAL_CSI_REGEX,qi as TERMINAL_OSC_REGEX,si as TERMINAL_SHIFT_DCS_REGEX,Lj as THIRD_PARTY_PROVIDERS,Vj as THOUGHT_ONLY_MAX_TOKENS_DISPOSITION,Kl as TOOL_NAME_ALIASES,Ft as TOOL_USE_SUMMARY_SYSTEM_PROMPT,cl as TaskCompletionScope,Bp as TaskOwnershipError,Oo as TeamEventEmitter,No as TeamEventType,Mp as TeamManager,uf as TelemetryTarget,jg as TextTokenizer,uo as TmuxBackend,Nd as ToolCallEvent,ma as ToolConfirmationOutcome,Da as ToolDisplayNames,Fa as ToolDisplayNamesMigration,ea as ToolErrorType,rb as ToolExecutionPhase,Ca as ToolNames,Ea as ToolNamesMigration,ce as ToolOutputTruncatedEvent,or as ToolRegistry,at as TrustGateError,bk as Turn,od as USER_AUTO_MEMORY_DIRNAME,ra as UiTelemetryService,p as UnauthorizedError,je as UserFeedbackEvent,ie as UserFeedbackRating,Ld as UserPromptEvent,Lh as UserPromptExpansionHookOutput,Md as UserRetryEvent,P as ValueType,ho as WORKTREES_DIR,ao as WORKTREE_BRANCH_PREFIX,co as WORKTREE_SESSION_FILE,Jr as WorkflowRunRegistry,po as WorkspaceContext,Ct as WorkspaceMcpBudget,Vt as WorkspaceMemoryFileTooLargeError,Tt as WorkspaceMemoryWriteTimeoutError,sh as __resetActiveGoalStoreForTests,ui as _recoverObjectsFromLine,Cn as _resetCachedIdeServerHost,zi as _resetEnsuredDirsCacheForTest,Rs as _resetRipGrepCachesForTest,x as _resetValidatePathCacheForTest,ai as abortGoalForStopHookCap,Du as abortSpeculation,Cu as acceptSpeculation,nk as acquireSleepInhibitor,lh as activeGoalEquals,Pe as addDaemonRequestAttribute,Cq as addMCPStatusChangeListener,Zb as addModelOutputAttributes,Xb as addSystemPromptAttributes,_b as addToolInputAttributes,$b as addToolResultAttributes,Yb as addToolSchemaAttributes,Wb as addUserPromptAttributes,Qt as aggregateUsage,Mm as allowEditorTypeInSandbox,$g as appendToLastTextPart,Am as applyAutoModeDecision,Qj as applyProviderInstallPlan,sk as applySkillAllowedTools,pt as approxBase64Bytes,vp as assertValidTaskId,ap as assignTeammateColor,Z as atomicWriteFile,aa as atomicWriteFileSync,_ as atomicWriteJSON,Gp as blockTask,zk as buildAddedMcpToolsReminder,Ck as buildAddedSkillsReminder,ij as buildApiHistoryFromConversation,Bk as buildAvailableSkillsReminder,Sp as buildBackgroundEntryLabel,Ru as buildBtwCacheSafeParams,Qu as buildBtwPrompt,yk as buildDeferredToolsReminder,Do as buildFallbackApproachSummary,Tl as buildHumanReadableRuleLabel,sj as buildInstallPlan,Ak as buildMcpServerInstructionsReminder,nq as buildMissedCronNotification,Mg as buildModelIdContext,$l as buildPermissionCheckContext,Sl as buildPermissionRules,zj as buildProviderTemplate,rf as buildReportedOperationHeaders,Al as buildShellExecWarnings,rk as buildSkillLlmContent,Dk as buildStartupContextReminder,Lp as buildTeammatePromptAddendum,Eg as cacheMatildaCredentials,ar as canUseRipgrep,Se as captureDaemonTelemetryContext,Hl as checkArgumentSafety,Bl as checkCommandPermissions,bs as checkForExtensionUpdate,Lm as checkHasEditorType,_r as checkNpmUpdate,Hp as claimTask,rt as clampInlineMediaPart,Gf as clampOutputToContextWindow,fp as classifyShutdownResponse,It as cleanSummary,Zu as cleanupTmpDir,oh as clearActiveGoal,sp as clearAllInboxes,rd as clearAutoMemoryRootCache,Yp as clearCacheSafeParams,Fg as clearCachedCredentialFile,uh as clearGoalTerminalObserver,rp as clearInbox,xc as clearMatildaCorrelationHashes,$f as clearMatildaCredentials,Yi as clearRuntimeStatus,bp as clearTeammateColors,Lu as clearWelcomeBackState,Vs as clearWorktreeSession,Js as cliSource,$r as cloneFromGit,oq as collectMemoryDiagnostics,Ik as collectToolCallIdsFromHistory,Gm as commandExists,Ok as compactPendingUserContentToBudget,Nk as compactTextMiddle,tj as computeModelListVersion,kk as computeThresholds,mj as computeUniqueBranchTitle,Ns as computedSource,Nq as connectAndDiscover,Tq as connectToMcpServer,dr as connectionIdOf,qp as consumeUnread,hs as convertClaudeAgentConfig,js as convertClaudePluginPackage,is as convertClaudeToMatildaConfig,Ym as convertColorToHex,Fn as convertToFunctionResponse,fs as convertTomlToMarkdown,vs as copyExtension,fb as countFileLines,Di as countLines,Xs as crawlCache,Kg as createContentGenerator,Jg as createContentGeneratorConfig,We as createDaemonBridgeTelemetry,X as createDebugLogger,Yk as createDefaultAutoMemoryExtractCursor,Zk as createDefaultAutoMemoryIndex,Xk as createDefaultAutoMemoryMetadata,lm as createDenialState,su as createFollowupController,Zp as createForkedChat,bi as createGoalStopHookCallback,Gh as createHookOutput,Cs as createInstructionsLoadedCallback,xq as createStreamableHttpCompatibilityFetch,zp as createTask,ip as createTeamFile,Yu as createTmpDir,Et as createToolUseSummaryMessage,Uq as createTransport,Jj as customProvider,cb as decodeBufferWithEncodingInfo,yt as decodeTagName,Kk as dedupeToolCallsById,Dj as deepseekProvider,Ms as defaultSource,Dp as deleteTask,kp as deleteTeamDirs,Ti as deserializeSnapshots,bb as detectBOM,zo as detectBackend,xl as detectCommandSubstitution,$a as detectEncodingFromBuffer,hb as detectFileEncoding,lb as detectFileType,ln as detectIdeFromEnv,gn as detectLineEnding,gg as detectRuntime,Wh as detectTodoChanges,Lq as discoverMcpTools,Qq as discoverPrompts,Oq as discoverTools,mp as disposeInboxLocks,ll as doesToolInvocationMatch,cs as downloadFromGitHubRelease,Zr as downloadFromNpmRegistry,Hm as editorCommands,Re as emitDaemonLog,ut as encodeInsightErrorMessage,st as encodeInsightProgressMessage,tt as encodeInsightReadyMessage,xt as encodeTagName,hn as encodeTextFileContent,oc as endHookSpan,cc as endInteractionSpan,fc as endLLMRequestSpan,rc as endSubagentSpan,mc as endToolBlockedOnUserSpan,kc as endToolExecutionSpan,ic as endToolSpan,_k as ensureAutoMemoryScaffold,fn as ensureCrlfLineEndings,$q as ensureMacBinarySigned,_q as ensureRipgrepHealthy,Eu as ensureToolResultPairing,yi as ensureTrailingNewlineSync,al as ensureUserAutoMemoryScaffold,nf as enterReportedOperationContext,Os as envLayer,E as escapePath,ol as escapeShellArg,te as estimateTokensFromChars,Em as evaluateAutoMode,dm as evaluatePermissionFlow,am as evaluatePermissionRules,yu as evaluateToolCall,Cl as execCommand,At as executeToolCall,Ei as exists,B as expandHomeDir,Ve as extractDaemonTraceContext,Va as extractExtensionsFromPatterns,es as extractFile,aj as extractJsonStringField,cj as extractLastJsonStringField,bj as extractLastJsonStringFields,jm as extractShellOperations,En as extractToolFilePaths,Ji as fetchGitDiff,Ki as fetchGitDiffHunks,nb as fileExists,Gu as filter,li as findGitRoot,dp as findMemberById,ep as findMemberByName,Nj as findProviderByCredentials,Mj as findProviderById,ds as findReleaseAsset,il as fireNotificationHook,jl as firePermissionRequestHook,hl as firePostToolUseFailureHook,gl as firePostToolUseHook,fl as firePreToolUseHook,_g as flatMapTextParts,Cc as forceFlushMetrics,_o as formatAgentId,Dm as formatClassifierBlockMessage,vk as formatDateForContext,mm as formatDenialStateLog,Eo as formatLineStats,Zm as formatMemoryUsage,ii as formatStopHookBlockingCapWarning,S as formatTraceparent,So as forwardApproval,lo as generateAgentWorktreeSlug,rg as generateCodeChallenge,qg as generateCodeVerifier,Ij as generateCustomEnvKey,sg as generatePKCEPair,uu as generatePromptSuggestion,Dt as generateSessionRecap,el as generateToolUseId,Gt as generateToolUseSummary,$o as generateUniqueTeammateName,Id as generateValidName,ue as generatedOutputTokens,mh as getActiveGoal,sc as getActiveInteractionSpan,Pn as getAgentName,Kp as getAgentStatuses,Ma as getAllGeminiMdFilenames,Hq as getAllMCPServerStatuses,Oj as getAllProviderBaseUrls,ik as getArenaSystemReminder,xd as getAutoMemoryConsolidationLockPath,wd as getAutoMemoryExtractCursorPath,Ad as getAutoMemoryFilePath,ud as getAutoMemoryIndexPath,vd as getAutoMemoryMetadataPath,sd as getAutoMemoryProjectStateDir,qd as getAutoMemoryRoot,yd as getAutoMemoryTopicFilename,zd as getAutoMemoryTopicPath,Cm as getAutoModePermissionDeniedReason,Yq as getBuiltinRipgrep,Xp as getCacheSafeParams,Ya as getCachedEncodingForBuffer,ql as getCommandRoot,rl as getCommandRoots,fk as getCompressionPrompt,ek as getCoreSystemPrompt,La as getCurrentGeminiMdFilename,dk as getCustomSystemPrompt,uj as getDefaultBaseUrlForProtocol,wj as getDefaultModelIds,Om as getDiffCommand,wk as getDirectoryContextString,Im as getEditorExecutable,fm as getEffectivePermissionForConfirmation,qs as getEnvContents,xk as getEnvironmentContext,c as getErrorMessage,d as getErrorStatus,e as getErrorType,ws as getExtensionId,Km as getExternalEditorCommand,vu as getFilterReason,qk as getFolderStructure,ch as getFunctionCalls,eh as getFunctionCallsAsJson,dh as getFunctionCallsFromParts,fh as getFunctionCallsFromPartsAsJson,mi as getGitBranch,ni as getGitRepoName,Dh as getHookKey,Wt as getIdeInstaller,Dn as getIdeServerHost,np as getInboxPath,Xo as getInboxesDir,Ek as getInitialChatHistory,jk as getInsightPrompt,wh as getLastGoalTerminal,Qo as getLeader,Iq as getMCPDiscoveryState,qu as getMCPServerPrompts,Gq as getMCPServerStatus,Nf as getMatildaAuthBaseUrl,ag as getMatildaAuthStatus,wc as getMatildaCorrelationHashes,Yf as getMatildaCredentialsPath,Cg as getMatildaOAuthClient,ot as getMaxInlineMediaBytes,pd as getMemoryBaseDir,Dr as getMonitorOutputPath,hg as getOrCreateSharedDispatcher,hk as getPlanModeSystemReminder,G as getProjectHash,Mu as getProjectSummaryInfo,gk as getProjectSummaryPrompt,Tg as getRateLimitErrorDetails,Ug as getRateLimitRetryDelayMs,oi as getRecentGitStatus,kf as getReportedOperationContext,Zg as getResponseText,bh as getResponseTextFromParts,kj as getResumePromptTokenCount,lj as getResumeTokenCounts,Rl as getRuleDisplayName,ps as getScopedEnvContents,an as getShellAbortReasonKind,ml as getShellConfiguration,ib as getSpecificMimeType,Nl as getSpecifierKind,Fk as getStartupContextLength,gh as getStructuredResponse,hh as getStructuredResponseFromParts,mg as getSupportedImageFormatsString,Za as getSystemEncoding,Ap as getTask,wp as getTaskPath,Yo as getTasksDir,Vo as getTeamDir,Wo as getTeamFilePath,Qn as getTeamName,Un as getTeammateColor,Nn as getTeammateContext,Uo as getTeamsRootDir,_j as getThoughtText,Pt as getTimeRangeBounds,R as getTraceContext,ng as getUnsupportedImageFormatWarning,Cd as getUserAutoMemoryIndexPath,Bd as getUserAutoMemoryRoot,Dd as getUserAutoMemoryTopicPath,cg as getValidMatildaAccessToken,Ju as getWelcomeBackState,hq as globalMemoryManager,Kq as handleAutomaticOAuth,la as hasCycleInSchema,If as hasExplicitOutputLimit,Sq as hasNetworkTransport,ul as hasNonFinalTopLevelBackgroundOperator,zl as hasShellSubstitution,wl as hasUnsafeMonitorBackgroundOperator,Ke as hashDaemonWorkspace,ou as hashMcpServerConfig,xs as hashValue,As as hookEventSupportsMatcher,Qr as hydrateString,rn as ideContextStore,Xe as initializeDaemonMetrics,zc as initializeTelemetry,Ue as injectDaemonTraceContext,bm as injectPermissionRulesIfMissing,Rq as invokeMcpPrompt,b as isAbortError,s as isAccountInactiveError,Fd as isAnyAutoMemPath,Ng as isApiError,tm as isApproveOutcome,hm as isAutoEditApproved,td as isAutoMemPath,St as isBareMode,Tm as isBinary,kb as isBinaryFile,Wf as isBrowserCommandBlocked,ls as isClaudePluginConfig,Fl as isCommandAllowed,El as isCommandAvailable,Gl as isCommandNeedsPermission,T as isDebugLoggingDegraded,nm as isDenialFallbackReason,vg as isDeviceAuthorizationSuccess,xg as isDeviceTokenPending,wg as isDeviceTokenSuccess,Nm as isEditorAvailable,Vq as isEnabled,yg as isErrorResponse,gt as isGatedMcpScope,Qg as isGenericQuotaExceededError,ki as isGitRepository,On as isInProcessTeammate,wm as isInSafeToolAllowlist,Uk as isInvalidArgumentError,Rg as isMatildaQuotaExceededError,Qm as isModifiableDeclarativeTool,a as isNodeError,qo as isPathWithinRoot,Mb as isPerformanceMonitoringActive,gm as isPlanModeBlocked,Pg as isProQuotaExceededError,Sg as isRateLimitError,jf as isReportedOperationHeaderName,Ae as isRuntimeDiagnosticsEnabled,Tk as isSchemaDepthError,Xr as isScopedNpmPackage,it as isSdkMcpServerConfig,Aa as isSettledStatus,Og as isStructuredError,I as isSubpath,J as isSubpaths,za as isSuccessStatus,lg as isSupportedImageMimeType,Gk as isSystemReminderContent,Tn as isTeamLead,Sn as isTeammate,yc as isTelemetrySdkInitialized,Jm as isTerminalEditor,ya as isTerminalStatus,gs as isTomlFormat,ka as isTool,kl as isToolEnabled,Vg as isTransientCapacityError,Wg as isUnattendedMode,Uj as isUserAuthoredPromptRecord,Ed as isUserAutoMemPath,Fm as isValidEditorType,Pk as isValidNonThoughtTextPart,nl as isWindows,jb as isWithinRoot,Xh as judgeGoal,Jf as knownTokenLimit,Ps as layer,Pq as listMcpPrompts,Ep as listTasks,lp as listTeamNames,Ys as loadIgnoreRules,Gs as loadServerHierarchicalMemory,Ot as loadUsageHistory,Mc as logApiCancel,Lc as logApiError,Ic as logApiRequest,Nc as logApiResponse,cd as logArenaAgentCompleted,dd as logArenaSessionEnded,bd as logArenaSessionStarted,_c as logAuth,Sc as logChatCompression,Rc as logConversationFinishedEvent,Zc as logExtensionDisable,Yc as logExtensionEnable,Vc as logExtensionInstallEvent,Wc as logExtensionUninstall,Xc as logExtensionUpdateEvent,Jc as logFlashFallback,Qc as logIdeConnection,Tc as logKittySequenceOverflow,hd as logMemoryDream,gd as logMemoryExtract,id as logMemoryRecall,Uc as logModelSlashCommand,Oc as logNextSpeakerCheck,ed as logPromptSuggestion,Kc as logRipgrepFallback,$c as logSkillLaunch,Pc as logSlashCommand,fd as logSpeculation,Dc as logStartSession,Gc as logToolCall,Hc as logToolOutputTruncated,ad as logUserFeedback,Ec as logUserPrompt,Fc as logUserRetry,Of as loginToMatilda,fg as loginToMatildaWithBrowser,bg as logoutMatilda,le as makeArenaAgentCompletedEvent,me as makeArenaSessionEndedEvent,ke as makeArenaSessionStartedEvent,Yd as makeChatCompressionEvent,Su as makeFakeConfig,D as makeRelative,Wd as makeSlashCommandEvent,Vl as matchesCommandPattern,Yl as matchesDomainPattern,Zl as matchesMcpPattern,Xl as matchesPathPattern,_l as matchesRule,Bg as matildaOAuth2Events,Mf as matildaProvider,ns as maybePromptForSettings,Bq as mcpServerRequiresOAuth,lr as mcpTransportOf,ks as mergeClaudeConfigs,Kt as metricsToUsageRecord,Ej as minimaxProvider,Ls as modelProvidersSource,Tf as modelRegistryKey,Gj as modelscopeProvider,Rm as modifyWithEditor,em as needsConfirmation,dn as needsUtf8Bom,Hf as normalize,Um as normalizeContent,Jk as normalizeModelToolCallIds,vl as normalizeMonitorCommand,Es as normalizeProxyUrl,ur as normalizeSkillPriority,gi as normalizeStopHookBlockingCap,we as normalizeStoredModelUsage,Lt as normalizeUsageRecord,vh as notifyGoalTerminal,yp as notifyTasksUpdated,xp as onTasksUpdated,og as openBrowserSecurely,Pm as openDiff,Cj as openRouterProvider,ze as openaiLogger,qt as oversizedMediaPlaceholder,rr as parse,ji as parseAndFormatApiError,Fe as parseBooleanEnvFlag,er as parseConnectionId,Oi as parseDeletedFromNameStatus,Mi as parseGitDiff,as as parseGitHubRepoForReleases,Li as parseGitNumstat,vt as parseInsightMessage,pu as parseInstallSource,vi as parseLineTolerant,Wr as parseNpmPackageSource,Pl as parseRule,Ql as parseRules,Ni as parseShortstat,Ge as parseTelemetryTargetValue,Zj as parseThought,mt as partListUnionToString,Yg as partToString,zm as passesAcceptEditsFastPath,Tr as performVariableReplacement,cm as persistPermissionOutcome,Jt as persistSessionUsage,Mq as populateMcpServerCommand,ah as prependToFirstTextPart,mb as processSingleFileContent,os as promptForSetting,_m as promptIdContext,yj as providerMatchesCredentials,xi as read,$k as readAutoMemoryIndex,eb as readFileWithEncoding,db as readFileWithEncodingInfo,gb as readFileWithLineAndLimit,op as readInbox,_i as readLastConversationTimestampSync,dj as readLastJsonStringFieldSync,ej as readLastJsonStringFieldsSync,wi as readLines,Nu as readManyFiles,Zf as readMatildaCredentials,Iu as readPathFromWorkspace,Xi as readRuntimeStatus,gp as readTeamFile,bl as readUserAutoMemoryIndex,Ts as readWorktreeSession,fo as readWorktreeSessionMarker,om as recordAllow,wb as recordApiErrorMetrics,Ib as recordApiRequestBreakdown,vb as recordApiResponseMetrics,Bb as recordApiRetry,Ob as recordArenaAgentCompletedMetrics,Pb as recordArenaSessionEndedMetrics,Nb as recordArenaSessionStartedMetrics,Lb as recordBaselineComparison,pm as recordBlock,zb as recordContentRetry,Ab as recordContentRetryFailure,Eb as recordCpuUsage,cf as recordDaemonBridgeError,df as recordDaemonCancel,$e as recordDaemonChannelLifecycle,Qe as recordDaemonError,Ze as recordDaemonHttpRequest,Oe as recordDaemonHttpResponse,bf as recordDaemonPromptDuration,af as recordDaemonPromptQueueWait,_e as recordDaemonSessionLifecycle,sm as recordFallbackApprove,xb as recordFileOperationMetric,ph as recordGoalIteration,yb as recordInvalidChunk,Rb as recordMemoryDreamMetrics,Qb as recordMemoryExtractMetrics,Sb as recordMemoryRecallMetrics,Db as recordMemoryUsage,Kb as recordPerformanceRegression,Jb as recordPerformanceScore,jh as recordStartupEvent,Cb as recordStartupPerformance,Hb as recordTokenEfficiency,ub as recordTokenUsageMetrics,tb as recordToolCallMetrics,Gb as recordToolExecutionBreakdown,Fb as recordToolQueueDepth,qm as recordUnavailable,Rr as recursivelyHydrateStrings,ig as redactProxyCredentials,Lk as redactStructuredOutputArgsForRecording,Vr as redactUrlCredentials,Mt as reestimateUsageFromAssistantRecord,dg as refreshMatildaCredentials,Ac as refreshSessionContext,Ye as registerDaemonGaugeCallbacks,di as registerGoalHook,Po as registerLeader,Ip as releaseOwnedTask,Fq as removeMCPServerStatus,Dq as removeMCPStatusChangeListener,Y as renameWithRetry,$ as renameWithRetrySync,Rk as repairOrphanedToolUseTurns,jj as replayUiTelemetryFromConversation,tf as reportCliAuthFunnelEvent,sf as reportCliClientEvent,jq as reportedAttemptPurposeForSendMessageType,U as resetDebugLoggingState,um as resetDenialState,Xa as resetEncodingCache,Fp as resetTaskList,en as resetUtf8BomCache,Rn as resolveActiveTeamName,M as resolveAndValidatePath,vj as resolveBaseUrl,Xq as resolveBundleDir,Dl as resolveCommandPath,Hg as resolveContentGeneratorConfigWithSources,Hs as resolveField,Pi as resolveGitDir,rh as resolveGoalLifecycleStatus,Rj as resolveLocalHistoryAccountScopeId,Sj as resolveLocalHistoryAccountScopeIdForCredentials,Pp as resolveMaxConcurrentBackgroundAgents,qj as resolveMetadataKey,Qs as resolveModelConfig,Lg as resolveModelId,Yr as resolveNpmRegistry,xe as resolveOpenAILogDir,Is as resolveOptionalField,pj as resolveOwnsModel,K as resolvePath,ck as resolvePathFromEnv,Wl as resolvePathPattern,Zq as resolveRipgrep,hi as resolveStopHookBlockingCap,He as resolveTelemetrySettings,Ml as resolveToolName,Ws as restoreWorktreeContext,Xg as retryWithBackoff,zu as rewritePathArgs,Nt as rewriteUsageHistoryFromChats,pf as runAsyncGeneratorWithReportedOperationContext,$p as runForkedAgent,qc as runInSubagentSpanContext,hc as runInToolSpanContext,br as runRipgrep,pi as runSideQuery,Te as runWithDaemonTelemetryContext,W as runWithDebugLogSession,_p as runWithForkedChatModel,of as runWithReportedAttemptPurpose,mf as runWithReportedOperationContext,Vn as runWithTeammateIdentity,Ce as runtimeDiagnostics,va as safeAgentId,Sm as safeLiteralReplace,H as sanitizeCwd,Ub as sanitizeHookName,Zo as sanitizeName,oj as sanitizeTitle,Tj as sanitizeToolCallResultForRecording,Fh as sanitizeUserPromptExpansionAdditionalContext,Wp as saveCacheSafeParams,Ku as saveWelcomeBackRestartChoice,tp as sendStructuredMessage,Si as serializeSnapshot,Xm as serializeTerminalToObject,Vm as serializeTerminalToText,$m as sessionIdContext,nh as setActiveGoal,V as setDebugLogSession,Ka as setGeminiMdFilename,th as setGoalTerminalObserver,xh as setLastGoalTerminal,Jq as setMCPDiscoveryState,vc as setMatildaCorrelationHashes,cp as setMemberActive,ih as setStartupEventSink,Ks as settingsSource,C as shortenPath,Xf as shouldAttemptBrowserLaunch,Il as shouldDefaultToNodePty,rm as shouldFallback,wu as shouldFilterSuggestion,Bm as shouldFirePermissionDeniedForAutoMode,ym as shouldForceAutoModeReviewForAllow,pg as shouldLaunchBrowser,xm as shouldRunAutoModeForCall,xj as shouldShowStep,Bc as shutdownTelemetry,mk as sleepInhibitor,pl as splitCommands,Ul as splitCompoundCommand,vr as splitConditionalSkills,nc as startHookSpan,bc as startInteractionSpan,ec as startLLMRequestSpan,Bu as startSpeculation,pc as startSubagentSpan,lc as startToolBlockedOnUserSpan,jc as startToolExecutionSpan,gc as startToolSpan,kq as startsReportedOperation,sr as stringify,Qf as stripRuntimeSnapshotPrefix,sl as stripShellWrapper,Hk as stripStartupContext,ti as stripTerminalControlSequences,tl as stripTrailingBackgroundAmp,Ou as subagentGenerator,Sr as substituteHookVariables,Ee as summarizeAnthropicWireRequest,De as summarizeOpenAIWireRequest,Co as summarizeUnifiedDiff,Mn as teammateIdentityStore,Kn as templateString,A as tildeifyPath,u as toFriendlyError,Jl as toPosixPath,Kf as tokenLimit,Ol as toolMatchesRuleToolName,ve as totalTokensFromBuckets,Vb as truncateContent,Ht as truncateJson,ac as truncateSpanError,nj as tryGenerateSessionTitle,jp as tryReclaimStaleTeam,sa as uiTelemetryService,Jp as unassignTeammateTasks,$i as unescapeJsonString,F as unescapePath,ci as unregisterGoalHook,Ro as unregisterLeader,qh as updateActiveGoalStatus,Yh as updateGoalStatus,Eq as updateMCPServerStatus,rs as updateSetting,O as updateSymlink,Cp as updateTask,Ig as validateModelConfig,ys as validateName,L as validatePath,Pr as validateVariables,eg as willOpenMatildaAuthBrowser,_a as windowsCodePageToEncoding,Ne as withDaemonBridgeSpan,Me as withDaemonRequestSpan,Le as withDaemonSpan,dc as withInteractionSpan,qf as withReportedAttemptPurpose,bo as worktreeBranchForSlug,To as wrapConfirmWithBadge,Ci as write,Ai as writeLine,Bi as writeLineSync,_f as writeMatildaCredentials,pp as writeMessage,Wi as writeRuntimeStatus,hp as writeTeamFile,Ut as writeWorkspaceContextFile,Us as writeWorktreeSession,eo as writeWorktreeSessionMarker,Fj as zaiProvider};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Force strict mode and setup for ESM
|
|
2
2
|
"use strict";
|
|
3
|
-
import{
|
|
3
|
+
import{Ig as D,xg as u}from"./chunk-4TV7Y2I2.js";import"./chunk-TZIDSCTF.js";import{l as A}from"./chunk-ROETRE5J.js";import{l as C}from"./chunk-INAZKGGR.js";import{d as w,g as T,h as k,i as b,s as o,t as v}from"./chunk-DCQKJTAX.js";import"./chunk-LSDMWVW6.js";import"./chunk-MTMU7JYZ.js";import"./chunk-TXMXCR7D.js";import"./chunk-YULUB745.js";import"./chunk-VYTYYCBR.js";import"./chunk-TISQNFB5.js";import"./chunk-34DXSYJZ.js";import"./chunk-47XR7IMP.js";import"./chunk-FWIVFCKF.js";import{k as f,l as y}from"./chunk-QKYGQLWC.js";import"./chunk-FRL6KOLY.js";import"./chunk-VWWEEU4V.js";import"./chunk-RNKDFE2S.js";import"./chunk-Q2I3ARPJ.js";import"./chunk-CRGV5RTO.js";import"./chunk-QHA3ZBRO.js";import"./chunk-ZYUCUBVQ.js";import"./chunk-4F4DA5UI.js";import"./chunk-DC7LAFZZ.js";import"./chunk-S7G6QPEP.js";import"./chunk-4J6DC24J.js";import"./chunk-LJR4RZZ2.js";import"./chunk-U347OO7S.js";import"./chunk-SDTWBD62.js";import"./chunk-B3NVKOSU.js";import"./chunk-WVY2P6WH.js";import"./chunk-UIRBHC5X.js";import"./chunk-32PTAACU.js";import"./chunk-32T6RWWT.js";import{g as c,i as g,p as h,q as p}from"./chunk-6B5BDE7S.js";import"./chunk-RJX7DK4Y.js";import"./chunk-XCJYORZX.js";import"./chunk-ESSYHTAZ.js";import"./chunk-3YLXGE6T.js";import"./chunk-EQEQPZLQ.js";import{b as d}from"./chunk-VLYRNOD3.js";import"./chunk-G7R2XEEF.js";import"./chunk-OA56BXPD.js";import"./chunk-FWDMPRKU.js";import{b as l}from"./chunk-GZPNIYVZ.js";import"./chunk-OWGSC52X.js";l();var i=class extends c{constructor(e,a){super(a);this.config=e}getDescription(){return`Create team "${this.params.team_name}"`}async execute(){let e=k(this.params.team_name);if(!e){let t="Team name is required.";return{llmContent:t,returnDisplay:t,error:{message:t}}}if(this.config.getArenaManager()){let t="Cannot create a team while an Arena session is active. End the Arena session first.";return{llmContent:t,returnDisplay:t,error:{message:t}}}if(this.config.getTeamManager()){let t="A team is already active. Delete it before creating a new one.";return{llmContent:t,returnDisplay:t,error:{message:t}}}let a=b(y,e),s={name:e,description:this.params.description,createdAt:Date.now(),leadAgentId:a,leadSessionId:this.config.getSessionId(),leadPid:process.pid,members:[]};try{await o(e,s)}catch(t){if(d(t)&&t.code==="EEXIST"){if(!await v(e)){let n=`Team "${e}" already exists and appears to be owned by a live matilda-code session. Pick a different name, or \u2014 if you're sure no other session is using it \u2014 remove the on-disk artifacts manually:
|
|
4
4
|
rm -rf "${w(e)}" "${T(e)}"`;return{llmContent:n,returnDisplay:n,error:{message:n}}}await o(e,s)}else throw t}await C(e),await A(e);let m=new u(this.config);await m.init();let x=new D(m,s,this.config.getSubagentManager(),{maxTeammates:this.config.getAgentsSettings().team?.maxTeammates});this.config.setTeamManager(x);let N={teamName:e,leadAgentId:a,teammates:{}};this.config.setTeamContext(N);let E={type:"team_result",teamName:e,action:"created"};return{llmContent:`Team "${e}" created.`+(this.params.description?` Description: ${this.params.description}`:""),returnDisplay:E}}},I=class r extends g{constructor(e){super(r.Name,p.TEAM_CREATE,`# TeamCreate
|
|
5
5
|
|
|
6
6
|
## When to Use
|