@maincode-ai/matilda-code 0.21.8 → 0.21.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/bundled/mainy/docs/configuration/settings.md +9 -5
  2. package/bundled/mainy/docs/reference/keyboard-shortcuts.md +3 -2
  3. package/chunks/{agent-IL7T4I2K.js → agent-HFMBAASZ.js} +1 -1
  4. package/chunks/{agent-headless-PR64PSXJ.js → agent-headless-Y4QZBATF.js} +1 -1
  5. package/chunks/ca-H4HPSGTI.js +25 -0
  6. package/chunks/{chunk-WOH6NLJH.js → chunk-6JHTLNKH.js} +1 -1
  7. package/chunks/{chunk-W6CQYQAL.js → chunk-6K4TWA3V.js} +1 -1
  8. package/chunks/{chunk-FV4IIIXN.js → chunk-NMPCACBI.js} +2 -2
  9. package/chunks/{chunk-YQNGLSJG.js → chunk-NP3QU6KY.js} +2 -2
  10. package/chunks/{chunk-QBBPRMPV.js → chunk-O54UZAY3.js} +1 -1
  11. package/chunks/{chunk-6GY6EBMC.js → chunk-PBCPYRSP.js} +3 -3
  12. package/chunks/{chunk-6D5M34RS.js → chunk-T4JNNZRX.js} +1 -1
  13. package/chunks/{computer-use-LL6VH2YY.js → computer-use-D32TORJM.js} +1 -1
  14. package/chunks/{contextCommand-NYUQREN7.js → contextCommand-HRWTOB5R.js} +1 -1
  15. package/chunks/de-S7F37S4F.js +25 -0
  16. package/chunks/{edit-EZH4FRBA.js → edit-CVFKTJ7G.js} +1 -1
  17. package/chunks/en-S6DMCJQZ.js +25 -0
  18. package/chunks/{enter-worktree-2NFK4Q5V.js → enter-worktree-LJBEPBPI.js} +1 -1
  19. package/chunks/{enterPlanMode-3RRWLKZY.js → enterPlanMode-LMRR4777.js} +1 -1
  20. package/chunks/{exit-worktree-ROPZ6KRN.js → exit-worktree-V7KTGJSX.js} +1 -1
  21. package/chunks/{exitPlanMode-XIZ2N2BH.js → exitPlanMode-KQINMKFC.js} +4 -4
  22. package/chunks/fr-RFJP3KVL.js +25 -0
  23. package/chunks/{geminiContentGenerator-Y5BT63HW.js → geminiContentGenerator-JGFPDSGE.js} +1 -1
  24. package/chunks/{glob-ZZX5YQEW.js → glob-FZNZJN65.js} +1 -1
  25. package/chunks/{grep-RITQSEH3.js → grep-GZETX354.js} +1 -1
  26. package/chunks/ja-UTJHPL3M.js +25 -0
  27. package/chunks/{matildaAgentContentGenerator-UATDDKKZ.js → matildaAgentContentGenerator-KCBISL4Z.js} +1 -1
  28. package/chunks/{matildaContentGenerator-4EWO3QKC.js → matildaContentGenerator-I7DLSOGS.js} +1 -1
  29. package/chunks/{monitor-DNWGCVNF.js → monitor-MI2Y2MO2.js} +1 -1
  30. package/chunks/{notebook-edit-FNCOZCKQ.js → notebook-edit-WK6NUSID.js} +1 -1
  31. package/chunks/{openaiContentGenerator-FEVSJC7Q.js → openaiContentGenerator-WXDEJSZE.js} +1 -1
  32. package/chunks/pt-KXMOTADP.js +25 -0
  33. package/chunks/{ripGrep-6EYEXCRW.js → ripGrep-R55EA2GB.js} +1 -1
  34. package/chunks/ru-EWGWZPQH.js +25 -0
  35. package/chunks/{scheduler-WIJWPRZD.js → scheduler-73CAQCIX.js} +1 -1
  36. package/chunks/{serve-UUEBKOVV.js → serve-GNXK43FQ.js} +1 -1
  37. package/chunks/{shell-CTE2Z3PU.js → shell-XGVUYVXY.js} +1 -1
  38. package/chunks/{skill-ZEEJW7MU.js → skill-DQMUM4ZC.js} +1 -1
  39. package/chunks/{src-CPPHVZMK.js → src-TBCCCTMT.js} +1 -1
  40. package/chunks/{team-create-XO32YS6Q.js → team-create-C6VPLV6L.js} +1 -1
  41. package/chunks/{workflow-UFWS3C22.js → workflow-JEXF4MOH.js} +2 -2
  42. package/chunks/{write-file-4K5POBXD.js → write-file-UJBDQOXN.js} +1 -1
  43. package/cli.js +477 -467
  44. package/locales/ca.js +26 -19
  45. package/locales/de.js +26 -19
  46. package/locales/en.js +30 -21
  47. package/locales/fr.js +26 -19
  48. package/locales/ja.js +26 -19
  49. package/locales/pt.js +26 -19
  50. package/locales/ru.js +26 -19
  51. package/package.json +2 -2
  52. package/chunks/ca-UW3G7H5I.js +0 -25
  53. package/chunks/de-QSFN3SRK.js +0 -25
  54. package/chunks/en-2BILXSUL.js +0 -25
  55. package/chunks/fr-FKTJ4COX.js +0 -25
  56. package/chunks/ja-GKS4GLZP.js +0 -25
  57. package/chunks/pt-VIW62ZAE.js +0 -25
  58. package/chunks/ru-FSSACF4A.js +0 -25
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{a as Ae,b as Cz,c as IP,d as Tz,e as U,f as Ez,g as Ze,h as Tt,i as kz,j as xz,k as sr,l as oe,m as le,n as yr,o as Ut,p as OP,q as DP,r as At,s as Jn,t as de,u as tr,v as Az,w as LP,x as Rz,y as Pz}from"./chunk-TZIDSCTF.js";import{d as Dz,e as Lz,g as Bz,h as jz,i as zz,j as NP,m as qz}from"./chunk-ROETRE5J.js";import{d as Wz,k as FP,n as Gz,p as Vz}from"./chunk-INAZKGGR.js";import{b as Ihe,i as Nz,j as Fz,k as $z,o as im,p as Uz,r as Hz}from"./chunk-DCQKJTAX.js";import{a as Gt}from"./chunk-LSDMWVW6.js";import{a as uv,b as Iz,d as BP,e as fv}from"./chunk-MTMU7JYZ.js";import{a as Kz,b as Yz,c as om}from"./chunk-TXMXCR7D.js";import{a as $P}from"./chunk-YULUB745.js";import{a as Jz,b as Xz,c as Zz,d as UP,e as Qz,f as HP}from"./chunk-VYTYYCBR.js";import{a as Ej,b as za,c as kj}from"./chunk-TISQNFB5.js";import{a as ji,b as PP,c as Bd,t as MP}from"./chunk-34DXSYJZ.js";import{a as hv,b as am}from"./chunk-FWIVFCKF.js";import{b as Mz,g as dv,j as sm,k as Oz,l as Rs}from"./chunk-QKYGQLWC.js";import{a as rt,b as jd,d as qd,e as Wd}from"./chunk-FRL6KOLY.js";import{b as $o,d as fz,f as pz,i as ct,j as mz,k as gz,l as yz,m as wz,n as _z,o as bz,p as vz,q as Sz}from"./chunk-VWWEEU4V.js";import{b as zd}from"./chunk-RNKDFE2S.js";import{a as hz}from"./chunk-Q2I3ARPJ.js";import{a as cv}from"./chunk-WOH6NLJH.js";import{a as xj}from"./chunk-QHA3ZBRO.js";import{$ as xP,U as CP,V as sz,W as az,Z as Ic,_ as nm,b as bP,ba as AP,c as vP,d as X2,e as SP,ea as av,f as Z2,ga as lv,pa as cn,qa as RP,ta as Hd}from"./chunk-6D5M34RS.js";import{a as No,c as TP}from"./chunk-4F4DA5UI.js";import{e as EP,f as kP}from"./chunk-DC7LAFZZ.js";import{m as Ud,p as iz,r as oz,v as rm}from"./chunk-S7G6QPEP.js";import{a as Vj,b as Yr,c as Yn,d as Kj,f as Yj}from"./chunk-4J6DC24J.js";import{a as Q2,g as ez,h as tz,k as $d,l as rz,m as nz}from"./chunk-SDTWBD62.js";import{$a as Xb,$b as P2,$c as fP,Ab as v2,Ac as uP,B as t2,Bb as S2,Bc as dP,Cb as C2,Cc as Lo,Db as T2,Eb as E2,Ec as hP,F as Ld,G as r2,Gb as tP,Ha as i2,Ic as B2,Jb as k2,Mc as j2,Ob as x2,Oc as z2,Qc as Fd,Rc as q2,Sb as Nd,Sc as W2,Tb as A2,Ub as R2,Va as o2,Vc as nv,Yb as Qb,Za as a2,_a as Ga,_b as rP,aa as n2,ab as l2,ac as Ac,ad as Mc,bb as c2,bc as nP,bd as G2,cb as kn,cd as sv,d as Bj,da as Wa,dc as M2,ec as sP,ed as pP,f as Do,fc as I2,fd as mP,g as Vb,ga as Zp,gb as QR,gc as iP,gd as gP,h as Kn,ha as Jb,hb as u2,hc as oP,i as qa,ib as d2,ic as aP,id as yP,jb as h2,k as Jj,kb as eP,kd as V2,l as Xj,lb as f2,m as Zj,mb as p2,mc as O2,nb as m2,nc as D2,ob as g2,oc as L2,od as K2,p as kc,pb as y2,pd as Y2,q as Xp,qb as w2,qd as J2,r as Qj,rb as _2,rc as lP,rd as wP,s as e2,sb as b2,sc as ev,t as xc,tc as tv,uc as F2,ud as _P,vb as Zb,vc as $2,vd as iv,wd as ov,xc as cP,ya as ZR,yc as tm,za as s2,zc as U2}from"./chunk-B3NVKOSU.js";import{b as Bi,h as Dr,k as N2,l as Rc,m as Lr,n as Pc,o as Qp,s as ti,t as em,w as rv}from"./chunk-32PTAACU.js";import{a as H2}from"./chunk-32T6RWWT.js";import{b as jj,c as Phe,d as Mhe,e as zj,f as qj,g as Qs,i as ei,j as Wj,k as JR,o as Gj,p as R,q as En,r as Kb,s as Yb}from"./chunk-6B5BDE7S.js";import{a as dz}from"./chunk-RJX7DK4Y.js";import{a as cz,b as Fo,c as uz}from"./chunk-ESSYHTAZ.js";import{b as lz}from"./chunk-3YLXGE6T.js";import{b as Xe,c as As,e as Dd}from"./chunk-EQEQPZLQ.js";import{A as Id,D as Ij,E as Oj,G as Zs,H as Od,J as Ec,K as Dj,N as VR,O as KR,P as fe,U as $j,V as Uj,X as Hj,_ as YR,aa as F,b as Ot,c as Wb,d as ne,e as Oo,l as Aj,q as Rj,s as Pj,v as Mj,w as ln}from"./chunk-VLYRNOD3.js";import{a as XR}from"./chunk-G7R2XEEF.js";import{g as Gb,h as Lj,l as Nj,n as Fj}from"./chunk-FWDMPRKU.js";import{a as __matilda_dirname,b as g}from"./chunk-GZPNIYVZ.js";import{a as Se,c as Ahe,d as N,e as Rhe,f as Ge}from"./chunk-OWGSC52X.js";var A3=N((pet,x3)=>{"use strict";g();x3.exports=function(e){return e.map(function(t){return t===""?"''":t&&typeof t=="object"?t.op.replace(/(.)/g,"\\$1"):/["\s\\]/.test(t)&&!/'/.test(t)?"'"+t.replace(/(['])/g,"\\$1")+"'":/["'\s]/.test(t)?'"'+t.replace(/(["\\$`!])/g,"\\$1")+'"':String(t).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g,"$1\\$2")}).join(" ")}});var L3=N((get,D3)=>{"use strict";g();var O3="(?:"+["\\|\\|","\\&\\&",";;","\\|\\&","\\<\\(","\\<\\<\\<",">>",">\\&","<\\&","[&;()|<>]"].join("|")+")",R3=new RegExp("^"+O3+"$"),P3="|&;()<> \\t",swe='"((\\\\"|[^"])*?)"',iwe="'((\\\\'|[^'])*?)'",owe=/^#$/,M3="'",I3='"',FM="$",Zc="",awe=4294967296;for($M=0;$M<4;$M++)Zc+=(awe*Math.random()).toString(16);var $M,lwe=new RegExp("^"+Zc);function cwe(r,e){for(var t=e.lastIndex,n=[],s;s=e.exec(r);)n.push(s),e.lastIndex===s.index&&(e.lastIndex+=1);return e.lastIndex=t,n}function uwe(r,e,t){var n=typeof r=="function"?r(t):r[t];return typeof n>"u"&&t!=""?n="":typeof n>"u"&&(n="$"),typeof n=="object"?e+Zc+JSON.stringify(n)+Zc:e+n}function dwe(r,e,t){t||(t={});var n=t.escape||"\\",s="(\\"+n+`['"`+P3+`]|[^\\s'"`+P3+"])+",o=new RegExp(["("+O3+")","("+s+"|"+swe+"|"+iwe+")+"].join("|"),"g"),a=cwe(r,o);if(a.length===0)return[];e||(e={});var l=!1;return a.map(function(c){var u=c[0];if(!u||l)return;if(R3.test(u))return{op:u};var d=!1,h=!1,f="",p=!1,y;function w(){y+=1;var b,v,S=u.charAt(y);if(S==="{"){if(y+=1,u.charAt(y)==="}")throw new Error("Bad substitution: "+u.slice(y-2,y+1));if(b=u.indexOf("}",y),b<0)throw new Error("Bad substitution: "+u.slice(y));v=u.slice(y,b),y=b}else if(/[*@#?$!_-]/.test(S))v=S,y+=1;else{var T=u.slice(y);b=T.match(/[^\w\d_]/),b?(v=T.slice(0,b.index),y+=b.index-1):(v=T,y=u.length)}return uwe(e,"",v)}for(y=0;y<u.length;y++){var m=u.charAt(y);if(p=p||!d&&(m==="*"||m==="?"),h)f+=m,h=!1;else if(d)m===d?d=!1:d==M3?f+=m:m===n?(y+=1,m=u.charAt(y),m===I3||m===n||m===FM?f+=m:f+=n+m):m===FM?f+=w():f+=m;else if(m===I3||m===M3)d=m;else{if(R3.test(m))return{op:u};if(owe.test(m)){l=!0;var _={comment:r.slice(c.index+y+1)};return f.length?[f,_]:[_]}else m===n?h=!0:m===FM?f+=w():f+=m}}return p?{op:"glob",pattern:f}:f}).reduce(function(c,u){return typeof u>"u"?c:c.concat(u)},[])}D3.exports=function(e,t,n){var s=dwe(e,t,n);return typeof t!="function"?s:s.reduce(function(o,a){if(typeof a=="object")return o.concat(a);var l=a.split(RegExp("("+Zc+".*?"+Zc+")","g"));return l.length===1?o.concat(l[0]):o.concat(l.filter(Boolean).map(function(c){return lwe.test(c)?JSON.parse(c.split(Zc)[1]):c}))},[])}});var il=N(UM=>{"use strict";g();UM.quote=A3();UM.parse=L3()});var h4=N((exports,module)=>{g();var Module=typeof Module<"u"?Module:{},ENVIRONMENT_IS_WEB=typeof window=="object",ENVIRONMENT_IS_WORKER=typeof importScripts=="function",ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",TreeSitter=function(){var initPromise,document=typeof window=="object"?{currentScript:window.document.currentScript}:null;class Parser{constructor(){this.initialize()}initialize(){throw new Error("cannot construct a Parser before calling `init()`")}static init(moduleOptions){return initPromise||(Module=Object.assign({},Module,moduleOptions),initPromise=new Promise(resolveInitPromise=>{var moduleOverrides=Object.assign({},Module),arguments_=[],thisProgram="./this.program",quit_=(r,e)=>{throw e},scriptDirectory="";function locateFile(r){return Module.locateFile?Module.locateFile(r,scriptDirectory):scriptDirectory+r}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=Se("fs"),nodePath=Se("path");scriptDirectory=__matilda_dirname+"/",readBinary=r=>{r=isFileURI(r)?new URL(r):nodePath.normalize(r);var e=fs.readFileSync(r);return e},readAsync=(r,e=!0)=>(r=isFileURI(r)?new URL(r):nodePath.normalize(r),new Promise((t,n)=>{fs.readFile(r,e?void 0:"utf8",(s,o)=>{s?n(s):t(e?o.buffer:o)})})),!Module.thisProgram&&process.argv.length>1&&(thisProgram=process.argv[1].replace(/\\/g,"/")),arguments_=process.argv.slice(2),typeof module<"u"&&(module.exports=Module),quit_=(r,e)=>{throw process.exitCode=r,e}}else(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)&&(ENVIRONMENT_IS_WORKER?scriptDirectory=self.location.href:typeof document<"u"&&document.currentScript&&(scriptDirectory=document.currentScript.src),scriptDirectory.startsWith("blob:")?scriptDirectory="":scriptDirectory=scriptDirectory.substr(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1),ENVIRONMENT_IS_WORKER&&(readBinary=r=>{var e=new XMLHttpRequest;return e.open("GET",r,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),readAsync=r=>isFileURI(r)?new Promise((e,t)=>{var n=new XMLHttpRequest;n.open("GET",r,!0),n.responseType="arraybuffer",n.onload=()=>{(n.status==200||n.status==0&&n.response)&&t(n.response),e(n.status)},n.onerror=e,n.send(null)}):fetch(r,{credentials:"same-origin"}).then(e=>e.ok?e.arrayBuffer():Promise.reject(new Error(e.status+" : "+e.url))));var out=Module.print||console.log.bind(console),err=Module.printErr||console.error.bind(console);Object.assign(Module,moduleOverrides),moduleOverrides=null,Module.arguments&&(arguments_=Module.arguments),Module.thisProgram&&(thisProgram=Module.thisProgram),Module.quit&&(quit_=Module.quit);var dynamicLibraries=Module.dynamicLibraries||[],wasmBinary;Module.wasmBinary&&(wasmBinary=Module.wasmBinary);var wasmMemory,ABORT=!1,EXITSTATUS,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64,HEAP_DATA_VIEW;function updateMemoryViews(){var r=wasmMemory.buffer;Module.HEAP_DATA_VIEW=HEAP_DATA_VIEW=new DataView(r),Module.HEAP8=HEAP8=new Int8Array(r),Module.HEAP16=HEAP16=new Int16Array(r),Module.HEAPU8=HEAPU8=new Uint8Array(r),Module.HEAPU16=HEAPU16=new Uint16Array(r),Module.HEAP32=HEAP32=new Int32Array(r),Module.HEAPU32=HEAPU32=new Uint32Array(r),Module.HEAPF32=HEAPF32=new Float32Array(r),Module.HEAPF64=HEAPF64=new Float64Array(r)}if(Module.wasmMemory)wasmMemory=Module.wasmMemory;else{var INITIAL_MEMORY=Module.INITIAL_MEMORY||33554432;wasmMemory=new WebAssembly.Memory({initial:INITIAL_MEMORY/65536,maximum:2147483648/65536})}updateMemoryViews();var __ATPRERUN__=[],__ATINIT__=[],__ATMAIN__=[],__ATPOSTRUN__=[],__RELOC_FUNCS__=[],runtimeInitialized=!1;function preRun(){if(Module.preRun)for(typeof Module.preRun=="function"&&(Module.preRun=[Module.preRun]);Module.preRun.length;)addOnPreRun(Module.preRun.shift());callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=!0,callRuntimeCallbacks(__RELOC_FUNCS__),callRuntimeCallbacks(__ATINIT__)}function preMain(){callRuntimeCallbacks(__ATMAIN__)}function postRun(){if(Module.postRun)for(typeof Module.postRun=="function"&&(Module.postRun=[Module.postRun]);Module.postRun.length;)addOnPostRun(Module.postRun.shift());callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(r){__ATPRERUN__.unshift(r)}function addOnInit(r){__ATINIT__.unshift(r)}function addOnPostRun(r){__ATPOSTRUN__.unshift(r)}var runDependencies=0,runDependencyWatcher=null,dependenciesFulfilled=null;function getUniqueRunDependency(r){return r}function addRunDependency(r){runDependencies++,Module.monitorRunDependencies?.(runDependencies)}function removeRunDependency(r){if(runDependencies--,Module.monitorRunDependencies?.(runDependencies),runDependencies==0&&(runDependencyWatcher!==null&&(clearInterval(runDependencyWatcher),runDependencyWatcher=null),dependenciesFulfilled)){var e=dependenciesFulfilled;dependenciesFulfilled=null,e()}}function abort(r){Module.onAbort?.(r),r="Aborted("+r+")",err(r),ABORT=!0,EXITSTATUS=1,r+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(r);throw e}var dataURIPrefix="data:application/octet-stream;base64,",isDataURI=r=>r.startsWith(dataURIPrefix),isFileURI=r=>r.startsWith("file://");function findWasmBinary(){var r="tree-sitter.wasm";return isDataURI(r)?r:locateFile(r)}var wasmBinaryFile;function getBinarySync(r){if(r==wasmBinaryFile&&wasmBinary)return new Uint8Array(wasmBinary);if(readBinary)return readBinary(r);throw"both async and sync fetching of the wasm failed"}function getBinaryPromise(r){return wasmBinary?Promise.resolve().then(()=>getBinarySync(r)):readAsync(r).then(e=>new Uint8Array(e),()=>getBinarySync(r))}function instantiateArrayBuffer(r,e,t){return getBinaryPromise(r).then(n=>WebAssembly.instantiate(n,e)).then(t,n=>{err(`failed to asynchronously prepare wasm: ${n}`),abort(n)})}function instantiateAsync(r,e,t,n){return!r&&typeof WebAssembly.instantiateStreaming=="function"&&!isDataURI(e)&&!isFileURI(e)&&!ENVIRONMENT_IS_NODE&&typeof fetch=="function"?fetch(e,{credentials:"same-origin"}).then(s=>{var o=WebAssembly.instantiateStreaming(s,t);return o.then(n,function(a){return err(`wasm streaming compile failed: ${a}`),err("falling back to ArrayBuffer instantiation"),instantiateArrayBuffer(e,t,n)})}):instantiateArrayBuffer(e,t,n)}function getWasmImports(){return{env:wasmImports,wasi_snapshot_preview1:wasmImports,"GOT.mem":new Proxy(wasmImports,GOTHandler),"GOT.func":new Proxy(wasmImports,GOTHandler)}}function createWasm(){var r=getWasmImports();function e(n,s){wasmExports=n.exports,wasmExports=relocateExports(wasmExports,1024);var o=getDylinkMetadata(s);return o.neededDynlibs&&(dynamicLibraries=o.neededDynlibs.concat(dynamicLibraries)),mergeLibSymbols(wasmExports,"main"),LDSO.init(),loadDylibs(),addOnInit(wasmExports.__wasm_call_ctors),__RELOC_FUNCS__.push(wasmExports.__wasm_apply_data_relocs),removeRunDependency("wasm-instantiate"),wasmExports}addRunDependency("wasm-instantiate");function t(n){e(n.instance,n.module)}if(Module.instantiateWasm)try{return Module.instantiateWasm(r,e)}catch(n){return err(`Module.instantiateWasm callback failed with error: ${n}`),!1}return wasmBinaryFile||(wasmBinaryFile=findWasmBinary()),instantiateAsync(wasmBinary,wasmBinaryFile,r,t),{}}var ASM_CONSTS={};function ExitStatus(r){this.name="ExitStatus",this.message=`Program terminated with exit(${r})`,this.status=r}var GOT={},currentModuleWeakSymbols=new Set([]),GOTHandler={get(r,e){var t=GOT[e];return t||(t=GOT[e]=new WebAssembly.Global({value:"i32",mutable:!0})),currentModuleWeakSymbols.has(e)||(t.required=!0),t}},LE_HEAP_LOAD_F32=r=>HEAP_DATA_VIEW.getFloat32(r,!0),LE_HEAP_LOAD_F64=r=>HEAP_DATA_VIEW.getFloat64(r,!0),LE_HEAP_LOAD_I16=r=>HEAP_DATA_VIEW.getInt16(r,!0),LE_HEAP_LOAD_I32=r=>HEAP_DATA_VIEW.getInt32(r,!0),LE_HEAP_LOAD_U32=r=>HEAP_DATA_VIEW.getUint32(r,!0),LE_HEAP_STORE_F32=(r,e)=>HEAP_DATA_VIEW.setFloat32(r,e,!0),LE_HEAP_STORE_F64=(r,e)=>HEAP_DATA_VIEW.setFloat64(r,e,!0),LE_HEAP_STORE_I16=(r,e)=>HEAP_DATA_VIEW.setInt16(r,e,!0),LE_HEAP_STORE_I32=(r,e)=>HEAP_DATA_VIEW.setInt32(r,e,!0),LE_HEAP_STORE_U32=(r,e)=>HEAP_DATA_VIEW.setUint32(r,e,!0),callRuntimeCallbacks=r=>{for(;r.length>0;)r.shift()(Module)},UTF8Decoder=typeof TextDecoder<"u"?new TextDecoder:void 0,UTF8ArrayToString=(r,e,t)=>{for(var n=e+t,s=e;r[s]&&!(s>=n);)++s;if(s-e>16&&r.buffer&&UTF8Decoder)return UTF8Decoder.decode(r.subarray(e,s));for(var o="";e<s;){var a=r[e++];if(!(a&128)){o+=String.fromCharCode(a);continue}var l=r[e++]&63;if((a&224)==192){o+=String.fromCharCode((a&31)<<6|l);continue}var c=r[e++]&63;if((a&240)==224?a=(a&15)<<12|l<<6|c:a=(a&7)<<18|l<<12|c<<6|r[e++]&63,a<65536)o+=String.fromCharCode(a);else{var u=a-65536;o+=String.fromCharCode(55296|u>>10,56320|u&1023)}}return o},getDylinkMetadata=r=>{var e=0,t=0;function n(){return r[e++]}function s(){for(var q=0,j=1;;){var z=r[e++];if(q+=(z&127)*j,j*=128,!(z&128))break}return q}function o(){var q=s();return e+=q,UTF8ArrayToString(r,e-q,q)}function a(q,j){if(q)throw new Error(j)}var l="dylink.0";if(r instanceof WebAssembly.Module){var c=WebAssembly.Module.customSections(r,l);c.length===0&&(l="dylink",c=WebAssembly.Module.customSections(r,l)),a(c.length===0,"need dylink section"),r=new Uint8Array(c[0]),t=r.length}else{var u=new Uint32Array(new Uint8Array(r.subarray(0,24)).buffer),d=u[0]==1836278016||u[0]==6386541;a(!d,"need to see wasm magic number"),a(r[8]!==0,"need the dylink section to be first"),e=9;var h=s();t=e+h,l=o()}var f={neededDynlibs:[],tlsExports:new Set,weakImports:new Set};if(l=="dylink"){f.memorySize=s(),f.memoryAlign=s(),f.tableSize=s(),f.tableAlign=s();for(var p=s(),y=0;y<p;++y){var w=o();f.neededDynlibs.push(w)}}else{a(l!=="dylink.0");for(var m=1,_=2,b=3,v=4,S=256,T=3,E=1;e<t;){var x=n(),k=s();if(x===m)f.memorySize=s(),f.memoryAlign=s(),f.tableSize=s(),f.tableAlign=s();else if(x===_)for(var p=s(),y=0;y<p;++y)w=o(),f.neededDynlibs.push(w);else if(x===b)for(var P=s();P--;){var B=o(),L=s();L&S&&f.tlsExports.add(B)}else if(x===v)for(var P=s();P--;){var $=o(),B=o(),L=s();(L&T)==E&&f.weakImports.add(B)}else e+=k}}return f};function getValue(r,e="i8"){switch(e.endsWith("*")&&(e="*"),e){case"i1":return HEAP8[r];case"i8":return HEAP8[r];case"i16":return LE_HEAP_LOAD_I16((r>>1)*2);case"i32":return LE_HEAP_LOAD_I32((r>>2)*4);case"i64":abort("to do getValue(i64) use WASM_BIGINT");case"float":return LE_HEAP_LOAD_F32((r>>2)*4);case"double":return LE_HEAP_LOAD_F64((r>>3)*8);case"*":return LE_HEAP_LOAD_U32((r>>2)*4);default:abort(`invalid type for getValue: ${e}`)}}var newDSO=(r,e,t)=>{var n={refcount:1/0,name:r,exports:t,global:!0};return LDSO.loadedLibsByName[r]=n,e!=null&&(LDSO.loadedLibsByHandle[e]=n),n},LDSO={loadedLibsByName:{},loadedLibsByHandle:{},init(){newDSO("__main__",0,wasmImports)}},___heap_base=78112,zeroMemory=(r,e)=>(HEAPU8.fill(0,r,r+e),r),alignMemory=(r,e)=>Math.ceil(r/e)*e,getMemory=r=>{if(runtimeInitialized)return zeroMemory(_malloc(r),r);var e=___heap_base,t=e+alignMemory(r,16);return ___heap_base=t,GOT.__heap_base.value=t,e},isInternalSym=r=>["__cpp_exception","__c_longjmp","__wasm_apply_data_relocs","__dso_handle","__tls_size","__tls_align","__set_stack_limits","_emscripten_tls_init","__wasm_init_tls","__wasm_call_ctors","__start_em_asm","__stop_em_asm","__start_em_js","__stop_em_js"].includes(r)||r.startsWith("__em_js__"),uleb128Encode=(r,e)=>{r<128?e.push(r):e.push(r%128|128,r>>7)},sigToWasmTypes=r=>{for(var e={i:"i32",j:"i64",f:"f32",d:"f64",e:"externref",p:"i32"},t={parameters:[],results:r[0]=="v"?[]:[e[r[0]]]},n=1;n<r.length;++n)t.parameters.push(e[r[n]]);return t},generateFuncType=(r,e)=>{var t=r.slice(0,1),n=r.slice(1),s={i:127,p:127,j:126,f:125,d:124,e:111};e.push(96),uleb128Encode(n.length,e);for(var o=0;o<n.length;++o)e.push(s[n[o]]);t=="v"?e.push(0):e.push(1,s[t])},convertJsFunctionToWasm=(r,e)=>{if(typeof WebAssembly.Function=="function")return new WebAssembly.Function(sigToWasmTypes(e),r);var t=[1];generateFuncType(e,t);var n=[0,97,115,109,1,0,0,0,1];uleb128Encode(t.length,n),n.push(...t),n.push(2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0);var s=new WebAssembly.Module(new Uint8Array(n)),o=new WebAssembly.Instance(s,{e:{f:r}}),a=o.exports.f;return a},wasmTableMirror=[],wasmTable=new WebAssembly.Table({initial:28,element:"anyfunc"}),getWasmTableEntry=r=>{var e=wasmTableMirror[r];return e||(r>=wasmTableMirror.length&&(wasmTableMirror.length=r+1),wasmTableMirror[r]=e=wasmTable.get(r)),e},updateTableMap=(r,e)=>{if(functionsInTableMap)for(var t=r;t<r+e;t++){var n=getWasmTableEntry(t);n&&functionsInTableMap.set(n,t)}},functionsInTableMap,getFunctionAddress=r=>(functionsInTableMap||(functionsInTableMap=new WeakMap,updateTableMap(0,wasmTable.length)),functionsInTableMap.get(r)||0),freeTableIndexes=[],getEmptyTableSlot=()=>{if(freeTableIndexes.length)return freeTableIndexes.pop();try{wasmTable.grow(1)}catch(r){throw r instanceof RangeError?"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.":r}return wasmTable.length-1},setWasmTableEntry=(r,e)=>{wasmTable.set(r,e),wasmTableMirror[r]=wasmTable.get(r)},addFunction=(r,e)=>{var t=getFunctionAddress(r);if(t)return t;var n=getEmptyTableSlot();try{setWasmTableEntry(n,r)}catch(o){if(!(o instanceof TypeError))throw o;var s=convertJsFunctionToWasm(r,e);setWasmTableEntry(n,s)}return functionsInTableMap.set(r,n),n},updateGOT=(r,e)=>{for(var t in r)if(!isInternalSym(t)){var n=r[t];t.startsWith("orig$")&&(t=t.split("$")[1],e=!0),GOT[t]||=new WebAssembly.Global({value:"i32",mutable:!0}),(e||GOT[t].value==0)&&(typeof n=="function"?GOT[t].value=addFunction(n):typeof n=="number"?GOT[t].value=n:err(`unhandled export type for '${t}': ${typeof n}`))}},relocateExports=(r,e,t)=>{var n={};for(var s in r){var o=r[s];typeof o=="object"&&(o=o.value),typeof o=="number"&&(o+=e),n[s]=o}return updateGOT(n,t),n},isSymbolDefined=r=>{var e=wasmImports[r];return!(!e||e.stub)},dynCallLegacy=(r,e,t)=>{r=r.replace(/p/g,"i");var n=Module["dynCall_"+r];return n(e,...t)},dynCall=(r,e,t=[])=>{if(r.includes("j"))return dynCallLegacy(r,e,t);var n=getWasmTableEntry(e)(...t);return n},stackSave=()=>_emscripten_stack_get_current(),stackRestore=r=>__emscripten_stack_restore(r),createInvokeFunction=r=>(e,...t)=>{var n=stackSave();try{return dynCall(r,e,t)}catch(s){if(stackRestore(n),s!==s+0)throw s;_setThrew(1,0)}},resolveGlobalSymbol=(r,e=!1)=>{var t;return e&&"orig$"+r in wasmImports&&(r="orig$"+r),isSymbolDefined(r)?t=wasmImports[r]:r.startsWith("invoke_")&&(t=wasmImports[r]=createInvokeFunction(r.split("_")[1])),{sym:t,name:r}},UTF8ToString=(r,e)=>r?UTF8ArrayToString(HEAPU8,r,e):"",loadWebAssemblyModule=(binary,flags,libName,localScope,handle)=>{var metadata=getDylinkMetadata(binary);currentModuleWeakSymbols=metadata.weakImports;function loadModule(){var firstLoad=!handle||!HEAP8[handle+8];if(firstLoad){var memAlign=Math.pow(2,metadata.memoryAlign),memoryBase=metadata.memorySize?alignMemory(getMemory(metadata.memorySize+memAlign),memAlign):0,tableBase=metadata.tableSize?wasmTable.length:0;handle&&(HEAP8[handle+8]=1,LE_HEAP_STORE_U32((handle+12>>2)*4,memoryBase),LE_HEAP_STORE_I32((handle+16>>2)*4,metadata.memorySize),LE_HEAP_STORE_U32((handle+20>>2)*4,tableBase),LE_HEAP_STORE_I32((handle+24>>2)*4,metadata.tableSize))}else memoryBase=LE_HEAP_LOAD_U32((handle+12>>2)*4),tableBase=LE_HEAP_LOAD_U32((handle+20>>2)*4);var tableGrowthNeeded=tableBase+metadata.tableSize-wasmTable.length;tableGrowthNeeded>0&&wasmTable.grow(tableGrowthNeeded);var moduleExports;function resolveSymbol(r){var e=resolveGlobalSymbol(r).sym;return!e&&localScope&&(e=localScope[r]),e||(e=moduleExports[r]),e}var proxyHandler={get(r,e){switch(e){case"__memory_base":return memoryBase;case"__table_base":return tableBase}if(e in wasmImports&&!wasmImports[e].stub)return wasmImports[e];if(!(e in r)){var t;r[e]=(...n)=>(t||=resolveSymbol(e),t(...n))}return r[e]}},proxy=new Proxy({},proxyHandler),info={"GOT.mem":new Proxy({},GOTHandler),"GOT.func":new Proxy({},GOTHandler),env:proxy,wasi_snapshot_preview1:proxy};function postInstantiation(module,instance){updateTableMap(tableBase,metadata.tableSize),moduleExports=relocateExports(instance.exports,memoryBase),flags.allowUndefined||reportUndefinedSymbols();function addEmAsm(addr,body){for(var args=[],arity=0;arity<16&&body.indexOf("$"+arity)!=-1;arity++)args.push("$"+arity);args=args.join(",");var func=`(${args}) => { ${body} };`;ASM_CONSTS[start]=eval(func)}if("__start_em_asm"in moduleExports)for(var start=moduleExports.__start_em_asm,stop=moduleExports.__stop_em_asm;start<stop;){var jsString=UTF8ToString(start);addEmAsm(start,jsString),start=HEAPU8.indexOf(0,start)+1}function addEmJs(name,cSig,body){var jsArgs=[];if(cSig=cSig.slice(1,-1),cSig!="void"){cSig=cSig.split(",");for(var i in cSig){var jsArg=cSig[i].split(" ").pop();jsArgs.push(jsArg.replace("*",""))}}var func=`(${jsArgs}) => ${body};`;moduleExports[name]=eval(func)}for(var name in moduleExports)if(name.startsWith("__em_js__")){var start=moduleExports[name],jsString=UTF8ToString(start),parts=jsString.split("<::>");addEmJs(name.replace("__em_js__",""),parts[0],parts[1]),delete moduleExports[name]}var applyRelocs=moduleExports.__wasm_apply_data_relocs;applyRelocs&&(runtimeInitialized?applyRelocs():__RELOC_FUNCS__.push(applyRelocs));var init=moduleExports.__wasm_call_ctors;return init&&(runtimeInitialized?init():__ATINIT__.push(init)),moduleExports}if(flags.loadAsync){if(binary instanceof WebAssembly.Module){var instance=new WebAssembly.Instance(binary,info);return Promise.resolve(postInstantiation(binary,instance))}return WebAssembly.instantiate(binary,info).then(r=>postInstantiation(r.module,r.instance))}var module=binary instanceof WebAssembly.Module?binary:new WebAssembly.Module(binary),instance=new WebAssembly.Instance(module,info);return postInstantiation(module,instance)}return flags.loadAsync?metadata.neededDynlibs.reduce((r,e)=>r.then(()=>loadDynamicLibrary(e,flags,localScope)),Promise.resolve()).then(loadModule):(metadata.neededDynlibs.forEach(r=>loadDynamicLibrary(r,flags,localScope)),loadModule())},mergeLibSymbols=(r,e)=>{for(var[t,n]of Object.entries(r)){let s=a=>{isSymbolDefined(a)||(wasmImports[a]=n)};s(t);let o="__main_argc_argv";t=="main"&&s(o),t==o&&s("main"),t.startsWith("dynCall_")&&!Module.hasOwnProperty(t)&&(Module[t]=n)}},asyncLoad=(r,e,t,n)=>{var s=n?"":`al ${r}`;readAsync(r).then(o=>{e(new Uint8Array(o)),s&&removeRunDependency(s)},o=>{if(t)t();else throw`Loading data file "${r}" failed.`}),s&&addRunDependency(s)};function loadDynamicLibrary(r,e={global:!0,nodelete:!0},t,n){var s=LDSO.loadedLibsByName[r];if(s)return e.global?s.global||(s.global=!0,mergeLibSymbols(s.exports,r)):t&&Object.assign(t,s.exports),e.nodelete&&s.refcount!==1/0&&(s.refcount=1/0),s.refcount++,n&&(LDSO.loadedLibsByHandle[n]=s),e.loadAsync?Promise.resolve(!0):!0;s=newDSO(r,n,"loading"),s.refcount=e.nodelete?1/0:1,s.global=e.global;function o(){if(n){var c=LE_HEAP_LOAD_U32((n+28>>2)*4),u=LE_HEAP_LOAD_U32((n+32>>2)*4);if(c&&u){var d=HEAP8.slice(c,c+u);return e.loadAsync?Promise.resolve(d):d}}var h=locateFile(r);if(e.loadAsync)return new Promise(function(f,p){asyncLoad(h,f,p)});if(!readBinary)throw new Error(`${h}: file not found, and synchronous loading of external files is not available`);return readBinary(h)}function a(){return e.loadAsync?o().then(c=>loadWebAssemblyModule(c,e,r,t,n)):loadWebAssemblyModule(o(),e,r,t,n)}function l(c){s.global?mergeLibSymbols(c,r):t&&Object.assign(t,c),s.exports=c}return e.loadAsync?a().then(c=>(l(c),!0)):(l(a()),!0)}var reportUndefinedSymbols=()=>{for(var[r,e]of Object.entries(GOT))if(e.value==0){var t=resolveGlobalSymbol(r,!0).sym;if(!t&&!e.required)continue;if(typeof t=="function")e.value=addFunction(t,t.sig);else if(typeof t=="number")e.value=t;else throw new Error(`bad export type for '${r}': ${typeof t}`)}},loadDylibs=()=>{if(!dynamicLibraries.length){reportUndefinedSymbols();return}addRunDependency("loadDylibs"),dynamicLibraries.reduce((r,e)=>r.then(()=>loadDynamicLibrary(e,{loadAsync:!0,global:!0,nodelete:!0,allowUndefined:!0})),Promise.resolve()).then(()=>{reportUndefinedSymbols(),removeRunDependency("loadDylibs")})},noExitRuntime=Module.noExitRuntime||!0;function setValue(r,e,t="i8"){switch(t.endsWith("*")&&(t="*"),t){case"i1":HEAP8[r]=e;break;case"i8":HEAP8[r]=e;break;case"i16":LE_HEAP_STORE_I16((r>>1)*2,e);break;case"i32":LE_HEAP_STORE_I32((r>>2)*4,e);break;case"i64":abort("to do setValue(i64) use WASM_BIGINT");case"float":LE_HEAP_STORE_F32((r>>2)*4,e);break;case"double":LE_HEAP_STORE_F64((r>>3)*8,e);break;case"*":LE_HEAP_STORE_U32((r>>2)*4,e);break;default:abort(`invalid type for setValue: ${t}`)}}var ___memory_base=new WebAssembly.Global({value:"i32",mutable:!1},1024),___stack_pointer=new WebAssembly.Global({value:"i32",mutable:!0},78112),___table_base=new WebAssembly.Global({value:"i32",mutable:!1},1),__abort_js=()=>{abort("")};__abort_js.sig="v";var nowIsMonotonic=1,__emscripten_get_now_is_monotonic=()=>nowIsMonotonic;__emscripten_get_now_is_monotonic.sig="i";var __emscripten_memcpy_js=(r,e,t)=>HEAPU8.copyWithin(r,e,e+t);__emscripten_memcpy_js.sig="vppp";var _emscripten_date_now=()=>Date.now();_emscripten_date_now.sig="d";var _emscripten_get_now;_emscripten_get_now=()=>performance.now(),_emscripten_get_now.sig="d";var getHeapMax=()=>2147483648,growMemory=r=>{var e=wasmMemory.buffer,t=(r-e.byteLength+65535)/65536;try{return wasmMemory.grow(t),updateMemoryViews(),1}catch{}},_emscripten_resize_heap=r=>{var e=HEAPU8.length;r>>>=0;var t=getHeapMax();if(r>t)return!1;for(var n=(c,u)=>c+(u-c%u)%u,s=1;s<=4;s*=2){var o=e*(1+.2/s);o=Math.min(o,r+100663296);var a=Math.min(t,n(Math.max(r,o),65536)),l=growMemory(a);if(l)return!0}return!1};_emscripten_resize_heap.sig="ip";var _fd_close=r=>52;_fd_close.sig="ii";var convertI32PairToI53Checked=(r,e)=>e+2097152>>>0<4194305-!!r?(r>>>0)+e*4294967296:NaN;function _fd_seek(r,e,t,n,s){var o=convertI32PairToI53Checked(e,t);return 70}_fd_seek.sig="iiiiip";var printCharBuffers=[null,[],[]],printChar=(r,e)=>{var t=printCharBuffers[r];e===0||e===10?((r===1?out:err)(UTF8ArrayToString(t,0)),t.length=0):t.push(e)},_fd_write=(r,e,t,n)=>{for(var s=0,o=0;o<t;o++){var a=LE_HEAP_LOAD_U32((e>>2)*4),l=LE_HEAP_LOAD_U32((e+4>>2)*4);e+=8;for(var c=0;c<l;c++)printChar(r,HEAPU8[a+c]);s+=l}return LE_HEAP_STORE_U32((n>>2)*4,s),0};_fd_write.sig="iippp";function _tree_sitter_log_callback(r,e){if(currentLogCallback){let t=UTF8ToString(e);currentLogCallback(t,r!==0)}}function _tree_sitter_parse_callback(r,e,t,n,s){let a=currentParseCallback(e,{row:t,column:n});typeof a=="string"?(setValue(s,a.length,"i32"),stringToUTF16(a,r,10240)):setValue(s,0,"i32")}var runtimeKeepaliveCounter=0,keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0,_proc_exit=r=>{EXITSTATUS=r,keepRuntimeAlive()||(Module.onExit?.(r),ABORT=!0),quit_(r,new ExitStatus(r))};_proc_exit.sig="vi";var exitJS=(r,e)=>{EXITSTATUS=r,_proc_exit(r)},handleException=r=>{if(r instanceof ExitStatus||r=="unwind")return EXITSTATUS;quit_(1,r)},lengthBytesUTF8=r=>{for(var e=0,t=0;t<r.length;++t){var n=r.charCodeAt(t);n<=127?e++:n<=2047?e+=2:n>=55296&&n<=57343?(e+=4,++t):e+=3}return e},stringToUTF8Array=(r,e,t,n)=>{if(!(n>0))return 0;for(var s=t,o=t+n-1,a=0;a<r.length;++a){var l=r.charCodeAt(a);if(l>=55296&&l<=57343){var c=r.charCodeAt(++a);l=65536+((l&1023)<<10)|c&1023}if(l<=127){if(t>=o)break;e[t++]=l}else if(l<=2047){if(t+1>=o)break;e[t++]=192|l>>6,e[t++]=128|l&63}else if(l<=65535){if(t+2>=o)break;e[t++]=224|l>>12,e[t++]=128|l>>6&63,e[t++]=128|l&63}else{if(t+3>=o)break;e[t++]=240|l>>18,e[t++]=128|l>>12&63,e[t++]=128|l>>6&63,e[t++]=128|l&63}}return e[t]=0,t-s},stringToUTF8=(r,e,t)=>stringToUTF8Array(r,HEAPU8,e,t),stackAlloc=r=>__emscripten_stack_alloc(r),stringToUTF8OnStack=r=>{var e=lengthBytesUTF8(r)+1,t=stackAlloc(e);return stringToUTF8(r,t,e),t},stringToUTF16=(r,e,t)=>{if(t??=2147483647,t<2)return 0;t-=2;for(var n=e,s=t<r.length*2?t/2:r.length,o=0;o<s;++o){var a=r.charCodeAt(o);LE_HEAP_STORE_I16((e>>1)*2,a),e+=2}return LE_HEAP_STORE_I16((e>>1)*2,0),e-n},AsciiToString=r=>{for(var e="";;){var t=HEAPU8[r++];if(!t)return e;e+=String.fromCharCode(t)}},wasmImports={__heap_base:___heap_base,__indirect_function_table:wasmTable,__memory_base:___memory_base,__stack_pointer:___stack_pointer,__table_base:___table_base,_abort_js:__abort_js,_emscripten_get_now_is_monotonic:__emscripten_get_now_is_monotonic,_emscripten_memcpy_js:__emscripten_memcpy_js,emscripten_get_now:_emscripten_get_now,emscripten_resize_heap:_emscripten_resize_heap,fd_close:_fd_close,fd_seek:_fd_seek,fd_write:_fd_write,memory:wasmMemory,tree_sitter_log_callback:_tree_sitter_log_callback,tree_sitter_parse_callback:_tree_sitter_parse_callback},wasmExports=createWasm(),___wasm_call_ctors=()=>(___wasm_call_ctors=wasmExports.__wasm_call_ctors)(),___wasm_apply_data_relocs=()=>(___wasm_apply_data_relocs=wasmExports.__wasm_apply_data_relocs)(),_malloc=Module._malloc=r=>(_malloc=Module._malloc=wasmExports.malloc)(r),_calloc=Module._calloc=(r,e)=>(_calloc=Module._calloc=wasmExports.calloc)(r,e),_realloc=Module._realloc=(r,e)=>(_realloc=Module._realloc=wasmExports.realloc)(r,e),_free=Module._free=r=>(_free=Module._free=wasmExports.free)(r),_ts_language_symbol_count=Module._ts_language_symbol_count=r=>(_ts_language_symbol_count=Module._ts_language_symbol_count=wasmExports.ts_language_symbol_count)(r),_ts_language_state_count=Module._ts_language_state_count=r=>(_ts_language_state_count=Module._ts_language_state_count=wasmExports.ts_language_state_count)(r),_ts_language_version=Module._ts_language_version=r=>(_ts_language_version=Module._ts_language_version=wasmExports.ts_language_version)(r),_ts_language_field_count=Module._ts_language_field_count=r=>(_ts_language_field_count=Module._ts_language_field_count=wasmExports.ts_language_field_count)(r),_ts_language_next_state=Module._ts_language_next_state=(r,e,t)=>(_ts_language_next_state=Module._ts_language_next_state=wasmExports.ts_language_next_state)(r,e,t),_ts_language_symbol_name=Module._ts_language_symbol_name=(r,e)=>(_ts_language_symbol_name=Module._ts_language_symbol_name=wasmExports.ts_language_symbol_name)(r,e),_ts_language_symbol_for_name=Module._ts_language_symbol_for_name=(r,e,t,n)=>(_ts_language_symbol_for_name=Module._ts_language_symbol_for_name=wasmExports.ts_language_symbol_for_name)(r,e,t,n),_strncmp=Module._strncmp=(r,e,t)=>(_strncmp=Module._strncmp=wasmExports.strncmp)(r,e,t),_ts_language_symbol_type=Module._ts_language_symbol_type=(r,e)=>(_ts_language_symbol_type=Module._ts_language_symbol_type=wasmExports.ts_language_symbol_type)(r,e),_ts_language_field_name_for_id=Module._ts_language_field_name_for_id=(r,e)=>(_ts_language_field_name_for_id=Module._ts_language_field_name_for_id=wasmExports.ts_language_field_name_for_id)(r,e),_ts_lookahead_iterator_new=Module._ts_lookahead_iterator_new=(r,e)=>(_ts_lookahead_iterator_new=Module._ts_lookahead_iterator_new=wasmExports.ts_lookahead_iterator_new)(r,e),_ts_lookahead_iterator_delete=Module._ts_lookahead_iterator_delete=r=>(_ts_lookahead_iterator_delete=Module._ts_lookahead_iterator_delete=wasmExports.ts_lookahead_iterator_delete)(r),_ts_lookahead_iterator_reset_state=Module._ts_lookahead_iterator_reset_state=(r,e)=>(_ts_lookahead_iterator_reset_state=Module._ts_lookahead_iterator_reset_state=wasmExports.ts_lookahead_iterator_reset_state)(r,e),_ts_lookahead_iterator_reset=Module._ts_lookahead_iterator_reset=(r,e,t)=>(_ts_lookahead_iterator_reset=Module._ts_lookahead_iterator_reset=wasmExports.ts_lookahead_iterator_reset)(r,e,t),_ts_lookahead_iterator_next=Module._ts_lookahead_iterator_next=r=>(_ts_lookahead_iterator_next=Module._ts_lookahead_iterator_next=wasmExports.ts_lookahead_iterator_next)(r),_ts_lookahead_iterator_current_symbol=Module._ts_lookahead_iterator_current_symbol=r=>(_ts_lookahead_iterator_current_symbol=Module._ts_lookahead_iterator_current_symbol=wasmExports.ts_lookahead_iterator_current_symbol)(r),_memset=Module._memset=(r,e,t)=>(_memset=Module._memset=wasmExports.memset)(r,e,t),_memcpy=Module._memcpy=(r,e,t)=>(_memcpy=Module._memcpy=wasmExports.memcpy)(r,e,t),_ts_parser_delete=Module._ts_parser_delete=r=>(_ts_parser_delete=Module._ts_parser_delete=wasmExports.ts_parser_delete)(r),_ts_parser_reset=Module._ts_parser_reset=r=>(_ts_parser_reset=Module._ts_parser_reset=wasmExports.ts_parser_reset)(r),_ts_parser_set_language=Module._ts_parser_set_language=(r,e)=>(_ts_parser_set_language=Module._ts_parser_set_language=wasmExports.ts_parser_set_language)(r,e),_ts_parser_timeout_micros=Module._ts_parser_timeout_micros=r=>(_ts_parser_timeout_micros=Module._ts_parser_timeout_micros=wasmExports.ts_parser_timeout_micros)(r),_ts_parser_set_timeout_micros=Module._ts_parser_set_timeout_micros=(r,e,t)=>(_ts_parser_set_timeout_micros=Module._ts_parser_set_timeout_micros=wasmExports.ts_parser_set_timeout_micros)(r,e,t),_ts_parser_set_included_ranges=Module._ts_parser_set_included_ranges=(r,e,t)=>(_ts_parser_set_included_ranges=Module._ts_parser_set_included_ranges=wasmExports.ts_parser_set_included_ranges)(r,e,t),_memmove=Module._memmove=(r,e,t)=>(_memmove=Module._memmove=wasmExports.memmove)(r,e,t),_memcmp=Module._memcmp=(r,e,t)=>(_memcmp=Module._memcmp=wasmExports.memcmp)(r,e,t),_ts_query_new=Module._ts_query_new=(r,e,t,n,s)=>(_ts_query_new=Module._ts_query_new=wasmExports.ts_query_new)(r,e,t,n,s),_ts_query_delete=Module._ts_query_delete=r=>(_ts_query_delete=Module._ts_query_delete=wasmExports.ts_query_delete)(r),_iswspace=Module._iswspace=r=>(_iswspace=Module._iswspace=wasmExports.iswspace)(r),_iswalnum=Module._iswalnum=r=>(_iswalnum=Module._iswalnum=wasmExports.iswalnum)(r),_ts_query_pattern_count=Module._ts_query_pattern_count=r=>(_ts_query_pattern_count=Module._ts_query_pattern_count=wasmExports.ts_query_pattern_count)(r),_ts_query_capture_count=Module._ts_query_capture_count=r=>(_ts_query_capture_count=Module._ts_query_capture_count=wasmExports.ts_query_capture_count)(r),_ts_query_string_count=Module._ts_query_string_count=r=>(_ts_query_string_count=Module._ts_query_string_count=wasmExports.ts_query_string_count)(r),_ts_query_capture_name_for_id=Module._ts_query_capture_name_for_id=(r,e,t)=>(_ts_query_capture_name_for_id=Module._ts_query_capture_name_for_id=wasmExports.ts_query_capture_name_for_id)(r,e,t),_ts_query_string_value_for_id=Module._ts_query_string_value_for_id=(r,e,t)=>(_ts_query_string_value_for_id=Module._ts_query_string_value_for_id=wasmExports.ts_query_string_value_for_id)(r,e,t),_ts_query_predicates_for_pattern=Module._ts_query_predicates_for_pattern=(r,e,t)=>(_ts_query_predicates_for_pattern=Module._ts_query_predicates_for_pattern=wasmExports.ts_query_predicates_for_pattern)(r,e,t),_ts_query_disable_capture=Module._ts_query_disable_capture=(r,e,t)=>(_ts_query_disable_capture=Module._ts_query_disable_capture=wasmExports.ts_query_disable_capture)(r,e,t),_ts_tree_copy=Module._ts_tree_copy=r=>(_ts_tree_copy=Module._ts_tree_copy=wasmExports.ts_tree_copy)(r),_ts_tree_delete=Module._ts_tree_delete=r=>(_ts_tree_delete=Module._ts_tree_delete=wasmExports.ts_tree_delete)(r),_ts_init=Module._ts_init=()=>(_ts_init=Module._ts_init=wasmExports.ts_init)(),_ts_parser_new_wasm=Module._ts_parser_new_wasm=()=>(_ts_parser_new_wasm=Module._ts_parser_new_wasm=wasmExports.ts_parser_new_wasm)(),_ts_parser_enable_logger_wasm=Module._ts_parser_enable_logger_wasm=(r,e)=>(_ts_parser_enable_logger_wasm=Module._ts_parser_enable_logger_wasm=wasmExports.ts_parser_enable_logger_wasm)(r,e),_ts_parser_parse_wasm=Module._ts_parser_parse_wasm=(r,e,t,n,s)=>(_ts_parser_parse_wasm=Module._ts_parser_parse_wasm=wasmExports.ts_parser_parse_wasm)(r,e,t,n,s),_ts_parser_included_ranges_wasm=Module._ts_parser_included_ranges_wasm=r=>(_ts_parser_included_ranges_wasm=Module._ts_parser_included_ranges_wasm=wasmExports.ts_parser_included_ranges_wasm)(r),_ts_language_type_is_named_wasm=Module._ts_language_type_is_named_wasm=(r,e)=>(_ts_language_type_is_named_wasm=Module._ts_language_type_is_named_wasm=wasmExports.ts_language_type_is_named_wasm)(r,e),_ts_language_type_is_visible_wasm=Module._ts_language_type_is_visible_wasm=(r,e)=>(_ts_language_type_is_visible_wasm=Module._ts_language_type_is_visible_wasm=wasmExports.ts_language_type_is_visible_wasm)(r,e),_ts_tree_root_node_wasm=Module._ts_tree_root_node_wasm=r=>(_ts_tree_root_node_wasm=Module._ts_tree_root_node_wasm=wasmExports.ts_tree_root_node_wasm)(r),_ts_tree_root_node_with_offset_wasm=Module._ts_tree_root_node_with_offset_wasm=r=>(_ts_tree_root_node_with_offset_wasm=Module._ts_tree_root_node_with_offset_wasm=wasmExports.ts_tree_root_node_with_offset_wasm)(r),_ts_tree_edit_wasm=Module._ts_tree_edit_wasm=r=>(_ts_tree_edit_wasm=Module._ts_tree_edit_wasm=wasmExports.ts_tree_edit_wasm)(r),_ts_tree_included_ranges_wasm=Module._ts_tree_included_ranges_wasm=r=>(_ts_tree_included_ranges_wasm=Module._ts_tree_included_ranges_wasm=wasmExports.ts_tree_included_ranges_wasm)(r),_ts_tree_get_changed_ranges_wasm=Module._ts_tree_get_changed_ranges_wasm=(r,e)=>(_ts_tree_get_changed_ranges_wasm=Module._ts_tree_get_changed_ranges_wasm=wasmExports.ts_tree_get_changed_ranges_wasm)(r,e),_ts_tree_cursor_new_wasm=Module._ts_tree_cursor_new_wasm=r=>(_ts_tree_cursor_new_wasm=Module._ts_tree_cursor_new_wasm=wasmExports.ts_tree_cursor_new_wasm)(r),_ts_tree_cursor_delete_wasm=Module._ts_tree_cursor_delete_wasm=r=>(_ts_tree_cursor_delete_wasm=Module._ts_tree_cursor_delete_wasm=wasmExports.ts_tree_cursor_delete_wasm)(r),_ts_tree_cursor_reset_wasm=Module._ts_tree_cursor_reset_wasm=r=>(_ts_tree_cursor_reset_wasm=Module._ts_tree_cursor_reset_wasm=wasmExports.ts_tree_cursor_reset_wasm)(r),_ts_tree_cursor_reset_to_wasm=Module._ts_tree_cursor_reset_to_wasm=(r,e)=>(_ts_tree_cursor_reset_to_wasm=Module._ts_tree_cursor_reset_to_wasm=wasmExports.ts_tree_cursor_reset_to_wasm)(r,e),_ts_tree_cursor_goto_first_child_wasm=Module._ts_tree_cursor_goto_first_child_wasm=r=>(_ts_tree_cursor_goto_first_child_wasm=Module._ts_tree_cursor_goto_first_child_wasm=wasmExports.ts_tree_cursor_goto_first_child_wasm)(r),_ts_tree_cursor_goto_last_child_wasm=Module._ts_tree_cursor_goto_last_child_wasm=r=>(_ts_tree_cursor_goto_last_child_wasm=Module._ts_tree_cursor_goto_last_child_wasm=wasmExports.ts_tree_cursor_goto_last_child_wasm)(r),_ts_tree_cursor_goto_first_child_for_index_wasm=Module._ts_tree_cursor_goto_first_child_for_index_wasm=r=>(_ts_tree_cursor_goto_first_child_for_index_wasm=Module._ts_tree_cursor_goto_first_child_for_index_wasm=wasmExports.ts_tree_cursor_goto_first_child_for_index_wasm)(r),_ts_tree_cursor_goto_first_child_for_position_wasm=Module._ts_tree_cursor_goto_first_child_for_position_wasm=r=>(_ts_tree_cursor_goto_first_child_for_position_wasm=Module._ts_tree_cursor_goto_first_child_for_position_wasm=wasmExports.ts_tree_cursor_goto_first_child_for_position_wasm)(r),_ts_tree_cursor_goto_next_sibling_wasm=Module._ts_tree_cursor_goto_next_sibling_wasm=r=>(_ts_tree_cursor_goto_next_sibling_wasm=Module._ts_tree_cursor_goto_next_sibling_wasm=wasmExports.ts_tree_cursor_goto_next_sibling_wasm)(r),_ts_tree_cursor_goto_previous_sibling_wasm=Module._ts_tree_cursor_goto_previous_sibling_wasm=r=>(_ts_tree_cursor_goto_previous_sibling_wasm=Module._ts_tree_cursor_goto_previous_sibling_wasm=wasmExports.ts_tree_cursor_goto_previous_sibling_wasm)(r),_ts_tree_cursor_goto_descendant_wasm=Module._ts_tree_cursor_goto_descendant_wasm=(r,e)=>(_ts_tree_cursor_goto_descendant_wasm=Module._ts_tree_cursor_goto_descendant_wasm=wasmExports.ts_tree_cursor_goto_descendant_wasm)(r,e),_ts_tree_cursor_goto_parent_wasm=Module._ts_tree_cursor_goto_parent_wasm=r=>(_ts_tree_cursor_goto_parent_wasm=Module._ts_tree_cursor_goto_parent_wasm=wasmExports.ts_tree_cursor_goto_parent_wasm)(r),_ts_tree_cursor_current_node_type_id_wasm=Module._ts_tree_cursor_current_node_type_id_wasm=r=>(_ts_tree_cursor_current_node_type_id_wasm=Module._ts_tree_cursor_current_node_type_id_wasm=wasmExports.ts_tree_cursor_current_node_type_id_wasm)(r),_ts_tree_cursor_current_node_state_id_wasm=Module._ts_tree_cursor_current_node_state_id_wasm=r=>(_ts_tree_cursor_current_node_state_id_wasm=Module._ts_tree_cursor_current_node_state_id_wasm=wasmExports.ts_tree_cursor_current_node_state_id_wasm)(r),_ts_tree_cursor_current_node_is_named_wasm=Module._ts_tree_cursor_current_node_is_named_wasm=r=>(_ts_tree_cursor_current_node_is_named_wasm=Module._ts_tree_cursor_current_node_is_named_wasm=wasmExports.ts_tree_cursor_current_node_is_named_wasm)(r),_ts_tree_cursor_current_node_is_missing_wasm=Module._ts_tree_cursor_current_node_is_missing_wasm=r=>(_ts_tree_cursor_current_node_is_missing_wasm=Module._ts_tree_cursor_current_node_is_missing_wasm=wasmExports.ts_tree_cursor_current_node_is_missing_wasm)(r),_ts_tree_cursor_current_node_id_wasm=Module._ts_tree_cursor_current_node_id_wasm=r=>(_ts_tree_cursor_current_node_id_wasm=Module._ts_tree_cursor_current_node_id_wasm=wasmExports.ts_tree_cursor_current_node_id_wasm)(r),_ts_tree_cursor_start_position_wasm=Module._ts_tree_cursor_start_position_wasm=r=>(_ts_tree_cursor_start_position_wasm=Module._ts_tree_cursor_start_position_wasm=wasmExports.ts_tree_cursor_start_position_wasm)(r),_ts_tree_cursor_end_position_wasm=Module._ts_tree_cursor_end_position_wasm=r=>(_ts_tree_cursor_end_position_wasm=Module._ts_tree_cursor_end_position_wasm=wasmExports.ts_tree_cursor_end_position_wasm)(r),_ts_tree_cursor_start_index_wasm=Module._ts_tree_cursor_start_index_wasm=r=>(_ts_tree_cursor_start_index_wasm=Module._ts_tree_cursor_start_index_wasm=wasmExports.ts_tree_cursor_start_index_wasm)(r),_ts_tree_cursor_end_index_wasm=Module._ts_tree_cursor_end_index_wasm=r=>(_ts_tree_cursor_end_index_wasm=Module._ts_tree_cursor_end_index_wasm=wasmExports.ts_tree_cursor_end_index_wasm)(r),_ts_tree_cursor_current_field_id_wasm=Module._ts_tree_cursor_current_field_id_wasm=r=>(_ts_tree_cursor_current_field_id_wasm=Module._ts_tree_cursor_current_field_id_wasm=wasmExports.ts_tree_cursor_current_field_id_wasm)(r),_ts_tree_cursor_current_depth_wasm=Module._ts_tree_cursor_current_depth_wasm=r=>(_ts_tree_cursor_current_depth_wasm=Module._ts_tree_cursor_current_depth_wasm=wasmExports.ts_tree_cursor_current_depth_wasm)(r),_ts_tree_cursor_current_descendant_index_wasm=Module._ts_tree_cursor_current_descendant_index_wasm=r=>(_ts_tree_cursor_current_descendant_index_wasm=Module._ts_tree_cursor_current_descendant_index_wasm=wasmExports.ts_tree_cursor_current_descendant_index_wasm)(r),_ts_tree_cursor_current_node_wasm=Module._ts_tree_cursor_current_node_wasm=r=>(_ts_tree_cursor_current_node_wasm=Module._ts_tree_cursor_current_node_wasm=wasmExports.ts_tree_cursor_current_node_wasm)(r),_ts_node_symbol_wasm=Module._ts_node_symbol_wasm=r=>(_ts_node_symbol_wasm=Module._ts_node_symbol_wasm=wasmExports.ts_node_symbol_wasm)(r),_ts_node_field_name_for_child_wasm=Module._ts_node_field_name_for_child_wasm=(r,e)=>(_ts_node_field_name_for_child_wasm=Module._ts_node_field_name_for_child_wasm=wasmExports.ts_node_field_name_for_child_wasm)(r,e),_ts_node_children_by_field_id_wasm=Module._ts_node_children_by_field_id_wasm=(r,e)=>(_ts_node_children_by_field_id_wasm=Module._ts_node_children_by_field_id_wasm=wasmExports.ts_node_children_by_field_id_wasm)(r,e),_ts_node_first_child_for_byte_wasm=Module._ts_node_first_child_for_byte_wasm=r=>(_ts_node_first_child_for_byte_wasm=Module._ts_node_first_child_for_byte_wasm=wasmExports.ts_node_first_child_for_byte_wasm)(r),_ts_node_first_named_child_for_byte_wasm=Module._ts_node_first_named_child_for_byte_wasm=r=>(_ts_node_first_named_child_for_byte_wasm=Module._ts_node_first_named_child_for_byte_wasm=wasmExports.ts_node_first_named_child_for_byte_wasm)(r),_ts_node_grammar_symbol_wasm=Module._ts_node_grammar_symbol_wasm=r=>(_ts_node_grammar_symbol_wasm=Module._ts_node_grammar_symbol_wasm=wasmExports.ts_node_grammar_symbol_wasm)(r),_ts_node_child_count_wasm=Module._ts_node_child_count_wasm=r=>(_ts_node_child_count_wasm=Module._ts_node_child_count_wasm=wasmExports.ts_node_child_count_wasm)(r),_ts_node_named_child_count_wasm=Module._ts_node_named_child_count_wasm=r=>(_ts_node_named_child_count_wasm=Module._ts_node_named_child_count_wasm=wasmExports.ts_node_named_child_count_wasm)(r),_ts_node_child_wasm=Module._ts_node_child_wasm=(r,e)=>(_ts_node_child_wasm=Module._ts_node_child_wasm=wasmExports.ts_node_child_wasm)(r,e),_ts_node_named_child_wasm=Module._ts_node_named_child_wasm=(r,e)=>(_ts_node_named_child_wasm=Module._ts_node_named_child_wasm=wasmExports.ts_node_named_child_wasm)(r,e),_ts_node_child_by_field_id_wasm=Module._ts_node_child_by_field_id_wasm=(r,e)=>(_ts_node_child_by_field_id_wasm=Module._ts_node_child_by_field_id_wasm=wasmExports.ts_node_child_by_field_id_wasm)(r,e),_ts_node_next_sibling_wasm=Module._ts_node_next_sibling_wasm=r=>(_ts_node_next_sibling_wasm=Module._ts_node_next_sibling_wasm=wasmExports.ts_node_next_sibling_wasm)(r),_ts_node_prev_sibling_wasm=Module._ts_node_prev_sibling_wasm=r=>(_ts_node_prev_sibling_wasm=Module._ts_node_prev_sibling_wasm=wasmExports.ts_node_prev_sibling_wasm)(r),_ts_node_next_named_sibling_wasm=Module._ts_node_next_named_sibling_wasm=r=>(_ts_node_next_named_sibling_wasm=Module._ts_node_next_named_sibling_wasm=wasmExports.ts_node_next_named_sibling_wasm)(r),_ts_node_prev_named_sibling_wasm=Module._ts_node_prev_named_sibling_wasm=r=>(_ts_node_prev_named_sibling_wasm=Module._ts_node_prev_named_sibling_wasm=wasmExports.ts_node_prev_named_sibling_wasm)(r),_ts_node_descendant_count_wasm=Module._ts_node_descendant_count_wasm=r=>(_ts_node_descendant_count_wasm=Module._ts_node_descendant_count_wasm=wasmExports.ts_node_descendant_count_wasm)(r),_ts_node_parent_wasm=Module._ts_node_parent_wasm=r=>(_ts_node_parent_wasm=Module._ts_node_parent_wasm=wasmExports.ts_node_parent_wasm)(r),_ts_node_descendant_for_index_wasm=Module._ts_node_descendant_for_index_wasm=r=>(_ts_node_descendant_for_index_wasm=Module._ts_node_descendant_for_index_wasm=wasmExports.ts_node_descendant_for_index_wasm)(r),_ts_node_named_descendant_for_index_wasm=Module._ts_node_named_descendant_for_index_wasm=r=>(_ts_node_named_descendant_for_index_wasm=Module._ts_node_named_descendant_for_index_wasm=wasmExports.ts_node_named_descendant_for_index_wasm)(r),_ts_node_descendant_for_position_wasm=Module._ts_node_descendant_for_position_wasm=r=>(_ts_node_descendant_for_position_wasm=Module._ts_node_descendant_for_position_wasm=wasmExports.ts_node_descendant_for_position_wasm)(r),_ts_node_named_descendant_for_position_wasm=Module._ts_node_named_descendant_for_position_wasm=r=>(_ts_node_named_descendant_for_position_wasm=Module._ts_node_named_descendant_for_position_wasm=wasmExports.ts_node_named_descendant_for_position_wasm)(r),_ts_node_start_point_wasm=Module._ts_node_start_point_wasm=r=>(_ts_node_start_point_wasm=Module._ts_node_start_point_wasm=wasmExports.ts_node_start_point_wasm)(r),_ts_node_end_point_wasm=Module._ts_node_end_point_wasm=r=>(_ts_node_end_point_wasm=Module._ts_node_end_point_wasm=wasmExports.ts_node_end_point_wasm)(r),_ts_node_start_index_wasm=Module._ts_node_start_index_wasm=r=>(_ts_node_start_index_wasm=Module._ts_node_start_index_wasm=wasmExports.ts_node_start_index_wasm)(r),_ts_node_end_index_wasm=Module._ts_node_end_index_wasm=r=>(_ts_node_end_index_wasm=Module._ts_node_end_index_wasm=wasmExports.ts_node_end_index_wasm)(r),_ts_node_to_string_wasm=Module._ts_node_to_string_wasm=r=>(_ts_node_to_string_wasm=Module._ts_node_to_string_wasm=wasmExports.ts_node_to_string_wasm)(r),_ts_node_children_wasm=Module._ts_node_children_wasm=r=>(_ts_node_children_wasm=Module._ts_node_children_wasm=wasmExports.ts_node_children_wasm)(r),_ts_node_named_children_wasm=Module._ts_node_named_children_wasm=r=>(_ts_node_named_children_wasm=Module._ts_node_named_children_wasm=wasmExports.ts_node_named_children_wasm)(r),_ts_node_descendants_of_type_wasm=Module._ts_node_descendants_of_type_wasm=(r,e,t,n,s,o,a)=>(_ts_node_descendants_of_type_wasm=Module._ts_node_descendants_of_type_wasm=wasmExports.ts_node_descendants_of_type_wasm)(r,e,t,n,s,o,a),_ts_node_is_named_wasm=Module._ts_node_is_named_wasm=r=>(_ts_node_is_named_wasm=Module._ts_node_is_named_wasm=wasmExports.ts_node_is_named_wasm)(r),_ts_node_has_changes_wasm=Module._ts_node_has_changes_wasm=r=>(_ts_node_has_changes_wasm=Module._ts_node_has_changes_wasm=wasmExports.ts_node_has_changes_wasm)(r),_ts_node_has_error_wasm=Module._ts_node_has_error_wasm=r=>(_ts_node_has_error_wasm=Module._ts_node_has_error_wasm=wasmExports.ts_node_has_error_wasm)(r),_ts_node_is_error_wasm=Module._ts_node_is_error_wasm=r=>(_ts_node_is_error_wasm=Module._ts_node_is_error_wasm=wasmExports.ts_node_is_error_wasm)(r),_ts_node_is_missing_wasm=Module._ts_node_is_missing_wasm=r=>(_ts_node_is_missing_wasm=Module._ts_node_is_missing_wasm=wasmExports.ts_node_is_missing_wasm)(r),_ts_node_is_extra_wasm=Module._ts_node_is_extra_wasm=r=>(_ts_node_is_extra_wasm=Module._ts_node_is_extra_wasm=wasmExports.ts_node_is_extra_wasm)(r),_ts_node_parse_state_wasm=Module._ts_node_parse_state_wasm=r=>(_ts_node_parse_state_wasm=Module._ts_node_parse_state_wasm=wasmExports.ts_node_parse_state_wasm)(r),_ts_node_next_parse_state_wasm=Module._ts_node_next_parse_state_wasm=r=>(_ts_node_next_parse_state_wasm=Module._ts_node_next_parse_state_wasm=wasmExports.ts_node_next_parse_state_wasm)(r),_ts_query_matches_wasm=Module._ts_query_matches_wasm=(r,e,t,n,s,o,a,l,c,u,d)=>(_ts_query_matches_wasm=Module._ts_query_matches_wasm=wasmExports.ts_query_matches_wasm)(r,e,t,n,s,o,a,l,c,u,d),_ts_query_captures_wasm=Module._ts_query_captures_wasm=(r,e,t,n,s,o,a,l,c,u,d)=>(_ts_query_captures_wasm=Module._ts_query_captures_wasm=wasmExports.ts_query_captures_wasm)(r,e,t,n,s,o,a,l,c,u,d),_iswalpha=Module._iswalpha=r=>(_iswalpha=Module._iswalpha=wasmExports.iswalpha)(r),_iswblank=Module._iswblank=r=>(_iswblank=Module._iswblank=wasmExports.iswblank)(r),_iswdigit=Module._iswdigit=r=>(_iswdigit=Module._iswdigit=wasmExports.iswdigit)(r),_iswlower=Module._iswlower=r=>(_iswlower=Module._iswlower=wasmExports.iswlower)(r),_iswupper=Module._iswupper=r=>(_iswupper=Module._iswupper=wasmExports.iswupper)(r),_iswxdigit=Module._iswxdigit=r=>(_iswxdigit=Module._iswxdigit=wasmExports.iswxdigit)(r),_memchr=Module._memchr=(r,e,t)=>(_memchr=Module._memchr=wasmExports.memchr)(r,e,t),_strlen=Module._strlen=r=>(_strlen=Module._strlen=wasmExports.strlen)(r),_strcmp=Module._strcmp=(r,e)=>(_strcmp=Module._strcmp=wasmExports.strcmp)(r,e),_strncat=Module._strncat=(r,e,t)=>(_strncat=Module._strncat=wasmExports.strncat)(r,e,t),_strncpy=Module._strncpy=(r,e,t)=>(_strncpy=Module._strncpy=wasmExports.strncpy)(r,e,t),_towlower=Module._towlower=r=>(_towlower=Module._towlower=wasmExports.towlower)(r),_towupper=Module._towupper=r=>(_towupper=Module._towupper=wasmExports.towupper)(r),_setThrew=(r,e)=>(_setThrew=wasmExports.setThrew)(r,e),__emscripten_stack_restore=r=>(__emscripten_stack_restore=wasmExports._emscripten_stack_restore)(r),__emscripten_stack_alloc=r=>(__emscripten_stack_alloc=wasmExports._emscripten_stack_alloc)(r),_emscripten_stack_get_current=()=>(_emscripten_stack_get_current=wasmExports.emscripten_stack_get_current)(),dynCall_jiji=Module.dynCall_jiji=(r,e,t,n,s)=>(dynCall_jiji=Module.dynCall_jiji=wasmExports.dynCall_jiji)(r,e,t,n,s),_orig$ts_parser_timeout_micros=Module._orig$ts_parser_timeout_micros=r=>(_orig$ts_parser_timeout_micros=Module._orig$ts_parser_timeout_micros=wasmExports.orig$ts_parser_timeout_micros)(r),_orig$ts_parser_set_timeout_micros=Module._orig$ts_parser_set_timeout_micros=(r,e)=>(_orig$ts_parser_set_timeout_micros=Module._orig$ts_parser_set_timeout_micros=wasmExports.orig$ts_parser_set_timeout_micros)(r,e);Module.AsciiToString=AsciiToString,Module.stringToUTF16=stringToUTF16;var calledRun;dependenciesFulfilled=function r(){calledRun||run(),calledRun||(dependenciesFulfilled=r)};function callMain(r=[]){var e=resolveGlobalSymbol("main").sym;if(e){r.unshift(thisProgram);var t=r.length,n=stackAlloc((t+1)*4),s=n;r.forEach(a=>{LE_HEAP_STORE_U32((s>>2)*4,stringToUTF8OnStack(a)),s+=4}),LE_HEAP_STORE_U32((s>>2)*4,0);try{var o=e(t,n);return exitJS(o,!0),o}catch(a){return handleException(a)}}}function run(r=arguments_){if(runDependencies>0||(preRun(),runDependencies>0))return;function e(){calledRun||(calledRun=!0,Module.calledRun=!0,!ABORT&&(initRuntime(),preMain(),Module.onRuntimeInitialized?.(),shouldRunNow&&callMain(r),postRun()))}Module.setStatus?(Module.setStatus("Running..."),setTimeout(function(){setTimeout(function(){Module.setStatus("")},1),e()},1)):e()}if(Module.preInit)for(typeof Module.preInit=="function"&&(Module.preInit=[Module.preInit]);Module.preInit.length>0;)Module.preInit.pop()();var shouldRunNow=!0;Module.noInitialRun&&(shouldRunNow=!1),run();let C=Module,INTERNAL={},SIZE_OF_INT=4,SIZE_OF_CURSOR=4*SIZE_OF_INT,SIZE_OF_NODE=5*SIZE_OF_INT,SIZE_OF_POINT=2*SIZE_OF_INT,SIZE_OF_RANGE=2*SIZE_OF_INT+2*SIZE_OF_POINT,ZERO_POINT={row:0,column:0},QUERY_WORD_REGEX=/[\w-.]*/g,PREDICATE_STEP_TYPE_CAPTURE=1,PREDICATE_STEP_TYPE_STRING=2,LANGUAGE_FUNCTION_REGEX=/^_?tree_sitter_\w+/,VERSION,MIN_COMPATIBLE_VERSION,TRANSFER_BUFFER,currentParseCallback,currentLogCallback;class ParserImpl{static init(){TRANSFER_BUFFER=C._ts_init(),VERSION=getValue(TRANSFER_BUFFER,"i32"),MIN_COMPATIBLE_VERSION=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32")}initialize(){C._ts_parser_new_wasm(),this[0]=getValue(TRANSFER_BUFFER,"i32"),this[1]=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32")}delete(){C._ts_parser_delete(this[0]),C._free(this[1]),this[0]=0,this[1]=0}setLanguage(e){let t;if(!e)t=0,e=null;else if(e.constructor===Language){t=e[0];let n=C._ts_language_version(t);if(n<MIN_COMPATIBLE_VERSION||VERSION<n)throw new Error(`Incompatible language version ${n}. Compatibility range ${MIN_COMPATIBLE_VERSION} through ${VERSION}.`)}else throw new Error("Argument must be a Language");return this.language=e,C._ts_parser_set_language(this[0],t),this}getLanguage(){return this.language}parse(e,t,n){if(typeof e=="string")currentParseCallback=(c,u)=>e.slice(c);else if(typeof e=="function")currentParseCallback=e;else throw new Error("Argument must be a string or a function");this.logCallback?(currentLogCallback=this.logCallback,C._ts_parser_enable_logger_wasm(this[0],1)):(currentLogCallback=null,C._ts_parser_enable_logger_wasm(this[0],0));let s=0,o=0;if(n?.includedRanges){s=n.includedRanges.length,o=C._calloc(s,SIZE_OF_RANGE);let c=o;for(let u=0;u<s;u++)marshalRange(c,n.includedRanges[u]),c+=SIZE_OF_RANGE}let a=C._ts_parser_parse_wasm(this[0],this[1],t?t[0]:0,o,s);if(!a)throw currentParseCallback=null,currentLogCallback=null,new Error("Parsing failed");let l=new Tree(INTERNAL,a,this.language,currentParseCallback);return currentParseCallback=null,currentLogCallback=null,l}reset(){C._ts_parser_reset(this[0])}getIncludedRanges(){C._ts_parser_included_ranges_wasm(this[0]);let e=getValue(TRANSFER_BUFFER,"i32"),t=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32"),n=new Array(e);if(e>0){let s=t;for(let o=0;o<e;o++)n[o]=unmarshalRange(s),s+=SIZE_OF_RANGE;C._free(t)}return n}getTimeoutMicros(){return C._ts_parser_timeout_micros(this[0])}setTimeoutMicros(e){C._ts_parser_set_timeout_micros(this[0],e)}setLogger(e){if(!e)e=null;else if(typeof e!="function")throw new Error("Logger callback must be a function");return this.logCallback=e,this}getLogger(){return this.logCallback}}class Tree{constructor(e,t,n,s){assertInternal(e),this[0]=t,this.language=n,this.textCallback=s}copy(){let e=C._ts_tree_copy(this[0]);return new Tree(INTERNAL,e,this.language,this.textCallback)}delete(){C._ts_tree_delete(this[0]),this[0]=0}edit(e){marshalEdit(e),C._ts_tree_edit_wasm(this[0])}get rootNode(){return C._ts_tree_root_node_wasm(this[0]),unmarshalNode(this)}rootNodeWithOffset(e,t){let n=TRANSFER_BUFFER+SIZE_OF_NODE;return setValue(n,e,"i32"),marshalPoint(n+SIZE_OF_INT,t),C._ts_tree_root_node_with_offset_wasm(this[0]),unmarshalNode(this)}getLanguage(){return this.language}walk(){return this.rootNode.walk()}getChangedRanges(e){if(e.constructor!==Tree)throw new TypeError("Argument must be a Tree");C._ts_tree_get_changed_ranges_wasm(this[0],e[0]);let t=getValue(TRANSFER_BUFFER,"i32"),n=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32"),s=new Array(t);if(t>0){let o=n;for(let a=0;a<t;a++)s[a]=unmarshalRange(o),o+=SIZE_OF_RANGE;C._free(n)}return s}getIncludedRanges(){C._ts_tree_included_ranges_wasm(this[0]);let e=getValue(TRANSFER_BUFFER,"i32"),t=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32"),n=new Array(e);if(e>0){let s=t;for(let o=0;o<e;o++)n[o]=unmarshalRange(s),s+=SIZE_OF_RANGE;C._free(t)}return n}}class Node{constructor(e,t){assertInternal(e),this.tree=t}get typeId(){return marshalNode(this),C._ts_node_symbol_wasm(this.tree[0])}get grammarId(){return marshalNode(this),C._ts_node_grammar_symbol_wasm(this.tree[0])}get type(){return this.tree.language.types[this.typeId]||"ERROR"}get grammarType(){return this.tree.language.types[this.grammarId]||"ERROR"}get endPosition(){return marshalNode(this),C._ts_node_end_point_wasm(this.tree[0]),unmarshalPoint(TRANSFER_BUFFER)}get endIndex(){return marshalNode(this),C._ts_node_end_index_wasm(this.tree[0])}get text(){return getText(this.tree,this.startIndex,this.endIndex)}get parseState(){return marshalNode(this),C._ts_node_parse_state_wasm(this.tree[0])}get nextParseState(){return marshalNode(this),C._ts_node_next_parse_state_wasm(this.tree[0])}get isNamed(){return marshalNode(this),C._ts_node_is_named_wasm(this.tree[0])===1}get hasError(){return marshalNode(this),C._ts_node_has_error_wasm(this.tree[0])===1}get hasChanges(){return marshalNode(this),C._ts_node_has_changes_wasm(this.tree[0])===1}get isError(){return marshalNode(this),C._ts_node_is_error_wasm(this.tree[0])===1}get isMissing(){return marshalNode(this),C._ts_node_is_missing_wasm(this.tree[0])===1}get isExtra(){return marshalNode(this),C._ts_node_is_extra_wasm(this.tree[0])===1}equals(e){return this.id===e.id}child(e){return marshalNode(this),C._ts_node_child_wasm(this.tree[0],e),unmarshalNode(this.tree)}namedChild(e){return marshalNode(this),C._ts_node_named_child_wasm(this.tree[0],e),unmarshalNode(this.tree)}childForFieldId(e){return marshalNode(this),C._ts_node_child_by_field_id_wasm(this.tree[0],e),unmarshalNode(this.tree)}childForFieldName(e){let t=this.tree.language.fields.indexOf(e);return t!==-1?this.childForFieldId(t):null}fieldNameForChild(e){marshalNode(this);let t=C._ts_node_field_name_for_child_wasm(this.tree[0],e);return t?AsciiToString(t):null}childrenForFieldName(e){let t=this.tree.language.fields.indexOf(e);return t!==-1&&t!==0?this.childrenForFieldId(t):[]}childrenForFieldId(e){marshalNode(this),C._ts_node_children_by_field_id_wasm(this.tree[0],e);let t=getValue(TRANSFER_BUFFER,"i32"),n=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32"),s=new Array(t);if(t>0){let o=n;for(let a=0;a<t;a++)s[a]=unmarshalNode(this.tree,o),o+=SIZE_OF_NODE;C._free(n)}return s}firstChildForIndex(e){marshalNode(this);let t=TRANSFER_BUFFER+SIZE_OF_NODE;return setValue(t,e,"i32"),C._ts_node_first_child_for_byte_wasm(this.tree[0]),unmarshalNode(this.tree)}firstNamedChildForIndex(e){marshalNode(this);let t=TRANSFER_BUFFER+SIZE_OF_NODE;return setValue(t,e,"i32"),C._ts_node_first_named_child_for_byte_wasm(this.tree[0]),unmarshalNode(this.tree)}get childCount(){return marshalNode(this),C._ts_node_child_count_wasm(this.tree[0])}get namedChildCount(){return marshalNode(this),C._ts_node_named_child_count_wasm(this.tree[0])}get firstChild(){return this.child(0)}get firstNamedChild(){return this.namedChild(0)}get lastChild(){return this.child(this.childCount-1)}get lastNamedChild(){return this.namedChild(this.namedChildCount-1)}get children(){if(!this._children){marshalNode(this),C._ts_node_children_wasm(this.tree[0]);let e=getValue(TRANSFER_BUFFER,"i32"),t=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32");if(this._children=new Array(e),e>0){let n=t;for(let s=0;s<e;s++)this._children[s]=unmarshalNode(this.tree,n),n+=SIZE_OF_NODE;C._free(t)}}return this._children}get namedChildren(){if(!this._namedChildren){marshalNode(this),C._ts_node_named_children_wasm(this.tree[0]);let e=getValue(TRANSFER_BUFFER,"i32"),t=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32");if(this._namedChildren=new Array(e),e>0){let n=t;for(let s=0;s<e;s++)this._namedChildren[s]=unmarshalNode(this.tree,n),n+=SIZE_OF_NODE;C._free(t)}}return this._namedChildren}descendantsOfType(e,t,n){Array.isArray(e)||(e=[e]),t||(t=ZERO_POINT),n||(n=ZERO_POINT);let s=[],o=this.tree.language.types;for(let d=0,h=o.length;d<h;d++)e.includes(o[d])&&s.push(d);let a=C._malloc(SIZE_OF_INT*s.length);for(let d=0,h=s.length;d<h;d++)setValue(a+d*SIZE_OF_INT,s[d],"i32");marshalNode(this),C._ts_node_descendants_of_type_wasm(this.tree[0],a,s.length,t.row,t.column,n.row,n.column);let l=getValue(TRANSFER_BUFFER,"i32"),c=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32"),u=new Array(l);if(l>0){let d=c;for(let h=0;h<l;h++)u[h]=unmarshalNode(this.tree,d),d+=SIZE_OF_NODE}return C._free(c),C._free(a),u}get nextSibling(){return marshalNode(this),C._ts_node_next_sibling_wasm(this.tree[0]),unmarshalNode(this.tree)}get previousSibling(){return marshalNode(this),C._ts_node_prev_sibling_wasm(this.tree[0]),unmarshalNode(this.tree)}get nextNamedSibling(){return marshalNode(this),C._ts_node_next_named_sibling_wasm(this.tree[0]),unmarshalNode(this.tree)}get previousNamedSibling(){return marshalNode(this),C._ts_node_prev_named_sibling_wasm(this.tree[0]),unmarshalNode(this.tree)}get descendantCount(){return marshalNode(this),C._ts_node_descendant_count_wasm(this.tree[0])}get parent(){return marshalNode(this),C._ts_node_parent_wasm(this.tree[0]),unmarshalNode(this.tree)}descendantForIndex(e,t=e){if(typeof e!="number"||typeof t!="number")throw new Error("Arguments must be numbers");marshalNode(this);let n=TRANSFER_BUFFER+SIZE_OF_NODE;return setValue(n,e,"i32"),setValue(n+SIZE_OF_INT,t,"i32"),C._ts_node_descendant_for_index_wasm(this.tree[0]),unmarshalNode(this.tree)}namedDescendantForIndex(e,t=e){if(typeof e!="number"||typeof t!="number")throw new Error("Arguments must be numbers");marshalNode(this);let n=TRANSFER_BUFFER+SIZE_OF_NODE;return setValue(n,e,"i32"),setValue(n+SIZE_OF_INT,t,"i32"),C._ts_node_named_descendant_for_index_wasm(this.tree[0]),unmarshalNode(this.tree)}descendantForPosition(e,t=e){if(!isPoint(e)||!isPoint(t))throw new Error("Arguments must be {row, column} objects");marshalNode(this);let n=TRANSFER_BUFFER+SIZE_OF_NODE;return marshalPoint(n,e),marshalPoint(n+SIZE_OF_POINT,t),C._ts_node_descendant_for_position_wasm(this.tree[0]),unmarshalNode(this.tree)}namedDescendantForPosition(e,t=e){if(!isPoint(e)||!isPoint(t))throw new Error("Arguments must be {row, column} objects");marshalNode(this);let n=TRANSFER_BUFFER+SIZE_OF_NODE;return marshalPoint(n,e),marshalPoint(n+SIZE_OF_POINT,t),C._ts_node_named_descendant_for_position_wasm(this.tree[0]),unmarshalNode(this.tree)}walk(){return marshalNode(this),C._ts_tree_cursor_new_wasm(this.tree[0]),new TreeCursor(INTERNAL,this.tree)}toString(){marshalNode(this);let e=C._ts_node_to_string_wasm(this.tree[0]),t=AsciiToString(e);return C._free(e),t}}class TreeCursor{constructor(e,t){assertInternal(e),this.tree=t,unmarshalTreeCursor(this)}delete(){marshalTreeCursor(this),C._ts_tree_cursor_delete_wasm(this.tree[0]),this[0]=this[1]=this[2]=0}reset(e){marshalNode(e),marshalTreeCursor(this,TRANSFER_BUFFER+SIZE_OF_NODE),C._ts_tree_cursor_reset_wasm(this.tree[0]),unmarshalTreeCursor(this)}resetTo(e){marshalTreeCursor(this,TRANSFER_BUFFER),marshalTreeCursor(e,TRANSFER_BUFFER+SIZE_OF_CURSOR),C._ts_tree_cursor_reset_to_wasm(this.tree[0],e.tree[0]),unmarshalTreeCursor(this)}get nodeType(){return this.tree.language.types[this.nodeTypeId]||"ERROR"}get nodeTypeId(){return marshalTreeCursor(this),C._ts_tree_cursor_current_node_type_id_wasm(this.tree[0])}get nodeStateId(){return marshalTreeCursor(this),C._ts_tree_cursor_current_node_state_id_wasm(this.tree[0])}get nodeId(){return marshalTreeCursor(this),C._ts_tree_cursor_current_node_id_wasm(this.tree[0])}get nodeIsNamed(){return marshalTreeCursor(this),C._ts_tree_cursor_current_node_is_named_wasm(this.tree[0])===1}get nodeIsMissing(){return marshalTreeCursor(this),C._ts_tree_cursor_current_node_is_missing_wasm(this.tree[0])===1}get nodeText(){marshalTreeCursor(this);let e=C._ts_tree_cursor_start_index_wasm(this.tree[0]),t=C._ts_tree_cursor_end_index_wasm(this.tree[0]);return getText(this.tree,e,t)}get startPosition(){return marshalTreeCursor(this),C._ts_tree_cursor_start_position_wasm(this.tree[0]),unmarshalPoint(TRANSFER_BUFFER)}get endPosition(){return marshalTreeCursor(this),C._ts_tree_cursor_end_position_wasm(this.tree[0]),unmarshalPoint(TRANSFER_BUFFER)}get startIndex(){return marshalTreeCursor(this),C._ts_tree_cursor_start_index_wasm(this.tree[0])}get endIndex(){return marshalTreeCursor(this),C._ts_tree_cursor_end_index_wasm(this.tree[0])}get currentNode(){return marshalTreeCursor(this),C._ts_tree_cursor_current_node_wasm(this.tree[0]),unmarshalNode(this.tree)}get currentFieldId(){return marshalTreeCursor(this),C._ts_tree_cursor_current_field_id_wasm(this.tree[0])}get currentFieldName(){return this.tree.language.fields[this.currentFieldId]}get currentDepth(){return marshalTreeCursor(this),C._ts_tree_cursor_current_depth_wasm(this.tree[0])}get currentDescendantIndex(){return marshalTreeCursor(this),C._ts_tree_cursor_current_descendant_index_wasm(this.tree[0])}gotoFirstChild(){marshalTreeCursor(this);let e=C._ts_tree_cursor_goto_first_child_wasm(this.tree[0]);return unmarshalTreeCursor(this),e===1}gotoLastChild(){marshalTreeCursor(this);let e=C._ts_tree_cursor_goto_last_child_wasm(this.tree[0]);return unmarshalTreeCursor(this),e===1}gotoFirstChildForIndex(e){marshalTreeCursor(this),setValue(TRANSFER_BUFFER+SIZE_OF_CURSOR,e,"i32");let t=C._ts_tree_cursor_goto_first_child_for_index_wasm(this.tree[0]);return unmarshalTreeCursor(this),t===1}gotoFirstChildForPosition(e){marshalTreeCursor(this),marshalPoint(TRANSFER_BUFFER+SIZE_OF_CURSOR,e);let t=C._ts_tree_cursor_goto_first_child_for_position_wasm(this.tree[0]);return unmarshalTreeCursor(this),t===1}gotoNextSibling(){marshalTreeCursor(this);let e=C._ts_tree_cursor_goto_next_sibling_wasm(this.tree[0]);return unmarshalTreeCursor(this),e===1}gotoPreviousSibling(){marshalTreeCursor(this);let e=C._ts_tree_cursor_goto_previous_sibling_wasm(this.tree[0]);return unmarshalTreeCursor(this),e===1}gotoDescendant(e){marshalTreeCursor(this),C._ts_tree_cursor_goto_descendant_wasm(this.tree[0],e),unmarshalTreeCursor(this)}gotoParent(){marshalTreeCursor(this);let e=C._ts_tree_cursor_goto_parent_wasm(this.tree[0]);return unmarshalTreeCursor(this),e===1}}class Language{constructor(e,t){assertInternal(e),this[0]=t,this.types=new Array(C._ts_language_symbol_count(this[0]));for(let n=0,s=this.types.length;n<s;n++)C._ts_language_symbol_type(this[0],n)<2&&(this.types[n]=UTF8ToString(C._ts_language_symbol_name(this[0],n)));this.fields=new Array(C._ts_language_field_count(this[0])+1);for(let n=0,s=this.fields.length;n<s;n++){let o=C._ts_language_field_name_for_id(this[0],n);o!==0?this.fields[n]=UTF8ToString(o):this.fields[n]=null}}get version(){return C._ts_language_version(this[0])}get fieldCount(){return this.fields.length-1}get stateCount(){return C._ts_language_state_count(this[0])}fieldIdForName(e){let t=this.fields.indexOf(e);return t!==-1?t:null}fieldNameForId(e){return this.fields[e]||null}idForNodeType(e,t){let n=lengthBytesUTF8(e),s=C._malloc(n+1);stringToUTF8(e,s,n+1);let o=C._ts_language_symbol_for_name(this[0],s,n,t);return C._free(s),o||null}get nodeTypeCount(){return C._ts_language_symbol_count(this[0])}nodeTypeForId(e){let t=C._ts_language_symbol_name(this[0],e);return t?UTF8ToString(t):null}nodeTypeIsNamed(e){return!!C._ts_language_type_is_named_wasm(this[0],e)}nodeTypeIsVisible(e){return!!C._ts_language_type_is_visible_wasm(this[0],e)}nextState(e,t){return C._ts_language_next_state(this[0],e,t)}lookaheadIterator(e){let t=C._ts_lookahead_iterator_new(this[0],e);return t?new LookaheadIterable(INTERNAL,t,this):null}query(e){let t=lengthBytesUTF8(e),n=C._malloc(t+1);stringToUTF8(e,n,t+1);let s=C._ts_query_new(this[0],n,t,TRANSFER_BUFFER,TRANSFER_BUFFER+SIZE_OF_INT);if(!s){let w=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32"),m=getValue(TRANSFER_BUFFER,"i32"),_=UTF8ToString(n,m).length,b=e.substr(_,100).split(`
3
+ import{a as Ae,b as Cz,c as IP,d as Tz,e as U,f as Ez,g as Ze,h as Tt,i as kz,j as xz,k as sr,l as oe,m as le,n as yr,o as Ut,p as OP,q as DP,r as At,s as Jn,t as de,u as tr,v as Az,w as LP,x as Rz,y as Pz}from"./chunk-TZIDSCTF.js";import{d as Dz,e as Lz,g as Bz,h as jz,i as zz,j as NP,m as qz}from"./chunk-ROETRE5J.js";import{d as Wz,k as FP,n as Gz,p as Vz}from"./chunk-INAZKGGR.js";import{b as Ihe,i as Nz,j as Fz,k as $z,o as im,p as Uz,r as Hz}from"./chunk-DCQKJTAX.js";import{a as Gt}from"./chunk-LSDMWVW6.js";import{a as uv,b as Iz,d as BP,e as fv}from"./chunk-MTMU7JYZ.js";import{a as Kz,b as Yz,c as om}from"./chunk-TXMXCR7D.js";import{a as $P}from"./chunk-YULUB745.js";import{a as Jz,b as Xz,c as Zz,d as UP,e as Qz,f as HP}from"./chunk-VYTYYCBR.js";import{a as Ej,b as za,c as kj}from"./chunk-TISQNFB5.js";import{a as ji,b as PP,c as Bd,t as MP}from"./chunk-34DXSYJZ.js";import{a as hv,b as am}from"./chunk-FWIVFCKF.js";import{b as Mz,g as dv,j as sm,k as Oz,l as Rs}from"./chunk-QKYGQLWC.js";import{a as rt,b as jd,d as qd,e as Wd}from"./chunk-FRL6KOLY.js";import{b as $o,d as fz,f as pz,i as ct,j as mz,k as gz,l as yz,m as wz,n as _z,o as bz,p as vz,q as Sz}from"./chunk-VWWEEU4V.js";import{b as zd}from"./chunk-RNKDFE2S.js";import{a as hz}from"./chunk-Q2I3ARPJ.js";import{a as cv}from"./chunk-6JHTLNKH.js";import{a as xj}from"./chunk-QHA3ZBRO.js";import{$ as xP,U as CP,V as sz,W as az,Z as Ic,_ as nm,b as bP,ba as AP,c as vP,d as X2,e as SP,ea as av,f as Z2,ga as lv,pa as cn,qa as RP,ta as Hd}from"./chunk-T4JNNZRX.js";import{a as No,c as TP}from"./chunk-4F4DA5UI.js";import{e as EP,f as kP}from"./chunk-DC7LAFZZ.js";import{m as Ud,p as iz,r as oz,v as rm}from"./chunk-S7G6QPEP.js";import{a as Vj,b as Yr,c as Yn,d as Kj,f as Yj}from"./chunk-4J6DC24J.js";import{a as Q2,g as ez,h as tz,k as $d,l as rz,m as nz}from"./chunk-SDTWBD62.js";import{$a as Xb,$b as P2,$c as fP,Ab as v2,Ac as uP,B as t2,Bb as S2,Bc as dP,Cb as C2,Cc as Lo,Db as T2,Eb as E2,Ec as hP,F as Ld,G as r2,Gb as tP,Ha as i2,Ic as B2,Jb as k2,Mc as j2,Ob as x2,Oc as z2,Qc as Fd,Rc as q2,Sb as Nd,Sc as W2,Tb as A2,Ub as R2,Va as o2,Vc as nv,Yb as Qb,Za as a2,_a as Ga,_b as rP,aa as n2,ab as l2,ac as Ac,ad as Mc,bb as c2,bc as nP,bd as G2,cb as kn,cd as sv,d as Bj,da as Wa,dc as M2,ec as sP,ed as pP,f as Do,fc as I2,fd as mP,g as Vb,ga as Zp,gb as QR,gc as iP,gd as gP,h as Kn,ha as Jb,hb as u2,hc as oP,i as qa,ib as d2,ic as aP,id as yP,jb as h2,k as Jj,kb as eP,kd as V2,l as Xj,lb as f2,m as Zj,mb as p2,mc as O2,nb as m2,nc as D2,ob as g2,oc as L2,od as K2,p as kc,pb as y2,pd as Y2,q as Xp,qb as w2,qd as J2,r as Qj,rb as _2,rc as lP,rd as wP,s as e2,sb as b2,sc as ev,t as xc,tc as tv,uc as F2,ud as _P,vb as Zb,vc as $2,vd as iv,wd as ov,xc as cP,ya as ZR,yc as tm,za as s2,zc as U2}from"./chunk-B3NVKOSU.js";import{b as Bi,h as Dr,k as N2,l as Rc,m as Lr,n as Pc,o as Qp,s as ti,t as em,w as rv}from"./chunk-32PTAACU.js";import{a as H2}from"./chunk-32T6RWWT.js";import{b as jj,c as Phe,d as Mhe,e as zj,f as qj,g as Qs,i as ei,j as Wj,k as JR,o as Gj,p as R,q as En,r as Kb,s as Yb}from"./chunk-6B5BDE7S.js";import{a as dz}from"./chunk-RJX7DK4Y.js";import{a as cz,b as Fo,c as uz}from"./chunk-ESSYHTAZ.js";import{b as lz}from"./chunk-3YLXGE6T.js";import{b as Xe,c as As,e as Dd}from"./chunk-EQEQPZLQ.js";import{A as Id,D as Ij,E as Oj,G as Zs,H as Od,J as Ec,K as Dj,N as VR,O as KR,P as fe,U as $j,V as Uj,X as Hj,_ as YR,aa as F,b as Ot,c as Wb,d as ne,e as Oo,l as Aj,q as Rj,s as Pj,v as Mj,w as ln}from"./chunk-VLYRNOD3.js";import{a as XR}from"./chunk-G7R2XEEF.js";import{g as Gb,h as Lj,l as Nj,n as Fj}from"./chunk-FWDMPRKU.js";import{a as __matilda_dirname,b as g}from"./chunk-GZPNIYVZ.js";import{a as Se,c as Ahe,d as N,e as Rhe,f as Ge}from"./chunk-OWGSC52X.js";var A3=N((pet,x3)=>{"use strict";g();x3.exports=function(e){return e.map(function(t){return t===""?"''":t&&typeof t=="object"?t.op.replace(/(.)/g,"\\$1"):/["\s\\]/.test(t)&&!/'/.test(t)?"'"+t.replace(/(['])/g,"\\$1")+"'":/["'\s]/.test(t)?'"'+t.replace(/(["\\$`!])/g,"\\$1")+'"':String(t).replace(/([A-Za-z]:)?([#!"$&'()*,:;<=>?@[\\\]^`{|}])/g,"$1\\$2")}).join(" ")}});var L3=N((get,D3)=>{"use strict";g();var O3="(?:"+["\\|\\|","\\&\\&",";;","\\|\\&","\\<\\(","\\<\\<\\<",">>",">\\&","<\\&","[&;()|<>]"].join("|")+")",R3=new RegExp("^"+O3+"$"),P3="|&;()<> \\t",swe='"((\\\\"|[^"])*?)"',iwe="'((\\\\'|[^'])*?)'",owe=/^#$/,M3="'",I3='"',FM="$",Zc="",awe=4294967296;for($M=0;$M<4;$M++)Zc+=(awe*Math.random()).toString(16);var $M,lwe=new RegExp("^"+Zc);function cwe(r,e){for(var t=e.lastIndex,n=[],s;s=e.exec(r);)n.push(s),e.lastIndex===s.index&&(e.lastIndex+=1);return e.lastIndex=t,n}function uwe(r,e,t){var n=typeof r=="function"?r(t):r[t];return typeof n>"u"&&t!=""?n="":typeof n>"u"&&(n="$"),typeof n=="object"?e+Zc+JSON.stringify(n)+Zc:e+n}function dwe(r,e,t){t||(t={});var n=t.escape||"\\",s="(\\"+n+`['"`+P3+`]|[^\\s'"`+P3+"])+",o=new RegExp(["("+O3+")","("+s+"|"+swe+"|"+iwe+")+"].join("|"),"g"),a=cwe(r,o);if(a.length===0)return[];e||(e={});var l=!1;return a.map(function(c){var u=c[0];if(!u||l)return;if(R3.test(u))return{op:u};var d=!1,h=!1,f="",p=!1,y;function w(){y+=1;var b,v,S=u.charAt(y);if(S==="{"){if(y+=1,u.charAt(y)==="}")throw new Error("Bad substitution: "+u.slice(y-2,y+1));if(b=u.indexOf("}",y),b<0)throw new Error("Bad substitution: "+u.slice(y));v=u.slice(y,b),y=b}else if(/[*@#?$!_-]/.test(S))v=S,y+=1;else{var T=u.slice(y);b=T.match(/[^\w\d_]/),b?(v=T.slice(0,b.index),y+=b.index-1):(v=T,y=u.length)}return uwe(e,"",v)}for(y=0;y<u.length;y++){var m=u.charAt(y);if(p=p||!d&&(m==="*"||m==="?"),h)f+=m,h=!1;else if(d)m===d?d=!1:d==M3?f+=m:m===n?(y+=1,m=u.charAt(y),m===I3||m===n||m===FM?f+=m:f+=n+m):m===FM?f+=w():f+=m;else if(m===I3||m===M3)d=m;else{if(R3.test(m))return{op:u};if(owe.test(m)){l=!0;var _={comment:r.slice(c.index+y+1)};return f.length?[f,_]:[_]}else m===n?h=!0:m===FM?f+=w():f+=m}}return p?{op:"glob",pattern:f}:f}).reduce(function(c,u){return typeof u>"u"?c:c.concat(u)},[])}D3.exports=function(e,t,n){var s=dwe(e,t,n);return typeof t!="function"?s:s.reduce(function(o,a){if(typeof a=="object")return o.concat(a);var l=a.split(RegExp("("+Zc+".*?"+Zc+")","g"));return l.length===1?o.concat(l[0]):o.concat(l.filter(Boolean).map(function(c){return lwe.test(c)?JSON.parse(c.split(Zc)[1]):c}))},[])}});var il=N(UM=>{"use strict";g();UM.quote=A3();UM.parse=L3()});var h4=N((exports,module)=>{g();var Module=typeof Module<"u"?Module:{},ENVIRONMENT_IS_WEB=typeof window=="object",ENVIRONMENT_IS_WORKER=typeof importScripts=="function",ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",TreeSitter=function(){var initPromise,document=typeof window=="object"?{currentScript:window.document.currentScript}:null;class Parser{constructor(){this.initialize()}initialize(){throw new Error("cannot construct a Parser before calling `init()`")}static init(moduleOptions){return initPromise||(Module=Object.assign({},Module,moduleOptions),initPromise=new Promise(resolveInitPromise=>{var moduleOverrides=Object.assign({},Module),arguments_=[],thisProgram="./this.program",quit_=(r,e)=>{throw e},scriptDirectory="";function locateFile(r){return Module.locateFile?Module.locateFile(r,scriptDirectory):scriptDirectory+r}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=Se("fs"),nodePath=Se("path");scriptDirectory=__matilda_dirname+"/",readBinary=r=>{r=isFileURI(r)?new URL(r):nodePath.normalize(r);var e=fs.readFileSync(r);return e},readAsync=(r,e=!0)=>(r=isFileURI(r)?new URL(r):nodePath.normalize(r),new Promise((t,n)=>{fs.readFile(r,e?void 0:"utf8",(s,o)=>{s?n(s):t(e?o.buffer:o)})})),!Module.thisProgram&&process.argv.length>1&&(thisProgram=process.argv[1].replace(/\\/g,"/")),arguments_=process.argv.slice(2),typeof module<"u"&&(module.exports=Module),quit_=(r,e)=>{throw process.exitCode=r,e}}else(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)&&(ENVIRONMENT_IS_WORKER?scriptDirectory=self.location.href:typeof document<"u"&&document.currentScript&&(scriptDirectory=document.currentScript.src),scriptDirectory.startsWith("blob:")?scriptDirectory="":scriptDirectory=scriptDirectory.substr(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1),ENVIRONMENT_IS_WORKER&&(readBinary=r=>{var e=new XMLHttpRequest;return e.open("GET",r,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),readAsync=r=>isFileURI(r)?new Promise((e,t)=>{var n=new XMLHttpRequest;n.open("GET",r,!0),n.responseType="arraybuffer",n.onload=()=>{(n.status==200||n.status==0&&n.response)&&t(n.response),e(n.status)},n.onerror=e,n.send(null)}):fetch(r,{credentials:"same-origin"}).then(e=>e.ok?e.arrayBuffer():Promise.reject(new Error(e.status+" : "+e.url))));var out=Module.print||console.log.bind(console),err=Module.printErr||console.error.bind(console);Object.assign(Module,moduleOverrides),moduleOverrides=null,Module.arguments&&(arguments_=Module.arguments),Module.thisProgram&&(thisProgram=Module.thisProgram),Module.quit&&(quit_=Module.quit);var dynamicLibraries=Module.dynamicLibraries||[],wasmBinary;Module.wasmBinary&&(wasmBinary=Module.wasmBinary);var wasmMemory,ABORT=!1,EXITSTATUS,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64,HEAP_DATA_VIEW;function updateMemoryViews(){var r=wasmMemory.buffer;Module.HEAP_DATA_VIEW=HEAP_DATA_VIEW=new DataView(r),Module.HEAP8=HEAP8=new Int8Array(r),Module.HEAP16=HEAP16=new Int16Array(r),Module.HEAPU8=HEAPU8=new Uint8Array(r),Module.HEAPU16=HEAPU16=new Uint16Array(r),Module.HEAP32=HEAP32=new Int32Array(r),Module.HEAPU32=HEAPU32=new Uint32Array(r),Module.HEAPF32=HEAPF32=new Float32Array(r),Module.HEAPF64=HEAPF64=new Float64Array(r)}if(Module.wasmMemory)wasmMemory=Module.wasmMemory;else{var INITIAL_MEMORY=Module.INITIAL_MEMORY||33554432;wasmMemory=new WebAssembly.Memory({initial:INITIAL_MEMORY/65536,maximum:2147483648/65536})}updateMemoryViews();var __ATPRERUN__=[],__ATINIT__=[],__ATMAIN__=[],__ATPOSTRUN__=[],__RELOC_FUNCS__=[],runtimeInitialized=!1;function preRun(){if(Module.preRun)for(typeof Module.preRun=="function"&&(Module.preRun=[Module.preRun]);Module.preRun.length;)addOnPreRun(Module.preRun.shift());callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=!0,callRuntimeCallbacks(__RELOC_FUNCS__),callRuntimeCallbacks(__ATINIT__)}function preMain(){callRuntimeCallbacks(__ATMAIN__)}function postRun(){if(Module.postRun)for(typeof Module.postRun=="function"&&(Module.postRun=[Module.postRun]);Module.postRun.length;)addOnPostRun(Module.postRun.shift());callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(r){__ATPRERUN__.unshift(r)}function addOnInit(r){__ATINIT__.unshift(r)}function addOnPostRun(r){__ATPOSTRUN__.unshift(r)}var runDependencies=0,runDependencyWatcher=null,dependenciesFulfilled=null;function getUniqueRunDependency(r){return r}function addRunDependency(r){runDependencies++,Module.monitorRunDependencies?.(runDependencies)}function removeRunDependency(r){if(runDependencies--,Module.monitorRunDependencies?.(runDependencies),runDependencies==0&&(runDependencyWatcher!==null&&(clearInterval(runDependencyWatcher),runDependencyWatcher=null),dependenciesFulfilled)){var e=dependenciesFulfilled;dependenciesFulfilled=null,e()}}function abort(r){Module.onAbort?.(r),r="Aborted("+r+")",err(r),ABORT=!0,EXITSTATUS=1,r+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(r);throw e}var dataURIPrefix="data:application/octet-stream;base64,",isDataURI=r=>r.startsWith(dataURIPrefix),isFileURI=r=>r.startsWith("file://");function findWasmBinary(){var r="tree-sitter.wasm";return isDataURI(r)?r:locateFile(r)}var wasmBinaryFile;function getBinarySync(r){if(r==wasmBinaryFile&&wasmBinary)return new Uint8Array(wasmBinary);if(readBinary)return readBinary(r);throw"both async and sync fetching of the wasm failed"}function getBinaryPromise(r){return wasmBinary?Promise.resolve().then(()=>getBinarySync(r)):readAsync(r).then(e=>new Uint8Array(e),()=>getBinarySync(r))}function instantiateArrayBuffer(r,e,t){return getBinaryPromise(r).then(n=>WebAssembly.instantiate(n,e)).then(t,n=>{err(`failed to asynchronously prepare wasm: ${n}`),abort(n)})}function instantiateAsync(r,e,t,n){return!r&&typeof WebAssembly.instantiateStreaming=="function"&&!isDataURI(e)&&!isFileURI(e)&&!ENVIRONMENT_IS_NODE&&typeof fetch=="function"?fetch(e,{credentials:"same-origin"}).then(s=>{var o=WebAssembly.instantiateStreaming(s,t);return o.then(n,function(a){return err(`wasm streaming compile failed: ${a}`),err("falling back to ArrayBuffer instantiation"),instantiateArrayBuffer(e,t,n)})}):instantiateArrayBuffer(e,t,n)}function getWasmImports(){return{env:wasmImports,wasi_snapshot_preview1:wasmImports,"GOT.mem":new Proxy(wasmImports,GOTHandler),"GOT.func":new Proxy(wasmImports,GOTHandler)}}function createWasm(){var r=getWasmImports();function e(n,s){wasmExports=n.exports,wasmExports=relocateExports(wasmExports,1024);var o=getDylinkMetadata(s);return o.neededDynlibs&&(dynamicLibraries=o.neededDynlibs.concat(dynamicLibraries)),mergeLibSymbols(wasmExports,"main"),LDSO.init(),loadDylibs(),addOnInit(wasmExports.__wasm_call_ctors),__RELOC_FUNCS__.push(wasmExports.__wasm_apply_data_relocs),removeRunDependency("wasm-instantiate"),wasmExports}addRunDependency("wasm-instantiate");function t(n){e(n.instance,n.module)}if(Module.instantiateWasm)try{return Module.instantiateWasm(r,e)}catch(n){return err(`Module.instantiateWasm callback failed with error: ${n}`),!1}return wasmBinaryFile||(wasmBinaryFile=findWasmBinary()),instantiateAsync(wasmBinary,wasmBinaryFile,r,t),{}}var ASM_CONSTS={};function ExitStatus(r){this.name="ExitStatus",this.message=`Program terminated with exit(${r})`,this.status=r}var GOT={},currentModuleWeakSymbols=new Set([]),GOTHandler={get(r,e){var t=GOT[e];return t||(t=GOT[e]=new WebAssembly.Global({value:"i32",mutable:!0})),currentModuleWeakSymbols.has(e)||(t.required=!0),t}},LE_HEAP_LOAD_F32=r=>HEAP_DATA_VIEW.getFloat32(r,!0),LE_HEAP_LOAD_F64=r=>HEAP_DATA_VIEW.getFloat64(r,!0),LE_HEAP_LOAD_I16=r=>HEAP_DATA_VIEW.getInt16(r,!0),LE_HEAP_LOAD_I32=r=>HEAP_DATA_VIEW.getInt32(r,!0),LE_HEAP_LOAD_U32=r=>HEAP_DATA_VIEW.getUint32(r,!0),LE_HEAP_STORE_F32=(r,e)=>HEAP_DATA_VIEW.setFloat32(r,e,!0),LE_HEAP_STORE_F64=(r,e)=>HEAP_DATA_VIEW.setFloat64(r,e,!0),LE_HEAP_STORE_I16=(r,e)=>HEAP_DATA_VIEW.setInt16(r,e,!0),LE_HEAP_STORE_I32=(r,e)=>HEAP_DATA_VIEW.setInt32(r,e,!0),LE_HEAP_STORE_U32=(r,e)=>HEAP_DATA_VIEW.setUint32(r,e,!0),callRuntimeCallbacks=r=>{for(;r.length>0;)r.shift()(Module)},UTF8Decoder=typeof TextDecoder<"u"?new TextDecoder:void 0,UTF8ArrayToString=(r,e,t)=>{for(var n=e+t,s=e;r[s]&&!(s>=n);)++s;if(s-e>16&&r.buffer&&UTF8Decoder)return UTF8Decoder.decode(r.subarray(e,s));for(var o="";e<s;){var a=r[e++];if(!(a&128)){o+=String.fromCharCode(a);continue}var l=r[e++]&63;if((a&224)==192){o+=String.fromCharCode((a&31)<<6|l);continue}var c=r[e++]&63;if((a&240)==224?a=(a&15)<<12|l<<6|c:a=(a&7)<<18|l<<12|c<<6|r[e++]&63,a<65536)o+=String.fromCharCode(a);else{var u=a-65536;o+=String.fromCharCode(55296|u>>10,56320|u&1023)}}return o},getDylinkMetadata=r=>{var e=0,t=0;function n(){return r[e++]}function s(){for(var q=0,j=1;;){var z=r[e++];if(q+=(z&127)*j,j*=128,!(z&128))break}return q}function o(){var q=s();return e+=q,UTF8ArrayToString(r,e-q,q)}function a(q,j){if(q)throw new Error(j)}var l="dylink.0";if(r instanceof WebAssembly.Module){var c=WebAssembly.Module.customSections(r,l);c.length===0&&(l="dylink",c=WebAssembly.Module.customSections(r,l)),a(c.length===0,"need dylink section"),r=new Uint8Array(c[0]),t=r.length}else{var u=new Uint32Array(new Uint8Array(r.subarray(0,24)).buffer),d=u[0]==1836278016||u[0]==6386541;a(!d,"need to see wasm magic number"),a(r[8]!==0,"need the dylink section to be first"),e=9;var h=s();t=e+h,l=o()}var f={neededDynlibs:[],tlsExports:new Set,weakImports:new Set};if(l=="dylink"){f.memorySize=s(),f.memoryAlign=s(),f.tableSize=s(),f.tableAlign=s();for(var p=s(),y=0;y<p;++y){var w=o();f.neededDynlibs.push(w)}}else{a(l!=="dylink.0");for(var m=1,_=2,b=3,v=4,S=256,T=3,E=1;e<t;){var x=n(),k=s();if(x===m)f.memorySize=s(),f.memoryAlign=s(),f.tableSize=s(),f.tableAlign=s();else if(x===_)for(var p=s(),y=0;y<p;++y)w=o(),f.neededDynlibs.push(w);else if(x===b)for(var P=s();P--;){var B=o(),L=s();L&S&&f.tlsExports.add(B)}else if(x===v)for(var P=s();P--;){var $=o(),B=o(),L=s();(L&T)==E&&f.weakImports.add(B)}else e+=k}}return f};function getValue(r,e="i8"){switch(e.endsWith("*")&&(e="*"),e){case"i1":return HEAP8[r];case"i8":return HEAP8[r];case"i16":return LE_HEAP_LOAD_I16((r>>1)*2);case"i32":return LE_HEAP_LOAD_I32((r>>2)*4);case"i64":abort("to do getValue(i64) use WASM_BIGINT");case"float":return LE_HEAP_LOAD_F32((r>>2)*4);case"double":return LE_HEAP_LOAD_F64((r>>3)*8);case"*":return LE_HEAP_LOAD_U32((r>>2)*4);default:abort(`invalid type for getValue: ${e}`)}}var newDSO=(r,e,t)=>{var n={refcount:1/0,name:r,exports:t,global:!0};return LDSO.loadedLibsByName[r]=n,e!=null&&(LDSO.loadedLibsByHandle[e]=n),n},LDSO={loadedLibsByName:{},loadedLibsByHandle:{},init(){newDSO("__main__",0,wasmImports)}},___heap_base=78112,zeroMemory=(r,e)=>(HEAPU8.fill(0,r,r+e),r),alignMemory=(r,e)=>Math.ceil(r/e)*e,getMemory=r=>{if(runtimeInitialized)return zeroMemory(_malloc(r),r);var e=___heap_base,t=e+alignMemory(r,16);return ___heap_base=t,GOT.__heap_base.value=t,e},isInternalSym=r=>["__cpp_exception","__c_longjmp","__wasm_apply_data_relocs","__dso_handle","__tls_size","__tls_align","__set_stack_limits","_emscripten_tls_init","__wasm_init_tls","__wasm_call_ctors","__start_em_asm","__stop_em_asm","__start_em_js","__stop_em_js"].includes(r)||r.startsWith("__em_js__"),uleb128Encode=(r,e)=>{r<128?e.push(r):e.push(r%128|128,r>>7)},sigToWasmTypes=r=>{for(var e={i:"i32",j:"i64",f:"f32",d:"f64",e:"externref",p:"i32"},t={parameters:[],results:r[0]=="v"?[]:[e[r[0]]]},n=1;n<r.length;++n)t.parameters.push(e[r[n]]);return t},generateFuncType=(r,e)=>{var t=r.slice(0,1),n=r.slice(1),s={i:127,p:127,j:126,f:125,d:124,e:111};e.push(96),uleb128Encode(n.length,e);for(var o=0;o<n.length;++o)e.push(s[n[o]]);t=="v"?e.push(0):e.push(1,s[t])},convertJsFunctionToWasm=(r,e)=>{if(typeof WebAssembly.Function=="function")return new WebAssembly.Function(sigToWasmTypes(e),r);var t=[1];generateFuncType(e,t);var n=[0,97,115,109,1,0,0,0,1];uleb128Encode(t.length,n),n.push(...t),n.push(2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0);var s=new WebAssembly.Module(new Uint8Array(n)),o=new WebAssembly.Instance(s,{e:{f:r}}),a=o.exports.f;return a},wasmTableMirror=[],wasmTable=new WebAssembly.Table({initial:28,element:"anyfunc"}),getWasmTableEntry=r=>{var e=wasmTableMirror[r];return e||(r>=wasmTableMirror.length&&(wasmTableMirror.length=r+1),wasmTableMirror[r]=e=wasmTable.get(r)),e},updateTableMap=(r,e)=>{if(functionsInTableMap)for(var t=r;t<r+e;t++){var n=getWasmTableEntry(t);n&&functionsInTableMap.set(n,t)}},functionsInTableMap,getFunctionAddress=r=>(functionsInTableMap||(functionsInTableMap=new WeakMap,updateTableMap(0,wasmTable.length)),functionsInTableMap.get(r)||0),freeTableIndexes=[],getEmptyTableSlot=()=>{if(freeTableIndexes.length)return freeTableIndexes.pop();try{wasmTable.grow(1)}catch(r){throw r instanceof RangeError?"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.":r}return wasmTable.length-1},setWasmTableEntry=(r,e)=>{wasmTable.set(r,e),wasmTableMirror[r]=wasmTable.get(r)},addFunction=(r,e)=>{var t=getFunctionAddress(r);if(t)return t;var n=getEmptyTableSlot();try{setWasmTableEntry(n,r)}catch(o){if(!(o instanceof TypeError))throw o;var s=convertJsFunctionToWasm(r,e);setWasmTableEntry(n,s)}return functionsInTableMap.set(r,n),n},updateGOT=(r,e)=>{for(var t in r)if(!isInternalSym(t)){var n=r[t];t.startsWith("orig$")&&(t=t.split("$")[1],e=!0),GOT[t]||=new WebAssembly.Global({value:"i32",mutable:!0}),(e||GOT[t].value==0)&&(typeof n=="function"?GOT[t].value=addFunction(n):typeof n=="number"?GOT[t].value=n:err(`unhandled export type for '${t}': ${typeof n}`))}},relocateExports=(r,e,t)=>{var n={};for(var s in r){var o=r[s];typeof o=="object"&&(o=o.value),typeof o=="number"&&(o+=e),n[s]=o}return updateGOT(n,t),n},isSymbolDefined=r=>{var e=wasmImports[r];return!(!e||e.stub)},dynCallLegacy=(r,e,t)=>{r=r.replace(/p/g,"i");var n=Module["dynCall_"+r];return n(e,...t)},dynCall=(r,e,t=[])=>{if(r.includes("j"))return dynCallLegacy(r,e,t);var n=getWasmTableEntry(e)(...t);return n},stackSave=()=>_emscripten_stack_get_current(),stackRestore=r=>__emscripten_stack_restore(r),createInvokeFunction=r=>(e,...t)=>{var n=stackSave();try{return dynCall(r,e,t)}catch(s){if(stackRestore(n),s!==s+0)throw s;_setThrew(1,0)}},resolveGlobalSymbol=(r,e=!1)=>{var t;return e&&"orig$"+r in wasmImports&&(r="orig$"+r),isSymbolDefined(r)?t=wasmImports[r]:r.startsWith("invoke_")&&(t=wasmImports[r]=createInvokeFunction(r.split("_")[1])),{sym:t,name:r}},UTF8ToString=(r,e)=>r?UTF8ArrayToString(HEAPU8,r,e):"",loadWebAssemblyModule=(binary,flags,libName,localScope,handle)=>{var metadata=getDylinkMetadata(binary);currentModuleWeakSymbols=metadata.weakImports;function loadModule(){var firstLoad=!handle||!HEAP8[handle+8];if(firstLoad){var memAlign=Math.pow(2,metadata.memoryAlign),memoryBase=metadata.memorySize?alignMemory(getMemory(metadata.memorySize+memAlign),memAlign):0,tableBase=metadata.tableSize?wasmTable.length:0;handle&&(HEAP8[handle+8]=1,LE_HEAP_STORE_U32((handle+12>>2)*4,memoryBase),LE_HEAP_STORE_I32((handle+16>>2)*4,metadata.memorySize),LE_HEAP_STORE_U32((handle+20>>2)*4,tableBase),LE_HEAP_STORE_I32((handle+24>>2)*4,metadata.tableSize))}else memoryBase=LE_HEAP_LOAD_U32((handle+12>>2)*4),tableBase=LE_HEAP_LOAD_U32((handle+20>>2)*4);var tableGrowthNeeded=tableBase+metadata.tableSize-wasmTable.length;tableGrowthNeeded>0&&wasmTable.grow(tableGrowthNeeded);var moduleExports;function resolveSymbol(r){var e=resolveGlobalSymbol(r).sym;return!e&&localScope&&(e=localScope[r]),e||(e=moduleExports[r]),e}var proxyHandler={get(r,e){switch(e){case"__memory_base":return memoryBase;case"__table_base":return tableBase}if(e in wasmImports&&!wasmImports[e].stub)return wasmImports[e];if(!(e in r)){var t;r[e]=(...n)=>(t||=resolveSymbol(e),t(...n))}return r[e]}},proxy=new Proxy({},proxyHandler),info={"GOT.mem":new Proxy({},GOTHandler),"GOT.func":new Proxy({},GOTHandler),env:proxy,wasi_snapshot_preview1:proxy};function postInstantiation(module,instance){updateTableMap(tableBase,metadata.tableSize),moduleExports=relocateExports(instance.exports,memoryBase),flags.allowUndefined||reportUndefinedSymbols();function addEmAsm(addr,body){for(var args=[],arity=0;arity<16&&body.indexOf("$"+arity)!=-1;arity++)args.push("$"+arity);args=args.join(",");var func=`(${args}) => { ${body} };`;ASM_CONSTS[start]=eval(func)}if("__start_em_asm"in moduleExports)for(var start=moduleExports.__start_em_asm,stop=moduleExports.__stop_em_asm;start<stop;){var jsString=UTF8ToString(start);addEmAsm(start,jsString),start=HEAPU8.indexOf(0,start)+1}function addEmJs(name,cSig,body){var jsArgs=[];if(cSig=cSig.slice(1,-1),cSig!="void"){cSig=cSig.split(",");for(var i in cSig){var jsArg=cSig[i].split(" ").pop();jsArgs.push(jsArg.replace("*",""))}}var func=`(${jsArgs}) => ${body};`;moduleExports[name]=eval(func)}for(var name in moduleExports)if(name.startsWith("__em_js__")){var start=moduleExports[name],jsString=UTF8ToString(start),parts=jsString.split("<::>");addEmJs(name.replace("__em_js__",""),parts[0],parts[1]),delete moduleExports[name]}var applyRelocs=moduleExports.__wasm_apply_data_relocs;applyRelocs&&(runtimeInitialized?applyRelocs():__RELOC_FUNCS__.push(applyRelocs));var init=moduleExports.__wasm_call_ctors;return init&&(runtimeInitialized?init():__ATINIT__.push(init)),moduleExports}if(flags.loadAsync){if(binary instanceof WebAssembly.Module){var instance=new WebAssembly.Instance(binary,info);return Promise.resolve(postInstantiation(binary,instance))}return WebAssembly.instantiate(binary,info).then(r=>postInstantiation(r.module,r.instance))}var module=binary instanceof WebAssembly.Module?binary:new WebAssembly.Module(binary),instance=new WebAssembly.Instance(module,info);return postInstantiation(module,instance)}return flags.loadAsync?metadata.neededDynlibs.reduce((r,e)=>r.then(()=>loadDynamicLibrary(e,flags,localScope)),Promise.resolve()).then(loadModule):(metadata.neededDynlibs.forEach(r=>loadDynamicLibrary(r,flags,localScope)),loadModule())},mergeLibSymbols=(r,e)=>{for(var[t,n]of Object.entries(r)){let s=a=>{isSymbolDefined(a)||(wasmImports[a]=n)};s(t);let o="__main_argc_argv";t=="main"&&s(o),t==o&&s("main"),t.startsWith("dynCall_")&&!Module.hasOwnProperty(t)&&(Module[t]=n)}},asyncLoad=(r,e,t,n)=>{var s=n?"":`al ${r}`;readAsync(r).then(o=>{e(new Uint8Array(o)),s&&removeRunDependency(s)},o=>{if(t)t();else throw`Loading data file "${r}" failed.`}),s&&addRunDependency(s)};function loadDynamicLibrary(r,e={global:!0,nodelete:!0},t,n){var s=LDSO.loadedLibsByName[r];if(s)return e.global?s.global||(s.global=!0,mergeLibSymbols(s.exports,r)):t&&Object.assign(t,s.exports),e.nodelete&&s.refcount!==1/0&&(s.refcount=1/0),s.refcount++,n&&(LDSO.loadedLibsByHandle[n]=s),e.loadAsync?Promise.resolve(!0):!0;s=newDSO(r,n,"loading"),s.refcount=e.nodelete?1/0:1,s.global=e.global;function o(){if(n){var c=LE_HEAP_LOAD_U32((n+28>>2)*4),u=LE_HEAP_LOAD_U32((n+32>>2)*4);if(c&&u){var d=HEAP8.slice(c,c+u);return e.loadAsync?Promise.resolve(d):d}}var h=locateFile(r);if(e.loadAsync)return new Promise(function(f,p){asyncLoad(h,f,p)});if(!readBinary)throw new Error(`${h}: file not found, and synchronous loading of external files is not available`);return readBinary(h)}function a(){return e.loadAsync?o().then(c=>loadWebAssemblyModule(c,e,r,t,n)):loadWebAssemblyModule(o(),e,r,t,n)}function l(c){s.global?mergeLibSymbols(c,r):t&&Object.assign(t,c),s.exports=c}return e.loadAsync?a().then(c=>(l(c),!0)):(l(a()),!0)}var reportUndefinedSymbols=()=>{for(var[r,e]of Object.entries(GOT))if(e.value==0){var t=resolveGlobalSymbol(r,!0).sym;if(!t&&!e.required)continue;if(typeof t=="function")e.value=addFunction(t,t.sig);else if(typeof t=="number")e.value=t;else throw new Error(`bad export type for '${r}': ${typeof t}`)}},loadDylibs=()=>{if(!dynamicLibraries.length){reportUndefinedSymbols();return}addRunDependency("loadDylibs"),dynamicLibraries.reduce((r,e)=>r.then(()=>loadDynamicLibrary(e,{loadAsync:!0,global:!0,nodelete:!0,allowUndefined:!0})),Promise.resolve()).then(()=>{reportUndefinedSymbols(),removeRunDependency("loadDylibs")})},noExitRuntime=Module.noExitRuntime||!0;function setValue(r,e,t="i8"){switch(t.endsWith("*")&&(t="*"),t){case"i1":HEAP8[r]=e;break;case"i8":HEAP8[r]=e;break;case"i16":LE_HEAP_STORE_I16((r>>1)*2,e);break;case"i32":LE_HEAP_STORE_I32((r>>2)*4,e);break;case"i64":abort("to do setValue(i64) use WASM_BIGINT");case"float":LE_HEAP_STORE_F32((r>>2)*4,e);break;case"double":LE_HEAP_STORE_F64((r>>3)*8,e);break;case"*":LE_HEAP_STORE_U32((r>>2)*4,e);break;default:abort(`invalid type for setValue: ${t}`)}}var ___memory_base=new WebAssembly.Global({value:"i32",mutable:!1},1024),___stack_pointer=new WebAssembly.Global({value:"i32",mutable:!0},78112),___table_base=new WebAssembly.Global({value:"i32",mutable:!1},1),__abort_js=()=>{abort("")};__abort_js.sig="v";var nowIsMonotonic=1,__emscripten_get_now_is_monotonic=()=>nowIsMonotonic;__emscripten_get_now_is_monotonic.sig="i";var __emscripten_memcpy_js=(r,e,t)=>HEAPU8.copyWithin(r,e,e+t);__emscripten_memcpy_js.sig="vppp";var _emscripten_date_now=()=>Date.now();_emscripten_date_now.sig="d";var _emscripten_get_now;_emscripten_get_now=()=>performance.now(),_emscripten_get_now.sig="d";var getHeapMax=()=>2147483648,growMemory=r=>{var e=wasmMemory.buffer,t=(r-e.byteLength+65535)/65536;try{return wasmMemory.grow(t),updateMemoryViews(),1}catch{}},_emscripten_resize_heap=r=>{var e=HEAPU8.length;r>>>=0;var t=getHeapMax();if(r>t)return!1;for(var n=(c,u)=>c+(u-c%u)%u,s=1;s<=4;s*=2){var o=e*(1+.2/s);o=Math.min(o,r+100663296);var a=Math.min(t,n(Math.max(r,o),65536)),l=growMemory(a);if(l)return!0}return!1};_emscripten_resize_heap.sig="ip";var _fd_close=r=>52;_fd_close.sig="ii";var convertI32PairToI53Checked=(r,e)=>e+2097152>>>0<4194305-!!r?(r>>>0)+e*4294967296:NaN;function _fd_seek(r,e,t,n,s){var o=convertI32PairToI53Checked(e,t);return 70}_fd_seek.sig="iiiiip";var printCharBuffers=[null,[],[]],printChar=(r,e)=>{var t=printCharBuffers[r];e===0||e===10?((r===1?out:err)(UTF8ArrayToString(t,0)),t.length=0):t.push(e)},_fd_write=(r,e,t,n)=>{for(var s=0,o=0;o<t;o++){var a=LE_HEAP_LOAD_U32((e>>2)*4),l=LE_HEAP_LOAD_U32((e+4>>2)*4);e+=8;for(var c=0;c<l;c++)printChar(r,HEAPU8[a+c]);s+=l}return LE_HEAP_STORE_U32((n>>2)*4,s),0};_fd_write.sig="iippp";function _tree_sitter_log_callback(r,e){if(currentLogCallback){let t=UTF8ToString(e);currentLogCallback(t,r!==0)}}function _tree_sitter_parse_callback(r,e,t,n,s){let a=currentParseCallback(e,{row:t,column:n});typeof a=="string"?(setValue(s,a.length,"i32"),stringToUTF16(a,r,10240)):setValue(s,0,"i32")}var runtimeKeepaliveCounter=0,keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0,_proc_exit=r=>{EXITSTATUS=r,keepRuntimeAlive()||(Module.onExit?.(r),ABORT=!0),quit_(r,new ExitStatus(r))};_proc_exit.sig="vi";var exitJS=(r,e)=>{EXITSTATUS=r,_proc_exit(r)},handleException=r=>{if(r instanceof ExitStatus||r=="unwind")return EXITSTATUS;quit_(1,r)},lengthBytesUTF8=r=>{for(var e=0,t=0;t<r.length;++t){var n=r.charCodeAt(t);n<=127?e++:n<=2047?e+=2:n>=55296&&n<=57343?(e+=4,++t):e+=3}return e},stringToUTF8Array=(r,e,t,n)=>{if(!(n>0))return 0;for(var s=t,o=t+n-1,a=0;a<r.length;++a){var l=r.charCodeAt(a);if(l>=55296&&l<=57343){var c=r.charCodeAt(++a);l=65536+((l&1023)<<10)|c&1023}if(l<=127){if(t>=o)break;e[t++]=l}else if(l<=2047){if(t+1>=o)break;e[t++]=192|l>>6,e[t++]=128|l&63}else if(l<=65535){if(t+2>=o)break;e[t++]=224|l>>12,e[t++]=128|l>>6&63,e[t++]=128|l&63}else{if(t+3>=o)break;e[t++]=240|l>>18,e[t++]=128|l>>12&63,e[t++]=128|l>>6&63,e[t++]=128|l&63}}return e[t]=0,t-s},stringToUTF8=(r,e,t)=>stringToUTF8Array(r,HEAPU8,e,t),stackAlloc=r=>__emscripten_stack_alloc(r),stringToUTF8OnStack=r=>{var e=lengthBytesUTF8(r)+1,t=stackAlloc(e);return stringToUTF8(r,t,e),t},stringToUTF16=(r,e,t)=>{if(t??=2147483647,t<2)return 0;t-=2;for(var n=e,s=t<r.length*2?t/2:r.length,o=0;o<s;++o){var a=r.charCodeAt(o);LE_HEAP_STORE_I16((e>>1)*2,a),e+=2}return LE_HEAP_STORE_I16((e>>1)*2,0),e-n},AsciiToString=r=>{for(var e="";;){var t=HEAPU8[r++];if(!t)return e;e+=String.fromCharCode(t)}},wasmImports={__heap_base:___heap_base,__indirect_function_table:wasmTable,__memory_base:___memory_base,__stack_pointer:___stack_pointer,__table_base:___table_base,_abort_js:__abort_js,_emscripten_get_now_is_monotonic:__emscripten_get_now_is_monotonic,_emscripten_memcpy_js:__emscripten_memcpy_js,emscripten_get_now:_emscripten_get_now,emscripten_resize_heap:_emscripten_resize_heap,fd_close:_fd_close,fd_seek:_fd_seek,fd_write:_fd_write,memory:wasmMemory,tree_sitter_log_callback:_tree_sitter_log_callback,tree_sitter_parse_callback:_tree_sitter_parse_callback},wasmExports=createWasm(),___wasm_call_ctors=()=>(___wasm_call_ctors=wasmExports.__wasm_call_ctors)(),___wasm_apply_data_relocs=()=>(___wasm_apply_data_relocs=wasmExports.__wasm_apply_data_relocs)(),_malloc=Module._malloc=r=>(_malloc=Module._malloc=wasmExports.malloc)(r),_calloc=Module._calloc=(r,e)=>(_calloc=Module._calloc=wasmExports.calloc)(r,e),_realloc=Module._realloc=(r,e)=>(_realloc=Module._realloc=wasmExports.realloc)(r,e),_free=Module._free=r=>(_free=Module._free=wasmExports.free)(r),_ts_language_symbol_count=Module._ts_language_symbol_count=r=>(_ts_language_symbol_count=Module._ts_language_symbol_count=wasmExports.ts_language_symbol_count)(r),_ts_language_state_count=Module._ts_language_state_count=r=>(_ts_language_state_count=Module._ts_language_state_count=wasmExports.ts_language_state_count)(r),_ts_language_version=Module._ts_language_version=r=>(_ts_language_version=Module._ts_language_version=wasmExports.ts_language_version)(r),_ts_language_field_count=Module._ts_language_field_count=r=>(_ts_language_field_count=Module._ts_language_field_count=wasmExports.ts_language_field_count)(r),_ts_language_next_state=Module._ts_language_next_state=(r,e,t)=>(_ts_language_next_state=Module._ts_language_next_state=wasmExports.ts_language_next_state)(r,e,t),_ts_language_symbol_name=Module._ts_language_symbol_name=(r,e)=>(_ts_language_symbol_name=Module._ts_language_symbol_name=wasmExports.ts_language_symbol_name)(r,e),_ts_language_symbol_for_name=Module._ts_language_symbol_for_name=(r,e,t,n)=>(_ts_language_symbol_for_name=Module._ts_language_symbol_for_name=wasmExports.ts_language_symbol_for_name)(r,e,t,n),_strncmp=Module._strncmp=(r,e,t)=>(_strncmp=Module._strncmp=wasmExports.strncmp)(r,e,t),_ts_language_symbol_type=Module._ts_language_symbol_type=(r,e)=>(_ts_language_symbol_type=Module._ts_language_symbol_type=wasmExports.ts_language_symbol_type)(r,e),_ts_language_field_name_for_id=Module._ts_language_field_name_for_id=(r,e)=>(_ts_language_field_name_for_id=Module._ts_language_field_name_for_id=wasmExports.ts_language_field_name_for_id)(r,e),_ts_lookahead_iterator_new=Module._ts_lookahead_iterator_new=(r,e)=>(_ts_lookahead_iterator_new=Module._ts_lookahead_iterator_new=wasmExports.ts_lookahead_iterator_new)(r,e),_ts_lookahead_iterator_delete=Module._ts_lookahead_iterator_delete=r=>(_ts_lookahead_iterator_delete=Module._ts_lookahead_iterator_delete=wasmExports.ts_lookahead_iterator_delete)(r),_ts_lookahead_iterator_reset_state=Module._ts_lookahead_iterator_reset_state=(r,e)=>(_ts_lookahead_iterator_reset_state=Module._ts_lookahead_iterator_reset_state=wasmExports.ts_lookahead_iterator_reset_state)(r,e),_ts_lookahead_iterator_reset=Module._ts_lookahead_iterator_reset=(r,e,t)=>(_ts_lookahead_iterator_reset=Module._ts_lookahead_iterator_reset=wasmExports.ts_lookahead_iterator_reset)(r,e,t),_ts_lookahead_iterator_next=Module._ts_lookahead_iterator_next=r=>(_ts_lookahead_iterator_next=Module._ts_lookahead_iterator_next=wasmExports.ts_lookahead_iterator_next)(r),_ts_lookahead_iterator_current_symbol=Module._ts_lookahead_iterator_current_symbol=r=>(_ts_lookahead_iterator_current_symbol=Module._ts_lookahead_iterator_current_symbol=wasmExports.ts_lookahead_iterator_current_symbol)(r),_memset=Module._memset=(r,e,t)=>(_memset=Module._memset=wasmExports.memset)(r,e,t),_memcpy=Module._memcpy=(r,e,t)=>(_memcpy=Module._memcpy=wasmExports.memcpy)(r,e,t),_ts_parser_delete=Module._ts_parser_delete=r=>(_ts_parser_delete=Module._ts_parser_delete=wasmExports.ts_parser_delete)(r),_ts_parser_reset=Module._ts_parser_reset=r=>(_ts_parser_reset=Module._ts_parser_reset=wasmExports.ts_parser_reset)(r),_ts_parser_set_language=Module._ts_parser_set_language=(r,e)=>(_ts_parser_set_language=Module._ts_parser_set_language=wasmExports.ts_parser_set_language)(r,e),_ts_parser_timeout_micros=Module._ts_parser_timeout_micros=r=>(_ts_parser_timeout_micros=Module._ts_parser_timeout_micros=wasmExports.ts_parser_timeout_micros)(r),_ts_parser_set_timeout_micros=Module._ts_parser_set_timeout_micros=(r,e,t)=>(_ts_parser_set_timeout_micros=Module._ts_parser_set_timeout_micros=wasmExports.ts_parser_set_timeout_micros)(r,e,t),_ts_parser_set_included_ranges=Module._ts_parser_set_included_ranges=(r,e,t)=>(_ts_parser_set_included_ranges=Module._ts_parser_set_included_ranges=wasmExports.ts_parser_set_included_ranges)(r,e,t),_memmove=Module._memmove=(r,e,t)=>(_memmove=Module._memmove=wasmExports.memmove)(r,e,t),_memcmp=Module._memcmp=(r,e,t)=>(_memcmp=Module._memcmp=wasmExports.memcmp)(r,e,t),_ts_query_new=Module._ts_query_new=(r,e,t,n,s)=>(_ts_query_new=Module._ts_query_new=wasmExports.ts_query_new)(r,e,t,n,s),_ts_query_delete=Module._ts_query_delete=r=>(_ts_query_delete=Module._ts_query_delete=wasmExports.ts_query_delete)(r),_iswspace=Module._iswspace=r=>(_iswspace=Module._iswspace=wasmExports.iswspace)(r),_iswalnum=Module._iswalnum=r=>(_iswalnum=Module._iswalnum=wasmExports.iswalnum)(r),_ts_query_pattern_count=Module._ts_query_pattern_count=r=>(_ts_query_pattern_count=Module._ts_query_pattern_count=wasmExports.ts_query_pattern_count)(r),_ts_query_capture_count=Module._ts_query_capture_count=r=>(_ts_query_capture_count=Module._ts_query_capture_count=wasmExports.ts_query_capture_count)(r),_ts_query_string_count=Module._ts_query_string_count=r=>(_ts_query_string_count=Module._ts_query_string_count=wasmExports.ts_query_string_count)(r),_ts_query_capture_name_for_id=Module._ts_query_capture_name_for_id=(r,e,t)=>(_ts_query_capture_name_for_id=Module._ts_query_capture_name_for_id=wasmExports.ts_query_capture_name_for_id)(r,e,t),_ts_query_string_value_for_id=Module._ts_query_string_value_for_id=(r,e,t)=>(_ts_query_string_value_for_id=Module._ts_query_string_value_for_id=wasmExports.ts_query_string_value_for_id)(r,e,t),_ts_query_predicates_for_pattern=Module._ts_query_predicates_for_pattern=(r,e,t)=>(_ts_query_predicates_for_pattern=Module._ts_query_predicates_for_pattern=wasmExports.ts_query_predicates_for_pattern)(r,e,t),_ts_query_disable_capture=Module._ts_query_disable_capture=(r,e,t)=>(_ts_query_disable_capture=Module._ts_query_disable_capture=wasmExports.ts_query_disable_capture)(r,e,t),_ts_tree_copy=Module._ts_tree_copy=r=>(_ts_tree_copy=Module._ts_tree_copy=wasmExports.ts_tree_copy)(r),_ts_tree_delete=Module._ts_tree_delete=r=>(_ts_tree_delete=Module._ts_tree_delete=wasmExports.ts_tree_delete)(r),_ts_init=Module._ts_init=()=>(_ts_init=Module._ts_init=wasmExports.ts_init)(),_ts_parser_new_wasm=Module._ts_parser_new_wasm=()=>(_ts_parser_new_wasm=Module._ts_parser_new_wasm=wasmExports.ts_parser_new_wasm)(),_ts_parser_enable_logger_wasm=Module._ts_parser_enable_logger_wasm=(r,e)=>(_ts_parser_enable_logger_wasm=Module._ts_parser_enable_logger_wasm=wasmExports.ts_parser_enable_logger_wasm)(r,e),_ts_parser_parse_wasm=Module._ts_parser_parse_wasm=(r,e,t,n,s)=>(_ts_parser_parse_wasm=Module._ts_parser_parse_wasm=wasmExports.ts_parser_parse_wasm)(r,e,t,n,s),_ts_parser_included_ranges_wasm=Module._ts_parser_included_ranges_wasm=r=>(_ts_parser_included_ranges_wasm=Module._ts_parser_included_ranges_wasm=wasmExports.ts_parser_included_ranges_wasm)(r),_ts_language_type_is_named_wasm=Module._ts_language_type_is_named_wasm=(r,e)=>(_ts_language_type_is_named_wasm=Module._ts_language_type_is_named_wasm=wasmExports.ts_language_type_is_named_wasm)(r,e),_ts_language_type_is_visible_wasm=Module._ts_language_type_is_visible_wasm=(r,e)=>(_ts_language_type_is_visible_wasm=Module._ts_language_type_is_visible_wasm=wasmExports.ts_language_type_is_visible_wasm)(r,e),_ts_tree_root_node_wasm=Module._ts_tree_root_node_wasm=r=>(_ts_tree_root_node_wasm=Module._ts_tree_root_node_wasm=wasmExports.ts_tree_root_node_wasm)(r),_ts_tree_root_node_with_offset_wasm=Module._ts_tree_root_node_with_offset_wasm=r=>(_ts_tree_root_node_with_offset_wasm=Module._ts_tree_root_node_with_offset_wasm=wasmExports.ts_tree_root_node_with_offset_wasm)(r),_ts_tree_edit_wasm=Module._ts_tree_edit_wasm=r=>(_ts_tree_edit_wasm=Module._ts_tree_edit_wasm=wasmExports.ts_tree_edit_wasm)(r),_ts_tree_included_ranges_wasm=Module._ts_tree_included_ranges_wasm=r=>(_ts_tree_included_ranges_wasm=Module._ts_tree_included_ranges_wasm=wasmExports.ts_tree_included_ranges_wasm)(r),_ts_tree_get_changed_ranges_wasm=Module._ts_tree_get_changed_ranges_wasm=(r,e)=>(_ts_tree_get_changed_ranges_wasm=Module._ts_tree_get_changed_ranges_wasm=wasmExports.ts_tree_get_changed_ranges_wasm)(r,e),_ts_tree_cursor_new_wasm=Module._ts_tree_cursor_new_wasm=r=>(_ts_tree_cursor_new_wasm=Module._ts_tree_cursor_new_wasm=wasmExports.ts_tree_cursor_new_wasm)(r),_ts_tree_cursor_delete_wasm=Module._ts_tree_cursor_delete_wasm=r=>(_ts_tree_cursor_delete_wasm=Module._ts_tree_cursor_delete_wasm=wasmExports.ts_tree_cursor_delete_wasm)(r),_ts_tree_cursor_reset_wasm=Module._ts_tree_cursor_reset_wasm=r=>(_ts_tree_cursor_reset_wasm=Module._ts_tree_cursor_reset_wasm=wasmExports.ts_tree_cursor_reset_wasm)(r),_ts_tree_cursor_reset_to_wasm=Module._ts_tree_cursor_reset_to_wasm=(r,e)=>(_ts_tree_cursor_reset_to_wasm=Module._ts_tree_cursor_reset_to_wasm=wasmExports.ts_tree_cursor_reset_to_wasm)(r,e),_ts_tree_cursor_goto_first_child_wasm=Module._ts_tree_cursor_goto_first_child_wasm=r=>(_ts_tree_cursor_goto_first_child_wasm=Module._ts_tree_cursor_goto_first_child_wasm=wasmExports.ts_tree_cursor_goto_first_child_wasm)(r),_ts_tree_cursor_goto_last_child_wasm=Module._ts_tree_cursor_goto_last_child_wasm=r=>(_ts_tree_cursor_goto_last_child_wasm=Module._ts_tree_cursor_goto_last_child_wasm=wasmExports.ts_tree_cursor_goto_last_child_wasm)(r),_ts_tree_cursor_goto_first_child_for_index_wasm=Module._ts_tree_cursor_goto_first_child_for_index_wasm=r=>(_ts_tree_cursor_goto_first_child_for_index_wasm=Module._ts_tree_cursor_goto_first_child_for_index_wasm=wasmExports.ts_tree_cursor_goto_first_child_for_index_wasm)(r),_ts_tree_cursor_goto_first_child_for_position_wasm=Module._ts_tree_cursor_goto_first_child_for_position_wasm=r=>(_ts_tree_cursor_goto_first_child_for_position_wasm=Module._ts_tree_cursor_goto_first_child_for_position_wasm=wasmExports.ts_tree_cursor_goto_first_child_for_position_wasm)(r),_ts_tree_cursor_goto_next_sibling_wasm=Module._ts_tree_cursor_goto_next_sibling_wasm=r=>(_ts_tree_cursor_goto_next_sibling_wasm=Module._ts_tree_cursor_goto_next_sibling_wasm=wasmExports.ts_tree_cursor_goto_next_sibling_wasm)(r),_ts_tree_cursor_goto_previous_sibling_wasm=Module._ts_tree_cursor_goto_previous_sibling_wasm=r=>(_ts_tree_cursor_goto_previous_sibling_wasm=Module._ts_tree_cursor_goto_previous_sibling_wasm=wasmExports.ts_tree_cursor_goto_previous_sibling_wasm)(r),_ts_tree_cursor_goto_descendant_wasm=Module._ts_tree_cursor_goto_descendant_wasm=(r,e)=>(_ts_tree_cursor_goto_descendant_wasm=Module._ts_tree_cursor_goto_descendant_wasm=wasmExports.ts_tree_cursor_goto_descendant_wasm)(r,e),_ts_tree_cursor_goto_parent_wasm=Module._ts_tree_cursor_goto_parent_wasm=r=>(_ts_tree_cursor_goto_parent_wasm=Module._ts_tree_cursor_goto_parent_wasm=wasmExports.ts_tree_cursor_goto_parent_wasm)(r),_ts_tree_cursor_current_node_type_id_wasm=Module._ts_tree_cursor_current_node_type_id_wasm=r=>(_ts_tree_cursor_current_node_type_id_wasm=Module._ts_tree_cursor_current_node_type_id_wasm=wasmExports.ts_tree_cursor_current_node_type_id_wasm)(r),_ts_tree_cursor_current_node_state_id_wasm=Module._ts_tree_cursor_current_node_state_id_wasm=r=>(_ts_tree_cursor_current_node_state_id_wasm=Module._ts_tree_cursor_current_node_state_id_wasm=wasmExports.ts_tree_cursor_current_node_state_id_wasm)(r),_ts_tree_cursor_current_node_is_named_wasm=Module._ts_tree_cursor_current_node_is_named_wasm=r=>(_ts_tree_cursor_current_node_is_named_wasm=Module._ts_tree_cursor_current_node_is_named_wasm=wasmExports.ts_tree_cursor_current_node_is_named_wasm)(r),_ts_tree_cursor_current_node_is_missing_wasm=Module._ts_tree_cursor_current_node_is_missing_wasm=r=>(_ts_tree_cursor_current_node_is_missing_wasm=Module._ts_tree_cursor_current_node_is_missing_wasm=wasmExports.ts_tree_cursor_current_node_is_missing_wasm)(r),_ts_tree_cursor_current_node_id_wasm=Module._ts_tree_cursor_current_node_id_wasm=r=>(_ts_tree_cursor_current_node_id_wasm=Module._ts_tree_cursor_current_node_id_wasm=wasmExports.ts_tree_cursor_current_node_id_wasm)(r),_ts_tree_cursor_start_position_wasm=Module._ts_tree_cursor_start_position_wasm=r=>(_ts_tree_cursor_start_position_wasm=Module._ts_tree_cursor_start_position_wasm=wasmExports.ts_tree_cursor_start_position_wasm)(r),_ts_tree_cursor_end_position_wasm=Module._ts_tree_cursor_end_position_wasm=r=>(_ts_tree_cursor_end_position_wasm=Module._ts_tree_cursor_end_position_wasm=wasmExports.ts_tree_cursor_end_position_wasm)(r),_ts_tree_cursor_start_index_wasm=Module._ts_tree_cursor_start_index_wasm=r=>(_ts_tree_cursor_start_index_wasm=Module._ts_tree_cursor_start_index_wasm=wasmExports.ts_tree_cursor_start_index_wasm)(r),_ts_tree_cursor_end_index_wasm=Module._ts_tree_cursor_end_index_wasm=r=>(_ts_tree_cursor_end_index_wasm=Module._ts_tree_cursor_end_index_wasm=wasmExports.ts_tree_cursor_end_index_wasm)(r),_ts_tree_cursor_current_field_id_wasm=Module._ts_tree_cursor_current_field_id_wasm=r=>(_ts_tree_cursor_current_field_id_wasm=Module._ts_tree_cursor_current_field_id_wasm=wasmExports.ts_tree_cursor_current_field_id_wasm)(r),_ts_tree_cursor_current_depth_wasm=Module._ts_tree_cursor_current_depth_wasm=r=>(_ts_tree_cursor_current_depth_wasm=Module._ts_tree_cursor_current_depth_wasm=wasmExports.ts_tree_cursor_current_depth_wasm)(r),_ts_tree_cursor_current_descendant_index_wasm=Module._ts_tree_cursor_current_descendant_index_wasm=r=>(_ts_tree_cursor_current_descendant_index_wasm=Module._ts_tree_cursor_current_descendant_index_wasm=wasmExports.ts_tree_cursor_current_descendant_index_wasm)(r),_ts_tree_cursor_current_node_wasm=Module._ts_tree_cursor_current_node_wasm=r=>(_ts_tree_cursor_current_node_wasm=Module._ts_tree_cursor_current_node_wasm=wasmExports.ts_tree_cursor_current_node_wasm)(r),_ts_node_symbol_wasm=Module._ts_node_symbol_wasm=r=>(_ts_node_symbol_wasm=Module._ts_node_symbol_wasm=wasmExports.ts_node_symbol_wasm)(r),_ts_node_field_name_for_child_wasm=Module._ts_node_field_name_for_child_wasm=(r,e)=>(_ts_node_field_name_for_child_wasm=Module._ts_node_field_name_for_child_wasm=wasmExports.ts_node_field_name_for_child_wasm)(r,e),_ts_node_children_by_field_id_wasm=Module._ts_node_children_by_field_id_wasm=(r,e)=>(_ts_node_children_by_field_id_wasm=Module._ts_node_children_by_field_id_wasm=wasmExports.ts_node_children_by_field_id_wasm)(r,e),_ts_node_first_child_for_byte_wasm=Module._ts_node_first_child_for_byte_wasm=r=>(_ts_node_first_child_for_byte_wasm=Module._ts_node_first_child_for_byte_wasm=wasmExports.ts_node_first_child_for_byte_wasm)(r),_ts_node_first_named_child_for_byte_wasm=Module._ts_node_first_named_child_for_byte_wasm=r=>(_ts_node_first_named_child_for_byte_wasm=Module._ts_node_first_named_child_for_byte_wasm=wasmExports.ts_node_first_named_child_for_byte_wasm)(r),_ts_node_grammar_symbol_wasm=Module._ts_node_grammar_symbol_wasm=r=>(_ts_node_grammar_symbol_wasm=Module._ts_node_grammar_symbol_wasm=wasmExports.ts_node_grammar_symbol_wasm)(r),_ts_node_child_count_wasm=Module._ts_node_child_count_wasm=r=>(_ts_node_child_count_wasm=Module._ts_node_child_count_wasm=wasmExports.ts_node_child_count_wasm)(r),_ts_node_named_child_count_wasm=Module._ts_node_named_child_count_wasm=r=>(_ts_node_named_child_count_wasm=Module._ts_node_named_child_count_wasm=wasmExports.ts_node_named_child_count_wasm)(r),_ts_node_child_wasm=Module._ts_node_child_wasm=(r,e)=>(_ts_node_child_wasm=Module._ts_node_child_wasm=wasmExports.ts_node_child_wasm)(r,e),_ts_node_named_child_wasm=Module._ts_node_named_child_wasm=(r,e)=>(_ts_node_named_child_wasm=Module._ts_node_named_child_wasm=wasmExports.ts_node_named_child_wasm)(r,e),_ts_node_child_by_field_id_wasm=Module._ts_node_child_by_field_id_wasm=(r,e)=>(_ts_node_child_by_field_id_wasm=Module._ts_node_child_by_field_id_wasm=wasmExports.ts_node_child_by_field_id_wasm)(r,e),_ts_node_next_sibling_wasm=Module._ts_node_next_sibling_wasm=r=>(_ts_node_next_sibling_wasm=Module._ts_node_next_sibling_wasm=wasmExports.ts_node_next_sibling_wasm)(r),_ts_node_prev_sibling_wasm=Module._ts_node_prev_sibling_wasm=r=>(_ts_node_prev_sibling_wasm=Module._ts_node_prev_sibling_wasm=wasmExports.ts_node_prev_sibling_wasm)(r),_ts_node_next_named_sibling_wasm=Module._ts_node_next_named_sibling_wasm=r=>(_ts_node_next_named_sibling_wasm=Module._ts_node_next_named_sibling_wasm=wasmExports.ts_node_next_named_sibling_wasm)(r),_ts_node_prev_named_sibling_wasm=Module._ts_node_prev_named_sibling_wasm=r=>(_ts_node_prev_named_sibling_wasm=Module._ts_node_prev_named_sibling_wasm=wasmExports.ts_node_prev_named_sibling_wasm)(r),_ts_node_descendant_count_wasm=Module._ts_node_descendant_count_wasm=r=>(_ts_node_descendant_count_wasm=Module._ts_node_descendant_count_wasm=wasmExports.ts_node_descendant_count_wasm)(r),_ts_node_parent_wasm=Module._ts_node_parent_wasm=r=>(_ts_node_parent_wasm=Module._ts_node_parent_wasm=wasmExports.ts_node_parent_wasm)(r),_ts_node_descendant_for_index_wasm=Module._ts_node_descendant_for_index_wasm=r=>(_ts_node_descendant_for_index_wasm=Module._ts_node_descendant_for_index_wasm=wasmExports.ts_node_descendant_for_index_wasm)(r),_ts_node_named_descendant_for_index_wasm=Module._ts_node_named_descendant_for_index_wasm=r=>(_ts_node_named_descendant_for_index_wasm=Module._ts_node_named_descendant_for_index_wasm=wasmExports.ts_node_named_descendant_for_index_wasm)(r),_ts_node_descendant_for_position_wasm=Module._ts_node_descendant_for_position_wasm=r=>(_ts_node_descendant_for_position_wasm=Module._ts_node_descendant_for_position_wasm=wasmExports.ts_node_descendant_for_position_wasm)(r),_ts_node_named_descendant_for_position_wasm=Module._ts_node_named_descendant_for_position_wasm=r=>(_ts_node_named_descendant_for_position_wasm=Module._ts_node_named_descendant_for_position_wasm=wasmExports.ts_node_named_descendant_for_position_wasm)(r),_ts_node_start_point_wasm=Module._ts_node_start_point_wasm=r=>(_ts_node_start_point_wasm=Module._ts_node_start_point_wasm=wasmExports.ts_node_start_point_wasm)(r),_ts_node_end_point_wasm=Module._ts_node_end_point_wasm=r=>(_ts_node_end_point_wasm=Module._ts_node_end_point_wasm=wasmExports.ts_node_end_point_wasm)(r),_ts_node_start_index_wasm=Module._ts_node_start_index_wasm=r=>(_ts_node_start_index_wasm=Module._ts_node_start_index_wasm=wasmExports.ts_node_start_index_wasm)(r),_ts_node_end_index_wasm=Module._ts_node_end_index_wasm=r=>(_ts_node_end_index_wasm=Module._ts_node_end_index_wasm=wasmExports.ts_node_end_index_wasm)(r),_ts_node_to_string_wasm=Module._ts_node_to_string_wasm=r=>(_ts_node_to_string_wasm=Module._ts_node_to_string_wasm=wasmExports.ts_node_to_string_wasm)(r),_ts_node_children_wasm=Module._ts_node_children_wasm=r=>(_ts_node_children_wasm=Module._ts_node_children_wasm=wasmExports.ts_node_children_wasm)(r),_ts_node_named_children_wasm=Module._ts_node_named_children_wasm=r=>(_ts_node_named_children_wasm=Module._ts_node_named_children_wasm=wasmExports.ts_node_named_children_wasm)(r),_ts_node_descendants_of_type_wasm=Module._ts_node_descendants_of_type_wasm=(r,e,t,n,s,o,a)=>(_ts_node_descendants_of_type_wasm=Module._ts_node_descendants_of_type_wasm=wasmExports.ts_node_descendants_of_type_wasm)(r,e,t,n,s,o,a),_ts_node_is_named_wasm=Module._ts_node_is_named_wasm=r=>(_ts_node_is_named_wasm=Module._ts_node_is_named_wasm=wasmExports.ts_node_is_named_wasm)(r),_ts_node_has_changes_wasm=Module._ts_node_has_changes_wasm=r=>(_ts_node_has_changes_wasm=Module._ts_node_has_changes_wasm=wasmExports.ts_node_has_changes_wasm)(r),_ts_node_has_error_wasm=Module._ts_node_has_error_wasm=r=>(_ts_node_has_error_wasm=Module._ts_node_has_error_wasm=wasmExports.ts_node_has_error_wasm)(r),_ts_node_is_error_wasm=Module._ts_node_is_error_wasm=r=>(_ts_node_is_error_wasm=Module._ts_node_is_error_wasm=wasmExports.ts_node_is_error_wasm)(r),_ts_node_is_missing_wasm=Module._ts_node_is_missing_wasm=r=>(_ts_node_is_missing_wasm=Module._ts_node_is_missing_wasm=wasmExports.ts_node_is_missing_wasm)(r),_ts_node_is_extra_wasm=Module._ts_node_is_extra_wasm=r=>(_ts_node_is_extra_wasm=Module._ts_node_is_extra_wasm=wasmExports.ts_node_is_extra_wasm)(r),_ts_node_parse_state_wasm=Module._ts_node_parse_state_wasm=r=>(_ts_node_parse_state_wasm=Module._ts_node_parse_state_wasm=wasmExports.ts_node_parse_state_wasm)(r),_ts_node_next_parse_state_wasm=Module._ts_node_next_parse_state_wasm=r=>(_ts_node_next_parse_state_wasm=Module._ts_node_next_parse_state_wasm=wasmExports.ts_node_next_parse_state_wasm)(r),_ts_query_matches_wasm=Module._ts_query_matches_wasm=(r,e,t,n,s,o,a,l,c,u,d)=>(_ts_query_matches_wasm=Module._ts_query_matches_wasm=wasmExports.ts_query_matches_wasm)(r,e,t,n,s,o,a,l,c,u,d),_ts_query_captures_wasm=Module._ts_query_captures_wasm=(r,e,t,n,s,o,a,l,c,u,d)=>(_ts_query_captures_wasm=Module._ts_query_captures_wasm=wasmExports.ts_query_captures_wasm)(r,e,t,n,s,o,a,l,c,u,d),_iswalpha=Module._iswalpha=r=>(_iswalpha=Module._iswalpha=wasmExports.iswalpha)(r),_iswblank=Module._iswblank=r=>(_iswblank=Module._iswblank=wasmExports.iswblank)(r),_iswdigit=Module._iswdigit=r=>(_iswdigit=Module._iswdigit=wasmExports.iswdigit)(r),_iswlower=Module._iswlower=r=>(_iswlower=Module._iswlower=wasmExports.iswlower)(r),_iswupper=Module._iswupper=r=>(_iswupper=Module._iswupper=wasmExports.iswupper)(r),_iswxdigit=Module._iswxdigit=r=>(_iswxdigit=Module._iswxdigit=wasmExports.iswxdigit)(r),_memchr=Module._memchr=(r,e,t)=>(_memchr=Module._memchr=wasmExports.memchr)(r,e,t),_strlen=Module._strlen=r=>(_strlen=Module._strlen=wasmExports.strlen)(r),_strcmp=Module._strcmp=(r,e)=>(_strcmp=Module._strcmp=wasmExports.strcmp)(r,e),_strncat=Module._strncat=(r,e,t)=>(_strncat=Module._strncat=wasmExports.strncat)(r,e,t),_strncpy=Module._strncpy=(r,e,t)=>(_strncpy=Module._strncpy=wasmExports.strncpy)(r,e,t),_towlower=Module._towlower=r=>(_towlower=Module._towlower=wasmExports.towlower)(r),_towupper=Module._towupper=r=>(_towupper=Module._towupper=wasmExports.towupper)(r),_setThrew=(r,e)=>(_setThrew=wasmExports.setThrew)(r,e),__emscripten_stack_restore=r=>(__emscripten_stack_restore=wasmExports._emscripten_stack_restore)(r),__emscripten_stack_alloc=r=>(__emscripten_stack_alloc=wasmExports._emscripten_stack_alloc)(r),_emscripten_stack_get_current=()=>(_emscripten_stack_get_current=wasmExports.emscripten_stack_get_current)(),dynCall_jiji=Module.dynCall_jiji=(r,e,t,n,s)=>(dynCall_jiji=Module.dynCall_jiji=wasmExports.dynCall_jiji)(r,e,t,n,s),_orig$ts_parser_timeout_micros=Module._orig$ts_parser_timeout_micros=r=>(_orig$ts_parser_timeout_micros=Module._orig$ts_parser_timeout_micros=wasmExports.orig$ts_parser_timeout_micros)(r),_orig$ts_parser_set_timeout_micros=Module._orig$ts_parser_set_timeout_micros=(r,e)=>(_orig$ts_parser_set_timeout_micros=Module._orig$ts_parser_set_timeout_micros=wasmExports.orig$ts_parser_set_timeout_micros)(r,e);Module.AsciiToString=AsciiToString,Module.stringToUTF16=stringToUTF16;var calledRun;dependenciesFulfilled=function r(){calledRun||run(),calledRun||(dependenciesFulfilled=r)};function callMain(r=[]){var e=resolveGlobalSymbol("main").sym;if(e){r.unshift(thisProgram);var t=r.length,n=stackAlloc((t+1)*4),s=n;r.forEach(a=>{LE_HEAP_STORE_U32((s>>2)*4,stringToUTF8OnStack(a)),s+=4}),LE_HEAP_STORE_U32((s>>2)*4,0);try{var o=e(t,n);return exitJS(o,!0),o}catch(a){return handleException(a)}}}function run(r=arguments_){if(runDependencies>0||(preRun(),runDependencies>0))return;function e(){calledRun||(calledRun=!0,Module.calledRun=!0,!ABORT&&(initRuntime(),preMain(),Module.onRuntimeInitialized?.(),shouldRunNow&&callMain(r),postRun()))}Module.setStatus?(Module.setStatus("Running..."),setTimeout(function(){setTimeout(function(){Module.setStatus("")},1),e()},1)):e()}if(Module.preInit)for(typeof Module.preInit=="function"&&(Module.preInit=[Module.preInit]);Module.preInit.length>0;)Module.preInit.pop()();var shouldRunNow=!0;Module.noInitialRun&&(shouldRunNow=!1),run();let C=Module,INTERNAL={},SIZE_OF_INT=4,SIZE_OF_CURSOR=4*SIZE_OF_INT,SIZE_OF_NODE=5*SIZE_OF_INT,SIZE_OF_POINT=2*SIZE_OF_INT,SIZE_OF_RANGE=2*SIZE_OF_INT+2*SIZE_OF_POINT,ZERO_POINT={row:0,column:0},QUERY_WORD_REGEX=/[\w-.]*/g,PREDICATE_STEP_TYPE_CAPTURE=1,PREDICATE_STEP_TYPE_STRING=2,LANGUAGE_FUNCTION_REGEX=/^_?tree_sitter_\w+/,VERSION,MIN_COMPATIBLE_VERSION,TRANSFER_BUFFER,currentParseCallback,currentLogCallback;class ParserImpl{static init(){TRANSFER_BUFFER=C._ts_init(),VERSION=getValue(TRANSFER_BUFFER,"i32"),MIN_COMPATIBLE_VERSION=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32")}initialize(){C._ts_parser_new_wasm(),this[0]=getValue(TRANSFER_BUFFER,"i32"),this[1]=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32")}delete(){C._ts_parser_delete(this[0]),C._free(this[1]),this[0]=0,this[1]=0}setLanguage(e){let t;if(!e)t=0,e=null;else if(e.constructor===Language){t=e[0];let n=C._ts_language_version(t);if(n<MIN_COMPATIBLE_VERSION||VERSION<n)throw new Error(`Incompatible language version ${n}. Compatibility range ${MIN_COMPATIBLE_VERSION} through ${VERSION}.`)}else throw new Error("Argument must be a Language");return this.language=e,C._ts_parser_set_language(this[0],t),this}getLanguage(){return this.language}parse(e,t,n){if(typeof e=="string")currentParseCallback=(c,u)=>e.slice(c);else if(typeof e=="function")currentParseCallback=e;else throw new Error("Argument must be a string or a function");this.logCallback?(currentLogCallback=this.logCallback,C._ts_parser_enable_logger_wasm(this[0],1)):(currentLogCallback=null,C._ts_parser_enable_logger_wasm(this[0],0));let s=0,o=0;if(n?.includedRanges){s=n.includedRanges.length,o=C._calloc(s,SIZE_OF_RANGE);let c=o;for(let u=0;u<s;u++)marshalRange(c,n.includedRanges[u]),c+=SIZE_OF_RANGE}let a=C._ts_parser_parse_wasm(this[0],this[1],t?t[0]:0,o,s);if(!a)throw currentParseCallback=null,currentLogCallback=null,new Error("Parsing failed");let l=new Tree(INTERNAL,a,this.language,currentParseCallback);return currentParseCallback=null,currentLogCallback=null,l}reset(){C._ts_parser_reset(this[0])}getIncludedRanges(){C._ts_parser_included_ranges_wasm(this[0]);let e=getValue(TRANSFER_BUFFER,"i32"),t=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32"),n=new Array(e);if(e>0){let s=t;for(let o=0;o<e;o++)n[o]=unmarshalRange(s),s+=SIZE_OF_RANGE;C._free(t)}return n}getTimeoutMicros(){return C._ts_parser_timeout_micros(this[0])}setTimeoutMicros(e){C._ts_parser_set_timeout_micros(this[0],e)}setLogger(e){if(!e)e=null;else if(typeof e!="function")throw new Error("Logger callback must be a function");return this.logCallback=e,this}getLogger(){return this.logCallback}}class Tree{constructor(e,t,n,s){assertInternal(e),this[0]=t,this.language=n,this.textCallback=s}copy(){let e=C._ts_tree_copy(this[0]);return new Tree(INTERNAL,e,this.language,this.textCallback)}delete(){C._ts_tree_delete(this[0]),this[0]=0}edit(e){marshalEdit(e),C._ts_tree_edit_wasm(this[0])}get rootNode(){return C._ts_tree_root_node_wasm(this[0]),unmarshalNode(this)}rootNodeWithOffset(e,t){let n=TRANSFER_BUFFER+SIZE_OF_NODE;return setValue(n,e,"i32"),marshalPoint(n+SIZE_OF_INT,t),C._ts_tree_root_node_with_offset_wasm(this[0]),unmarshalNode(this)}getLanguage(){return this.language}walk(){return this.rootNode.walk()}getChangedRanges(e){if(e.constructor!==Tree)throw new TypeError("Argument must be a Tree");C._ts_tree_get_changed_ranges_wasm(this[0],e[0]);let t=getValue(TRANSFER_BUFFER,"i32"),n=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32"),s=new Array(t);if(t>0){let o=n;for(let a=0;a<t;a++)s[a]=unmarshalRange(o),o+=SIZE_OF_RANGE;C._free(n)}return s}getIncludedRanges(){C._ts_tree_included_ranges_wasm(this[0]);let e=getValue(TRANSFER_BUFFER,"i32"),t=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32"),n=new Array(e);if(e>0){let s=t;for(let o=0;o<e;o++)n[o]=unmarshalRange(s),s+=SIZE_OF_RANGE;C._free(t)}return n}}class Node{constructor(e,t){assertInternal(e),this.tree=t}get typeId(){return marshalNode(this),C._ts_node_symbol_wasm(this.tree[0])}get grammarId(){return marshalNode(this),C._ts_node_grammar_symbol_wasm(this.tree[0])}get type(){return this.tree.language.types[this.typeId]||"ERROR"}get grammarType(){return this.tree.language.types[this.grammarId]||"ERROR"}get endPosition(){return marshalNode(this),C._ts_node_end_point_wasm(this.tree[0]),unmarshalPoint(TRANSFER_BUFFER)}get endIndex(){return marshalNode(this),C._ts_node_end_index_wasm(this.tree[0])}get text(){return getText(this.tree,this.startIndex,this.endIndex)}get parseState(){return marshalNode(this),C._ts_node_parse_state_wasm(this.tree[0])}get nextParseState(){return marshalNode(this),C._ts_node_next_parse_state_wasm(this.tree[0])}get isNamed(){return marshalNode(this),C._ts_node_is_named_wasm(this.tree[0])===1}get hasError(){return marshalNode(this),C._ts_node_has_error_wasm(this.tree[0])===1}get hasChanges(){return marshalNode(this),C._ts_node_has_changes_wasm(this.tree[0])===1}get isError(){return marshalNode(this),C._ts_node_is_error_wasm(this.tree[0])===1}get isMissing(){return marshalNode(this),C._ts_node_is_missing_wasm(this.tree[0])===1}get isExtra(){return marshalNode(this),C._ts_node_is_extra_wasm(this.tree[0])===1}equals(e){return this.id===e.id}child(e){return marshalNode(this),C._ts_node_child_wasm(this.tree[0],e),unmarshalNode(this.tree)}namedChild(e){return marshalNode(this),C._ts_node_named_child_wasm(this.tree[0],e),unmarshalNode(this.tree)}childForFieldId(e){return marshalNode(this),C._ts_node_child_by_field_id_wasm(this.tree[0],e),unmarshalNode(this.tree)}childForFieldName(e){let t=this.tree.language.fields.indexOf(e);return t!==-1?this.childForFieldId(t):null}fieldNameForChild(e){marshalNode(this);let t=C._ts_node_field_name_for_child_wasm(this.tree[0],e);return t?AsciiToString(t):null}childrenForFieldName(e){let t=this.tree.language.fields.indexOf(e);return t!==-1&&t!==0?this.childrenForFieldId(t):[]}childrenForFieldId(e){marshalNode(this),C._ts_node_children_by_field_id_wasm(this.tree[0],e);let t=getValue(TRANSFER_BUFFER,"i32"),n=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32"),s=new Array(t);if(t>0){let o=n;for(let a=0;a<t;a++)s[a]=unmarshalNode(this.tree,o),o+=SIZE_OF_NODE;C._free(n)}return s}firstChildForIndex(e){marshalNode(this);let t=TRANSFER_BUFFER+SIZE_OF_NODE;return setValue(t,e,"i32"),C._ts_node_first_child_for_byte_wasm(this.tree[0]),unmarshalNode(this.tree)}firstNamedChildForIndex(e){marshalNode(this);let t=TRANSFER_BUFFER+SIZE_OF_NODE;return setValue(t,e,"i32"),C._ts_node_first_named_child_for_byte_wasm(this.tree[0]),unmarshalNode(this.tree)}get childCount(){return marshalNode(this),C._ts_node_child_count_wasm(this.tree[0])}get namedChildCount(){return marshalNode(this),C._ts_node_named_child_count_wasm(this.tree[0])}get firstChild(){return this.child(0)}get firstNamedChild(){return this.namedChild(0)}get lastChild(){return this.child(this.childCount-1)}get lastNamedChild(){return this.namedChild(this.namedChildCount-1)}get children(){if(!this._children){marshalNode(this),C._ts_node_children_wasm(this.tree[0]);let e=getValue(TRANSFER_BUFFER,"i32"),t=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32");if(this._children=new Array(e),e>0){let n=t;for(let s=0;s<e;s++)this._children[s]=unmarshalNode(this.tree,n),n+=SIZE_OF_NODE;C._free(t)}}return this._children}get namedChildren(){if(!this._namedChildren){marshalNode(this),C._ts_node_named_children_wasm(this.tree[0]);let e=getValue(TRANSFER_BUFFER,"i32"),t=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32");if(this._namedChildren=new Array(e),e>0){let n=t;for(let s=0;s<e;s++)this._namedChildren[s]=unmarshalNode(this.tree,n),n+=SIZE_OF_NODE;C._free(t)}}return this._namedChildren}descendantsOfType(e,t,n){Array.isArray(e)||(e=[e]),t||(t=ZERO_POINT),n||(n=ZERO_POINT);let s=[],o=this.tree.language.types;for(let d=0,h=o.length;d<h;d++)e.includes(o[d])&&s.push(d);let a=C._malloc(SIZE_OF_INT*s.length);for(let d=0,h=s.length;d<h;d++)setValue(a+d*SIZE_OF_INT,s[d],"i32");marshalNode(this),C._ts_node_descendants_of_type_wasm(this.tree[0],a,s.length,t.row,t.column,n.row,n.column);let l=getValue(TRANSFER_BUFFER,"i32"),c=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32"),u=new Array(l);if(l>0){let d=c;for(let h=0;h<l;h++)u[h]=unmarshalNode(this.tree,d),d+=SIZE_OF_NODE}return C._free(c),C._free(a),u}get nextSibling(){return marshalNode(this),C._ts_node_next_sibling_wasm(this.tree[0]),unmarshalNode(this.tree)}get previousSibling(){return marshalNode(this),C._ts_node_prev_sibling_wasm(this.tree[0]),unmarshalNode(this.tree)}get nextNamedSibling(){return marshalNode(this),C._ts_node_next_named_sibling_wasm(this.tree[0]),unmarshalNode(this.tree)}get previousNamedSibling(){return marshalNode(this),C._ts_node_prev_named_sibling_wasm(this.tree[0]),unmarshalNode(this.tree)}get descendantCount(){return marshalNode(this),C._ts_node_descendant_count_wasm(this.tree[0])}get parent(){return marshalNode(this),C._ts_node_parent_wasm(this.tree[0]),unmarshalNode(this.tree)}descendantForIndex(e,t=e){if(typeof e!="number"||typeof t!="number")throw new Error("Arguments must be numbers");marshalNode(this);let n=TRANSFER_BUFFER+SIZE_OF_NODE;return setValue(n,e,"i32"),setValue(n+SIZE_OF_INT,t,"i32"),C._ts_node_descendant_for_index_wasm(this.tree[0]),unmarshalNode(this.tree)}namedDescendantForIndex(e,t=e){if(typeof e!="number"||typeof t!="number")throw new Error("Arguments must be numbers");marshalNode(this);let n=TRANSFER_BUFFER+SIZE_OF_NODE;return setValue(n,e,"i32"),setValue(n+SIZE_OF_INT,t,"i32"),C._ts_node_named_descendant_for_index_wasm(this.tree[0]),unmarshalNode(this.tree)}descendantForPosition(e,t=e){if(!isPoint(e)||!isPoint(t))throw new Error("Arguments must be {row, column} objects");marshalNode(this);let n=TRANSFER_BUFFER+SIZE_OF_NODE;return marshalPoint(n,e),marshalPoint(n+SIZE_OF_POINT,t),C._ts_node_descendant_for_position_wasm(this.tree[0]),unmarshalNode(this.tree)}namedDescendantForPosition(e,t=e){if(!isPoint(e)||!isPoint(t))throw new Error("Arguments must be {row, column} objects");marshalNode(this);let n=TRANSFER_BUFFER+SIZE_OF_NODE;return marshalPoint(n,e),marshalPoint(n+SIZE_OF_POINT,t),C._ts_node_named_descendant_for_position_wasm(this.tree[0]),unmarshalNode(this.tree)}walk(){return marshalNode(this),C._ts_tree_cursor_new_wasm(this.tree[0]),new TreeCursor(INTERNAL,this.tree)}toString(){marshalNode(this);let e=C._ts_node_to_string_wasm(this.tree[0]),t=AsciiToString(e);return C._free(e),t}}class TreeCursor{constructor(e,t){assertInternal(e),this.tree=t,unmarshalTreeCursor(this)}delete(){marshalTreeCursor(this),C._ts_tree_cursor_delete_wasm(this.tree[0]),this[0]=this[1]=this[2]=0}reset(e){marshalNode(e),marshalTreeCursor(this,TRANSFER_BUFFER+SIZE_OF_NODE),C._ts_tree_cursor_reset_wasm(this.tree[0]),unmarshalTreeCursor(this)}resetTo(e){marshalTreeCursor(this,TRANSFER_BUFFER),marshalTreeCursor(e,TRANSFER_BUFFER+SIZE_OF_CURSOR),C._ts_tree_cursor_reset_to_wasm(this.tree[0],e.tree[0]),unmarshalTreeCursor(this)}get nodeType(){return this.tree.language.types[this.nodeTypeId]||"ERROR"}get nodeTypeId(){return marshalTreeCursor(this),C._ts_tree_cursor_current_node_type_id_wasm(this.tree[0])}get nodeStateId(){return marshalTreeCursor(this),C._ts_tree_cursor_current_node_state_id_wasm(this.tree[0])}get nodeId(){return marshalTreeCursor(this),C._ts_tree_cursor_current_node_id_wasm(this.tree[0])}get nodeIsNamed(){return marshalTreeCursor(this),C._ts_tree_cursor_current_node_is_named_wasm(this.tree[0])===1}get nodeIsMissing(){return marshalTreeCursor(this),C._ts_tree_cursor_current_node_is_missing_wasm(this.tree[0])===1}get nodeText(){marshalTreeCursor(this);let e=C._ts_tree_cursor_start_index_wasm(this.tree[0]),t=C._ts_tree_cursor_end_index_wasm(this.tree[0]);return getText(this.tree,e,t)}get startPosition(){return marshalTreeCursor(this),C._ts_tree_cursor_start_position_wasm(this.tree[0]),unmarshalPoint(TRANSFER_BUFFER)}get endPosition(){return marshalTreeCursor(this),C._ts_tree_cursor_end_position_wasm(this.tree[0]),unmarshalPoint(TRANSFER_BUFFER)}get startIndex(){return marshalTreeCursor(this),C._ts_tree_cursor_start_index_wasm(this.tree[0])}get endIndex(){return marshalTreeCursor(this),C._ts_tree_cursor_end_index_wasm(this.tree[0])}get currentNode(){return marshalTreeCursor(this),C._ts_tree_cursor_current_node_wasm(this.tree[0]),unmarshalNode(this.tree)}get currentFieldId(){return marshalTreeCursor(this),C._ts_tree_cursor_current_field_id_wasm(this.tree[0])}get currentFieldName(){return this.tree.language.fields[this.currentFieldId]}get currentDepth(){return marshalTreeCursor(this),C._ts_tree_cursor_current_depth_wasm(this.tree[0])}get currentDescendantIndex(){return marshalTreeCursor(this),C._ts_tree_cursor_current_descendant_index_wasm(this.tree[0])}gotoFirstChild(){marshalTreeCursor(this);let e=C._ts_tree_cursor_goto_first_child_wasm(this.tree[0]);return unmarshalTreeCursor(this),e===1}gotoLastChild(){marshalTreeCursor(this);let e=C._ts_tree_cursor_goto_last_child_wasm(this.tree[0]);return unmarshalTreeCursor(this),e===1}gotoFirstChildForIndex(e){marshalTreeCursor(this),setValue(TRANSFER_BUFFER+SIZE_OF_CURSOR,e,"i32");let t=C._ts_tree_cursor_goto_first_child_for_index_wasm(this.tree[0]);return unmarshalTreeCursor(this),t===1}gotoFirstChildForPosition(e){marshalTreeCursor(this),marshalPoint(TRANSFER_BUFFER+SIZE_OF_CURSOR,e);let t=C._ts_tree_cursor_goto_first_child_for_position_wasm(this.tree[0]);return unmarshalTreeCursor(this),t===1}gotoNextSibling(){marshalTreeCursor(this);let e=C._ts_tree_cursor_goto_next_sibling_wasm(this.tree[0]);return unmarshalTreeCursor(this),e===1}gotoPreviousSibling(){marshalTreeCursor(this);let e=C._ts_tree_cursor_goto_previous_sibling_wasm(this.tree[0]);return unmarshalTreeCursor(this),e===1}gotoDescendant(e){marshalTreeCursor(this),C._ts_tree_cursor_goto_descendant_wasm(this.tree[0],e),unmarshalTreeCursor(this)}gotoParent(){marshalTreeCursor(this);let e=C._ts_tree_cursor_goto_parent_wasm(this.tree[0]);return unmarshalTreeCursor(this),e===1}}class Language{constructor(e,t){assertInternal(e),this[0]=t,this.types=new Array(C._ts_language_symbol_count(this[0]));for(let n=0,s=this.types.length;n<s;n++)C._ts_language_symbol_type(this[0],n)<2&&(this.types[n]=UTF8ToString(C._ts_language_symbol_name(this[0],n)));this.fields=new Array(C._ts_language_field_count(this[0])+1);for(let n=0,s=this.fields.length;n<s;n++){let o=C._ts_language_field_name_for_id(this[0],n);o!==0?this.fields[n]=UTF8ToString(o):this.fields[n]=null}}get version(){return C._ts_language_version(this[0])}get fieldCount(){return this.fields.length-1}get stateCount(){return C._ts_language_state_count(this[0])}fieldIdForName(e){let t=this.fields.indexOf(e);return t!==-1?t:null}fieldNameForId(e){return this.fields[e]||null}idForNodeType(e,t){let n=lengthBytesUTF8(e),s=C._malloc(n+1);stringToUTF8(e,s,n+1);let o=C._ts_language_symbol_for_name(this[0],s,n,t);return C._free(s),o||null}get nodeTypeCount(){return C._ts_language_symbol_count(this[0])}nodeTypeForId(e){let t=C._ts_language_symbol_name(this[0],e);return t?UTF8ToString(t):null}nodeTypeIsNamed(e){return!!C._ts_language_type_is_named_wasm(this[0],e)}nodeTypeIsVisible(e){return!!C._ts_language_type_is_visible_wasm(this[0],e)}nextState(e,t){return C._ts_language_next_state(this[0],e,t)}lookaheadIterator(e){let t=C._ts_lookahead_iterator_new(this[0],e);return t?new LookaheadIterable(INTERNAL,t,this):null}query(e){let t=lengthBytesUTF8(e),n=C._malloc(t+1);stringToUTF8(e,n,t+1);let s=C._ts_query_new(this[0],n,t,TRANSFER_BUFFER,TRANSFER_BUFFER+SIZE_OF_INT);if(!s){let w=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32"),m=getValue(TRANSFER_BUFFER,"i32"),_=UTF8ToString(n,m).length,b=e.substr(_,100).split(`
4
4
  `)[0],v=b.match(QUERY_WORD_REGEX)[0],S;switch(w){case 2:S=new RangeError(`Bad node name '${v}'`);break;case 3:S=new RangeError(`Bad field name '${v}'`);break;case 4:S=new RangeError(`Bad capture name @${v}`);break;case 5:S=new TypeError(`Bad pattern structure at offset ${_}: '${b}'...`),v="";break;default:S=new SyntaxError(`Bad syntax at offset ${_}: '${b}'...`),v="";break}throw S.index=_,S.length=v.length,C._free(n),S}let o=C._ts_query_string_count(s),a=C._ts_query_capture_count(s),l=C._ts_query_pattern_count(s),c=new Array(a),u=new Array(o);for(let w=0;w<a;w++){let m=C._ts_query_capture_name_for_id(s,w,TRANSFER_BUFFER),_=getValue(TRANSFER_BUFFER,"i32");c[w]=UTF8ToString(m,_)}for(let w=0;w<o;w++){let m=C._ts_query_string_value_for_id(s,w,TRANSFER_BUFFER),_=getValue(TRANSFER_BUFFER,"i32");u[w]=UTF8ToString(m,_)}let d=new Array(l),h=new Array(l),f=new Array(l),p=new Array(l),y=new Array(l);for(let w=0;w<l;w++){let m=C._ts_query_predicates_for_pattern(s,w,TRANSFER_BUFFER),_=getValue(TRANSFER_BUFFER,"i32");p[w]=[],y[w]=[];let b=[],v=m;for(let S=0;S<_;S++){let T=getValue(v,"i32");v+=SIZE_OF_INT;let E=getValue(v,"i32");if(v+=SIZE_OF_INT,T===PREDICATE_STEP_TYPE_CAPTURE)b.push({type:"capture",name:c[E]});else if(T===PREDICATE_STEP_TYPE_STRING)b.push({type:"string",value:u[E]});else if(b.length>0){if(b[0].type!=="string")throw new Error("Predicates must begin with a literal value");let x=b[0].value,k=!0,P=!0,B;switch(x){case"any-not-eq?":case"not-eq?":k=!1;case"any-eq?":case"eq?":if(b.length!==3)throw new Error(`Wrong number of arguments to \`#${x}\` predicate. Expected 2, got ${b.length-1}`);if(b[1].type!=="capture")throw new Error(`First argument of \`#${x}\` predicate must be a capture. Got "${b[1].value}"`);if(P=!x.startsWith("any-"),b[2].type==="capture"){let j=b[1].name,z=b[2].name;y[w].push(W=>{let K=[],G=[];for(let M of W)M.name===j&&K.push(M.node),M.name===z&&G.push(M.node);let A=(M,O,D)=>D?M.text===O.text:M.text!==O.text;return P?K.every(M=>G.some(O=>A(M,O,k))):K.some(M=>G.some(O=>A(M,O,k)))})}else{B=b[1].name;let j=b[2].value,z=K=>K.text===j,W=K=>K.text!==j;y[w].push(K=>{let G=[];for(let M of K)M.name===B&&G.push(M.node);let A=k?z:W;return P?G.every(A):G.some(A)})}break;case"any-not-match?":case"not-match?":k=!1;case"any-match?":case"match?":if(b.length!==3)throw new Error(`Wrong number of arguments to \`#${x}\` predicate. Expected 2, got ${b.length-1}.`);if(b[1].type!=="capture")throw new Error(`First argument of \`#${x}\` predicate must be a capture. Got "${b[1].value}".`);if(b[2].type!=="string")throw new Error(`Second argument of \`#${x}\` predicate must be a string. Got @${b[2].value}.`);B=b[1].name;let L=new RegExp(b[2].value);P=!x.startsWith("any-"),y[w].push(j=>{let z=[];for(let K of j)K.name===B&&z.push(K.node.text);let W=(K,G)=>G?L.test(K):!L.test(K);return z.length===0?!k:P?z.every(K=>W(K,k)):z.some(K=>W(K,k))});break;case"set!":if(b.length<2||b.length>3)throw new Error(`Wrong number of arguments to \`#set!\` predicate. Expected 1 or 2. Got ${b.length-1}.`);if(b.some(j=>j.type!=="string"))throw new Error('Arguments to `#set!` predicate must be a strings.".');d[w]||(d[w]={}),d[w][b[1].value]=b[2]?b[2].value:null;break;case"is?":case"is-not?":if(b.length<2||b.length>3)throw new Error(`Wrong number of arguments to \`#${x}\` predicate. Expected 1 or 2. Got ${b.length-1}.`);if(b.some(j=>j.type!=="string"))throw new Error(`Arguments to \`#${x}\` predicate must be a strings.".`);let $=x==="is?"?h:f;$[w]||($[w]={}),$[w][b[1].value]=b[2]?b[2].value:null;break;case"not-any-of?":k=!1;case"any-of?":if(b.length<2)throw new Error(`Wrong number of arguments to \`#${x}\` predicate. Expected at least 1. Got ${b.length-1}.`);if(b[1].type!=="capture")throw new Error(`First argument of \`#${x}\` predicate must be a capture. Got "${b[1].value}".`);for(let j=2;j<b.length;j++)if(b[j].type!=="string")throw new Error(`Arguments to \`#${x}\` predicate must be a strings.".`);B=b[1].name;let q=b.slice(2).map(j=>j.value);y[w].push(j=>{let z=[];for(let W of j)W.name===B&&z.push(W.node.text);return z.length===0?!k:z.every(W=>q.includes(W))===k});break;default:p[w].push({operator:x,operands:b.slice(1)})}b.length=0}}Object.freeze(d[w]),Object.freeze(h[w]),Object.freeze(f[w])}return C._free(n),new Query(INTERNAL,s,c,y,p,Object.freeze(d),Object.freeze(h),Object.freeze(f))}static load(e){let t;if(e instanceof Uint8Array)t=Promise.resolve(e);else{let n=e;if(typeof process<"u"&&process.versions&&process.versions.node){let s=Se("fs");t=Promise.resolve(s.readFileSync(n))}else t=fetch(n).then(s=>s.arrayBuffer().then(o=>{if(s.ok)return new Uint8Array(o);{let a=new TextDecoder("utf-8").decode(o);throw new Error(`Language.load failed with status ${s.status}.
5
5
 
6
6
  ${a}`)}}))}return t.then(n=>loadWebAssemblyModule(n,{loadAsync:!0})).then(n=>{let s=Object.keys(n),o=s.find(l=>LANGUAGE_FUNCTION_REGEX.test(l)&&!l.includes("external_scanner_"));o||console.log(`Couldn't find language function in WASM file. Symbols:
@@ -2196,7 +2196,7 @@ ${jd(r)}
2196
2196
  The current date is: ${K}. Note: This is the authoritative current date \u2014 it may differ from the "Today's date" mentioned earlier in the conversation startup context.
2197
2197
  </system-reminder>`),this.lastInjectedDate=K)}this.config.getApprovalMode()==="plan"&&j.push(Yv(this.config.getSdkMode()));let z=this.config.getArenaManager();if(z)try{let G=`${z.getArenaSessionDir()}/config.json`;j.push(gG(G))}catch{}let W=await this.tryConsumeMemoryPrefetch();W?.prompt&&j.unshift(W.prompt),k=[...j,...k]}if(a==="toolResult"){let j=await this.tryConsumeMemoryPrefetch();j?.prompt&&(k=[...k,j.prompt]),await this.microcompactHistoryBeforeSend(null,{sizeOnly:!0,pendingContent:Yn(k)})}let P=Bd(this.config.getSessionId());P&&(yield{type:"active_goal",value:P});let B=P,L=j=>{if(!PP(B,j))return B=j,{type:"active_goal",value:j??null}},$=a==="hook"?E.run(x,k,t,e):E.run(x,k,t),q=!1;for await(let j of $){S&&!q&&(this.lastSentIdeContext=v,this.forceFullIdeContext=!1,q=!0);let z=this.config.getSkipLoopDetection(),W=!z&&this.loopDetector.addAndCheckDeterministicToolCallLoop(j),K=!W&&!z&&this.loopDetector.addAndCheckHeuristicLoops(j);if(W||K){let G=this.loopDetector.getLastLoopType();if(j.type==="tool_call_request"&&G==="consecutive_identical_tool_calls"){let A=this.loopDetector.getConsecutiveToolCallCount(),M=Math.max(0,E.pendingToolCalls.length-A);E.pendingToolCalls.splice(M)}return yield{type:"loop_detected",...G&&{value:{loopType:G}}},T&&await T.reportError("Loop detected"),this.lastApiCompletionTimestamp=Date.now(),u&&kn("error",{errorMessage:"loop detected"}),this.cancelPendingMemoryPrefetch(),E}if(T&&j.type==="finished"&&await T.updateStatus(),j.type==="chat_compressed"&&j.value?.compressionStatus===1){this.forceFullIdeContext=!0;try{await this.restoreStartupContextAfterCompaction()}catch(G){this.config.getDebugLogger().warn(`Failed to restore startup context after compaction: ${G}`)}this.fireSessionStartHook("compact").then(G=>{!G||!this.chat||(this.lastSessionStartContext=G,this.lastSessionStartSource="compact",this.chat.applySessionStartContext(G,"compact"))}).catch(G=>{this.config.getDebugLogger().warn(`SessionStart hook failed: ${G}`)})}if(yield j,j.type==="error"){if(this.forceFullIdeContext=!0,T){let G=j.value instanceof Error?j.value.message:"Unknown error";await T.reportError(G)}if(this.lastApiCompletionTimestamp=Date.now(),u){let G=j.value instanceof Error?"[API error]":"unknown error";kn("error",{errorMessage:G})}return this.cancelPendingMemoryPrefetch(),E}}if(this.lastApiCompletionTimestamp=Date.now(),l&&c&&!E.pendingToolCalls.length&&!Et.current?.pending&&t&&!t.aborted&&this.config.hasHooksForEvent("Stop")){let j=this.getLastModelMessageText()||"[no response text]",z=await c.request({type:"hook-execution-request",eventName:"Stop",input:{stop_hook_active:!0,last_assistant_message:j},signal:t},"hook-execution-response"),W=Bd(this.config.getSessionId());if(t.aborted){let M=L(W);return M&&(yield M),u&&kn("cancelled"),E}let G=z.output?ct("Stop",z.output):void 0;if(G?.systemMessage&&(yield{type:"hook_system_message",value:G.systemMessage}),G?.isBlockingDecision()||G?.shouldStopExecution()){if(t.aborted){let V=L(W);return V&&(yield V),u&&kn("cancelled"),E}let M=G.getEffectiveReason(),O=++f.iterationCount,D=[...f.reasons,M];f.reasons=D;let H=this.config.getStopHookBlockingCap();if(O>=H){let V=jc("Stop",H);MP(this.config,this.config.getSessionId(),V);let Z=Bd(this.config.getSessionId()),Q=L(Z);throw Q&&(yield Q),tt.warn(V),new Aj(V)}let X=L(W);X&&(yield X),yield{type:"stop_hook_loop",value:{iterationCount:O,reasons:D,stopHookCount:z.stopHookCount??1}};let te=[{text:M}],ee=Bd(this.config.getSessionId())?p:p-1,I=yield*this.sendMessageStream(te,t,n,{type:"hook",modelOverride:s?.modelOverride},ee);return u&&kn(t.aborted?"cancelled":"ok"),d=!0,I}let A=L(W);A&&(yield A)}if(!E.pendingToolCalls.length&&t&&!t.aborted){try{let M=this.getChat(),D=this.getHistoryTailShallow(40,!0);Que(M.getGenerationConfig(),D,this.config.getModel())}catch{}let j=this.config.getApprovalMode(),z=vq(j)||j==="plan",W=this.getChat().getLastHistoryEntry?.(),K=uj(W),G=MR(W)||K||!!W&&PR(W);if(this.config.getSkipNextSpeakerCheck()&&!z&&!G)return this.runManagedAutoMemoryBackgroundTasks(a),T&&await T.reportCompleted(),u&&kn("ok"),E;let A=await Dde(this.getChat(),this.config,t,n);if(R2(this.config,new W2(n,E.finishReason?.toString()||"",A?.next_speaker||"")),A?.next_speaker==="model"){let M=[{text:MR(W)?"Please continue with a user-visible response. Do not only think silently \u2014 summarize results or take the next concrete action.":K?"You announced a next action but did not call a tool. Call the appropriate tool now (e.g. enter_plan_mode, or a read-only investigation tool). Do not only restate your intent.":"Please continue."}],O=yield*this.sendMessageStream(M,t,n,{...s,type:"hook"},p-1);return u&&kn(t.aborted?"cancelled":"ok"),d=!0,O}this.runManagedAutoMemoryBackgroundTasks(a),T&&await T.reportCompleted()}return t?.aborted&&T&&await T.reportCancelled(),u&&kn(t?.aborted?"cancelled":"ok"),d=!0,E}finally{d||this.cancelPendingMemoryPrefetch(),u&&kn(t?.aborted?"cancelled":"error",{errorMessage:"unexpected exit"})}}async generateContent(e,t,n,s,o){let a=o??wE.getStore()??this.lastPromptId,l=s;try{let c=this.config.getUserMemory(),u=t.systemInstruction?Mm(t.systemInstruction,c):this.getMainSessionSystemInstruction(),d={abortSignal:n,...t,systemInstruction:u},{contentGenerator:h,retryAuthType:f,retryErrorCodes:p,model:y}=await this.config.getBaseLlmClient().resolveForModel(s);return await Uc(()=>(l=y,h.generateContent({model:y,config:d,contents:e},a)),{authType:f,extraRetryErrorCodes:p,persistentMode:$c(),signal:n,heartbeatFn:_=>{dj.stderr.write(`[matilda-code] Waiting for API capacity... attempt ${_.attempt}, retry in ${Math.ceil(_.remainingMs/1e3)}s
2198
2198
  `)},onRetry:_=>{Ac(this.config,new Mc({model:l,promptId:a,attemptNumber:_.attempt,error:_.error,statusCode:_.errorStatus,retryDelayMs:_.delayMs,subagentName:Do.getStore()}))}})}catch(c){throw n.aborted?c:(await ji(c,`Error generating content via API with model ${l}.`,{requestContents:e,requestConfig:t},"generateContent-api"),new Error(`Failed to generate content with model ${l}: ${ne(c)}`))}}async tryCompressChat(e,t=!1,n,s,o){let a=this.lastSessionStartContext,l=this.lastSessionStartSource,c=await this.getChat().tryCompress(e,this.config.getModel(),t,n,s||o?{customInstructions:s,pendingCommittedMessage:o}:void 0);if(c.compressionStatus===1){let u=this.getChat(),d=u.getHistoryShallow?.()??u.getHistory();await this.startChat(d,"compact"),!this.lastSessionStartContext&&a&&l&&(this.lastSessionStartContext=a,this.lastSessionStartSource=l,this.getChat().applySessionStartContext(a,l)),tt.debug("[FILE_READ_CACHE] clear after tryCompressChat"),this.config.getFileReadCache().clear(),this.getChat().setLastPromptTokenCount(c.newTokenCount),this.forceFullIdeContext=!0}return c}async disarmFileReadCacheAfterEviction(e,t){let n=this.config.getFileReadCache();if(e.unresolvedEvictedReads>0){tt.debug(`[FILE_READ_CACHE] clear after ${t} (${e.unresolvedEvictedReads} unresolved blanked read(s))`),n.clear();return}if(e.evictedReadPaths.length===0)return;let s=await Promise.all(e.evictedReadPaths.map(a=>l5e.stat(a).catch(()=>{}))),o=!0;for(let a of s)(!a||!n.markReadEvictedFromHistory(a))&&(o=!1);o?tt.debug(`[FILE_READ_CACHE] disarmed fast-path for ${e.evictedReadPaths.length} file(s) after ${t}`):(tt.debug(`[FILE_READ_CACHE] clear after ${t} (an evicted path was unresolvable)`),n.clear())}async tryCompressChatFast(){let{info:e,microcompactMeta:t}=this.getChat().compressFast();return e.compressionStatus!==1||(t&&await this.disarmFileReadCacheAfterEviction(t,"compress-fast"),this.forceFullIdeContext=!0),e}};g();import*as Kp from"node:fs/promises";import*as Lde from"node:path";var Ad=F("WORKTREE_CLEANUP"),g5e=[MN],y5e=30*24*60*60*1e3;function w5e(r){return g5e.some(e=>e.test(r))}async function Nde(r,e={}){let t=e.cutoffMs??y5e,n=Date.now()-t,s=new us(r),o=s.getUserWorktreesDir();try{await Kp.access(o)}catch{return 0}let a;try{a=await Kp.readdir(o,{withFileTypes:!0})}catch(c){return c.code==="ENOENT"||Ad.warn(`Failed to read ${o}: ${c}`),0}let l=0;for(let c of a){if(!c.isDirectory()||!w5e(c.name))continue;let u=Lde.join(o,c.name),d;try{d=(await Kp.stat(u)).mtimeMs}catch(y){y.code!=="ENOENT"&&Ad.warn(`cleanupStaleAgentWorktrees: cannot stat ${u} \u2014 skipping: ${y}`);continue}if(d>=n)continue;let[h,f]=await Promise.all([_5e(u),s.hasUnmergedWorktreeCommits(c.name)]);if(h||f)continue;let p=await s.removeUserWorktree(c.name,{deleteBranch:!0});if(!p.success){Ad.warn(`Failed to remove stale agent worktree ${u}: ${p.error}`);continue}p.branchPreserved?Ad.warn(`Removed stale agent worktree ${u} but kept branch ${ow(c.name)} (unmerged commits at delete time)`):Ad.debug(`Removed stale agent worktree ${u}`),l+=1}return l>0&&Ad.debug(`cleanupStaleAgentWorktrees: removed ${l} stale worktree(s)`),l}async function _5e(r){try{return(await sn(r).raw(["status","--porcelain","--untracked-files=no"])).trim().length>0}catch(e){return Ad.warn(`hasTrackedChanges: cannot inspect ${r} \u2014 assuming dirty: ${e}`),!0}}g();import*as Yp from"node:os";import{readFileSync as v5e}from"node:fs";import{EventEmitter as S5e}from"node:events";import{getHeapStatistics as Ude}from"node:v8";g();import*as Ub from"node:fs";import*as fj from"node:path";import*as $de from"node:v8";var $b=F("MEMORY_DUMP"),Fde=3,b5e=3e4,OR=class{constructor(e){this.config=e}dumpCount=0;lastDumpTime=0;resetForNewSession(){this.dumpCount=0,this.lastDumpTime=0}async dump(e,t=[]){if(this.dumpCount>=Fde){$b.debug(`Skipping dump: session cap reached (${Fde})`);return}let n=Date.now();if(n-this.lastDumpTime<b5e){$b.debug("Skipping dump: cooldown not elapsed");return}let s=++this.dumpCount;this.lastDumpTime=n;try{let o=this.ensureDiagnosticsDir(),a=this.config.getSessionId(),l=new Date().toISOString().replace(/:/g,"-").replace(/\./g,"_"),c=`memory-${a.slice(0,8)}-${l}.json`,u=fj.join(o,c),d=t[t.length-1],h=d?{rss:d.rss,heapUsed:d.heapUsed,heapTotal:d.heapTotal,external:d.external,arrayBuffers:0}:process.memoryUsage(),f={trigger:e,dumpNumber:s,timestamp:new Date().toISOString(),memoryUsage:h,v8HeapStats:$de.getHeapStatistics(),recentSamples:t,session:this.collectSessionStats(),suggestion:this.getSuggestion(e),collectionComplete:!1};Ub.writeFileSync(u,JSON.stringify(f,null,2),"utf8"),$b.info(`Phase 1 diagnostics written to ${u} (trigger=${e}, dump #${s})`);let p=await jce({sessionId:a,matildaVersion:this.config.getCliVersion()}),y={trigger:e,dumpNumber:s,...p,recentSamples:t,session:this.collectSessionStats(),suggestion:this.getSuggestion(e),collectionComplete:!0};return Ub.writeFileSync(u,JSON.stringify(y,null,2),"utf8"),$b.info(`Phase 2 diagnostics written to ${u} (trigger=${e}, dump #${s})`),{filePath:u,trigger:e}}catch(o){$b.error(`Failed to write memory diagnostics: ${ne(o)}`);return}}ensureDiagnosticsDir(){let e=this.config.storage.getProjectDir(),t=fj.join(e,"diagnostics");return Ub.mkdirSync(t,{recursive:!0}),t}collectSessionStats(){try{let e=this.config.getGeminiClient?.();return e?{historyEntries:e.getChat?.()?.getHistoryLength?.()??0}:{available:!1}}catch{return{available:!1}}}getSuggestion(e){return e==="critical"?"Memory is critically high. Consider running /compress or starting a fresh session to avoid OOM.":"Memory pressure detected. Running /compress may help reduce memory usage."}};var C5e=60,Rd;function T5e(){if(Rd===void 0){try{Rd=Yp.availableParallelism?.()??Yp.cpus().length??1}catch{Rd=1}(!Rd||Rd<1)&&(Rd=1)}return Rd}function pj(){try{return process.cpuUsage()}catch{return{user:0,system:0}}}var mj=class{samples=[];prevCpuUsage=pj();prevSampleTime=Date.now();record(e){let t=Date.now(),n=t-this.prevSampleTime,s=pj(),o=s.user-this.prevCpuUsage.user,a=s.system-this.prevCpuUsage.system,l=o+a;if(n<=0){let u=this.samples[this.samples.length-1];return this.push({ts:t,rss:e.rss,heapUsed:e.heapUsed,heapTotal:e.heapTotal,external:e.external,cpuPercent:u?.cpuPercent??0})}let c=Math.min(100,Math.max(0,l/(n*1e3)*100/T5e()));return this.prevCpuUsage=s,this.prevSampleTime=t,this.push({ts:t,rss:e.rss,heapUsed:e.heapUsed,heapTotal:e.heapTotal,external:e.external,cpuPercent:Math.round(c*100)/100})}push(e){return this.samples.push(e),this.samples.length>C5e&&this.samples.shift(),e}getAll(){return[...this.samples]}reset(){this.samples.length=0,this.prevCpuUsage=pj(),this.prevSampleTime=Date.now()}},DR={softPressureRatio:.5,hardPressureRatio:.65,criticalRatio:.8,cleanupCooldownMs:5e3,enableExplicitGC:!0};function yj(r){for(let[e,t]of[["softPressureRatio",r.softPressureRatio],["hardPressureRatio",r.hardPressureRatio],["criticalRatio",r.criticalRatio]])if(!Number.isFinite(t)||t<.3||t>.98)throw new Error(`${e} must be a finite ratio in [0.3, 0.98]`);if(r.softPressureRatio>=r.hardPressureRatio)throw new Error("softPressureRatio must be < hardPressureRatio");if(r.hardPressureRatio>=r.criticalRatio)throw new Error("hardPressureRatio must be < criticalRatio");if(!Number.isFinite(r.cleanupCooldownMs)||r.cleanupCooldownMs<0)throw new Error("cleanupCooldownMs must be a non-negative number")}var at=F("MEMORY_PRESSURE"),E5e=64*1024*1024,jb=class extends S5e{config;coreConfig;pendingCheck=!1;cleanupInProgress=!1;hasLoggedSamplingError=!1;activeCleanupAction="none";lastCleanupAction="none";queuedCleanupRecommendation;lastCleanupTime=0;consecutiveCleanupFailures=0;consecutiveIneffectiveCleanups=0;consecutiveIneffectiveAggressiveCleanups=0;cleanupGeneration=0;effectiveMemoryLimit;diagnosticsDumper;runtimeSamples=new mj;constructor(e,t){super(),this.coreConfig=e,this.config={...t??DR},yj(this.config),this.effectiveMemoryLimit=this.computeEffectiveMemoryLimit(),this.diagnosticsDumper=new OR(e);let n=Ude().heap_size_limit;at.info(`Effective memory limit: ${Bb(this.effectiveMemoryLimit)} MiB; V8 heap limit: ${Bb(n)} MiB`),this.effectiveMemoryLimit<=0&&at.warn("Effective memory limit is not positive; RSS pressure checks are disabled")}getConsecutiveFailures(){return this.consecutiveCleanupFailures}resetConsecutiveFailures(){this.consecutiveCleanupFailures=0,this.consecutiveIneffectiveCleanups=0,this.consecutiveIneffectiveAggressiveCleanups=0}resetForNewSession(){this.cleanupGeneration++,this.resetConsecutiveFailures(),this.diagnosticsDumper.resetForNewSession(),this.runtimeSamples.reset(),this.cleanupInProgress=!1,this.activeCleanupAction="none",this.queuedCleanupRecommendation=void 0,this.lastCleanupAction="none",this.lastCleanupTime=0}scheduleCheck(){this.pendingCheck||(this.pendingCheck=!0,queueMicrotask(()=>{try{this.performCheck()}finally{this.pendingCheck=!1}}))}performCheck(){try{this.performCheckInternal()}catch(e){at.error(`Memory pressure check failed: ${ne(e)}`)}}performCheckInternal(){let e=this.readMemoryUsage(),t=e?this.getPressureLevel(e):"normal";if(t!=="critical"&&(this.consecutiveIneffectiveAggressiveCleanups=0),e)try{let l=this.runtimeSamples.record(e);i2()&&(ZR(this.coreConfig,l.rss,{memory_type:"rss"}),ZR(this.coreConfig,l.heapUsed,{memory_type:"heap_used"}),s2(this.coreConfig,l.cpuPercent,{}))}catch(l){let c=`Runtime sampling failed: ${ne(l)}`;this.hasLoggedSamplingError?at.debug(c):(this.hasLoggedSamplingError=!0,at.error(c))}if(t==="normal")return;let n=this.recommendCleanup(t);if(n.action==="none")return;let s=Date.now(),o=Hb(n.action)>Hb(this.lastCleanupAction),a=this.getCleanupCooldownMs(n.action);!o&&s-this.lastCleanupTime<a||((t==="hard"||t==="critical")&&this.diagnosticsDumper.dump(t,this.runtimeSamples.getAll()),this.executeCleanup(n))}readMemoryUsage(){try{return process.memoryUsage()}catch(e){at.error(`Failed to read memory usage for pressure check: ${ne(e)}`);return}}getPressureLevel(e){let t=e??this.readMemoryUsage();if(!t)return"normal";let n=this.effectiveMemoryLimit>0?t.rss/this.effectiveMemoryLimit:0,s=Ude().heap_size_limit,o=s>0?t.heapUsed/s:0,a=Math.max(n,o);return a>=this.config.criticalRatio?"critical":a>=this.config.hardPressureRatio?"hard":a>=this.config.softPressureRatio?"soft":"normal"}recommendCleanup(e){switch(e){case"critical":return{action:"aggressive",steps:["evict_cold_cache","compact_history","clear_file_cache",...this.config.enableExplicitGC?["trigger_gc"]:[]]};case"hard":return{action:"moderate",steps:["evict_cold_cache","compact_history","clear_file_cache"]};case"soft":return{action:"light",steps:["evict_stale_cache"]};default:return gj(e)}}executeCleanup(e){if(this.cleanupInProgress){let s=Hb(e.action),o=Hb(this.activeCleanupAction),a=this.queuedCleanupRecommendation?Hb(this.queuedCleanupRecommendation.action):0;s>o&&s>a?(this.queuedCleanupRecommendation=e,at.debug(`Queued escalated cleanup "${e.action}" while "${this.activeCleanupAction}" is in progress`)):at.debug("Cleanup already in progress, skipping");return}let t;try{t=process.memoryUsage().rss}catch(s){this.recordCleanupFailure(e,s);return}this.cleanupInProgress=!0,this.activeCleanupAction=e.action,this.lastCleanupAction=e.action,this.lastCleanupTime=Date.now();let n=this.cleanupGeneration;this.runCleanupSteps(e.steps,n).then(()=>{n===this.cleanupGeneration&&(this.consecutiveCleanupFailures=0,setImmediate(()=>{if(n===this.cleanupGeneration)try{let s=process.memoryUsage().rss;this.logCleanupResult(t,s,e)}catch(s){at.error(`Cleanup measurement failed: ${ne(s)}`)}finally{this.finishCleanupAndRunQueued(n)}}))}).catch(s=>{n===this.cleanupGeneration&&(this.recordCleanupFailure(e,s),this.finishCleanupAndRunQueued(n))})}finishCleanupAndRunQueued(e){if(e!==this.cleanupGeneration)return;this.cleanupInProgress=!1,this.activeCleanupAction="none";let t=this.queuedCleanupRecommendation;if(this.queuedCleanupRecommendation=void 0,t)try{this.executeCleanup(t)}catch(n){this.recordCleanupFailure(t,n)}}getCleanupCooldownMs(e){let t=this.config.cleanupCooldownMs;if(e!=="aggressive"||t===0||this.consecutiveIneffectiveAggressiveCleanups<3)return t;let n=Math.min(this.consecutiveIneffectiveAggressiveCleanups-2,6);return t*2**n}logCleanupResult(e,t,n){let s=e-t,o=e>0?s/e:0;if(at.info(`Cleanup "${n.action}" completed; RSS delta ${s} bytes (${(o*100).toFixed(1)}%)`),o<.01){if(this.consecutiveIneffectiveCleanups++,n.action==="aggressive"&&this.consecutiveIneffectiveAggressiveCleanups++,Hde(this.consecutiveIneffectiveCleanups)){let a={rss:t,freedBytes:s,freedRatio:o,consecutiveIneffectiveCleanups:this.consecutiveIneffectiveCleanups,recommendation:n};at.warn(`Cleanup "${n.action}" has been ineffective ${this.consecutiveIneffectiveCleanups} times consecutively`),this.emitSafely("memory-cleanup-ineffective",a)}return}this.consecutiveIneffectiveCleanups=0,n.action==="aggressive"&&(this.consecutiveIneffectiveAggressiveCleanups=0)}recordCleanupFailure(e,t){let n=ne(t),s=0;try{s=process.memoryUsage().rss}catch(o){at.error(`Failed to read RSS after cleanup failure: ${ne(o)}`)}this.consecutiveCleanupFailures++,at.error(`Cleanup "${e.action}" failed: ${n}; consecutive failures: ${this.consecutiveCleanupFailures}`),Hde(this.consecutiveCleanupFailures)&&this.emitSafely("memory-cleanup-failed",{rss:s,consecutiveFailures:this.consecutiveCleanupFailures,recommendation:e,error:n})}emitSafely(e,t){try{this.emit(e,t)}catch(n){at.error(`${e} handler threw: ${ne(n)}`)}}async runCleanupSteps(e,t){for(let n of e){if(t!==this.cleanupGeneration)return;this.executeStep(n),await Promise.resolve()}}executeStep(e){switch(e){case"clear_file_cache":{this.coreConfig.getFileReadCache().clear(),at.debug("FileReadCache cleared");break}case"evict_cold_cache":{let t=this.coreConfig.getFileReadCache().evictNotAccessedSince(30);at.debug(`FileReadCache cold eviction: ${t} entries`);break}case"evict_stale_cache":{let t=this.coreConfig.getFileReadCache().evictNotAccessedSince(60);at.debug(`FileReadCache stale eviction: ${t} entries`);break}case"trigger_gc":{if(typeof globalThis.gc=="function"){let t=process.memoryUsage().rss;globalThis.gc();let n=process.memoryUsage().rss;at.debug(`global.gc() freed ${t-n} bytes`)}else at.warn("trigger_gc requested but global.gc is not available; start Node.js with --expose-gc");break}case"compact_history":{try{let t=this.coreConfig.getGeminiClient?.();if(!t?.isInitialized?.()){at.debug("[COMPACT_HISTORY] skipped: client not initialized");break}let n=t.getChat(),s=n.getHistoryShallow?.()??n.getHistory(),o=this.coreConfig.getClearContextOnIdle(),a=Zd(s,Date.now()-1,{...o,toolResultsThresholdMinutes:(o.toolResultsThresholdMinutes??0)<0?o.toolResultsThresholdMinutes:0});if(a.meta){n.setHistory(a.history),this.coreConfig.getFileReadCache().clear();let l=a.meta;at.debug(`[COMPACT_HISTORY] cleared ${l.toolsCleared} tool result(s) + ${l.mediaCleared} media (~${l.tokensSaved} tokens), kept ${l.toolsKept} tool / ${l.mediaKept} media`)}else at.debug("[COMPACT_HISTORY] nothing to compact")}catch(t){at.error(`[COMPACT_HISTORY] failed: ${ne(t)}`)}break}default:return gj(e)}}computeEffectiveMemoryLimit(){let e=Yp.totalmem(),t=this.readCgroupMemoryLimit("/sys/fs/cgroup/memory.max",e);if(t!==void 0)return at.info(`Using cgroup v2 memory limit: ${Bb(t)} MiB`),t;let n=this.readCgroupMemoryLimit("/sys/fs/cgroup/memory/memory.limit_in_bytes",e);return n!==void 0?(at.info(`Using cgroup v1 memory limit: ${Bb(n)} MiB`),n):(at.info(`Using host memory limit: ${Bb(e)} MiB`),e)}readCgroupMemoryLimit(e,t){try{let n=v5e(e,"utf-8").trim();if(n==="max")return;if(!/^-?\d+$/.test(n)){at.warn(`Ignoring non-numeric cgroup memory limit from ${e}: ${n}`);return}let s=Number(n);if(!Number.isFinite(s)||s<=0){at.warn(`Ignoring out-of-range cgroup memory limit from ${e}: ${n}`);return}if(s<E5e){at.warn(`Ignoring unrealistically small cgroup memory limit from ${e}: ${n}`);return}if(!Number.isSafeInteger(s)){at.debug(`Ignoring unlimited cgroup memory limit from ${e}: ${n}`);return}if(t>0&&s>t){at.debug(`Ignoring cgroup memory limit above host total from ${e}: ${n}`);return}return s}catch(n){at.debug(`Failed to read cgroup memory limit from ${e}: `+ne(n));return}}};function Hb(r){switch(r){case"aggressive":return 3;case"moderate":return 2;case"light":return 1;case"none":return 0;default:return gj(r)}}function Hde(r){return r===3||r===10||r>10&&r%20===0}function Bb(r){return(r/1024/1024).toFixed(0)}function gj(r){throw new Error(`Unhandled memory pressure monitor value: ${String(r)}`)}g();var k5e=F("PROMPT_REGISTRY"),LR=class{prompts=new Map;registerPrompt(e){if(this.prompts.has(e.name)){let t=`${e.serverName}_${e.name}`;k5e.warn(`Prompt with name "${e.name}" is already registered. Renaming to "${t}".`),this.prompts.set(t,{...e,name:t})}else this.prompts.set(e.name,e)}getAllPrompts(){return Array.from(this.prompts.values()).sort((e,t)=>e.name.localeCompare(t.name))}getPrompt(e){return this.prompts.get(e)}getPromptsByServer(e){let t=[];for(let n of this.prompts.values())n.serverName===e&&t.push(n);return t.sort((n,s)=>n.name.localeCompare(s.name))}clear(){this.prompts.clear()}removePromptsByServer(e){for(let[t,n]of this.prompts.entries())n.serverName===e&&this.prompts.delete(t)}};import{randomUUID as Bde}from"node:crypto";var x5e=F("GIT_CO_AUTHOR"),A5e=F("MEMORY_PRESSURE"),jde=.15;var Ps=(o=>(o.PLAN="plan",o.DEFAULT="default",o.AUTO_EDIT="auto-edit",o.AUTO="auto",o.BOGAN="bogan",o))(Ps||{}),EH=Object.values(Ps).filter(r=>r!=="auto"),_j=class extends Error{constructor(e){super(e),this.name="TrustGateError"}},b8t={plan:{id:"plan",name:"Plan",description:"Analyze only, do not modify files or execute commands"},default:{id:"default",name:"Default",description:"Require approval for file edits or shell commands"},"auto-edit":{id:"auto-edit",name:"Auto Edit",description:"Automatically approve file edits"},auto:{id:"auto",name:"Auto",description:"LLM classifier auto-approves safe actions, blocks risky ones"},bogan:{id:"bogan",name:"BOGAN",description:"Automatically approve all tools"}},NR="Written by Matilda \u{1F1E6}\u{1F1FA} made by [Maincode](https://maincode.com)";function R5e(r){if(typeof r=="boolean")return{commit:r,pr:r,prMessage:NR};let e=(s,o)=>{if(s===void 0)return!0;if(typeof s=="boolean")return s;if(typeof s=="string"){let a=s.trim().toLowerCase();return a==="true"||a==="yes"||a==="on"||a==="1"?!0:(["false","no","off","0","disabled",""].includes(a)||x5e.warn(`Unrecognized string value for general.gitCoAuthor.${o}: ${JSON.stringify(s)}; treating as false. Accepted forms: true/yes/on/1, false/no/off/0/empty.`),!1)}return typeof s=="number"?s===1:!1},t=r?.prMessage,n=typeof t=="string"?t:NR;return{commit:e(r?.commit,"commit"),pr:e(r?.pr,"pr"),prMessage:n}}var P5e=25e3,M5e=1e3,I5e=2e5;function v8t(r){return r==="project"||r==="workspace"}var zde=class{constructor(e,t,n,s,o,a,l,c,u,d,h,f,p,y,w,m,_,b,v,S,T){this.command=e;this.args=t;this.env=n;this.cwd=s;this.url=o;this.httpUrl=a;this.headers=l;this.tcp=c;this.timeout=u;this.trust=d;this.description=h;this.includeTools=f;this.excludeTools=p;this.extensionName=y;this.oauth=w;this.authProviderType=m;this.targetAudience=_;this.targetServiceAccount=b;this.type=v;this.discoveryTimeoutMs=S;this.scope=T}};function Ln(r){return r.type==="sdk"}var TK=(n=>(n.DYNAMIC_DISCOVERY="dynamic_discovery",n.GOOGLE_CREDENTIALS="google_credentials",n.SERVICE_ACCOUNT_IMPERSONATION="service_account_impersonation",n))(TK||{});function O5e(r){if(r)switch(r){case"stream-json":return"stream-json";case"json":case"json":return"json";case"text":case"text":default:return"text"}}function D5e(){let r={...DR};try{r.softPressureRatio=wj("MATILDA_MEMORY_PRESSURE_SOFT",r.softPressureRatio),r.hardPressureRatio=wj("MATILDA_MEMORY_PRESSURE_HARD",r.hardPressureRatio),r.criticalRatio=wj("MATILDA_MEMORY_PRESSURE_CRITICAL",r.criticalRatio);let e=Qt.env.MATILDA_MEMORY_ENABLE_GC;e&&["0","false","off","no"].includes(e.trim().toLowerCase())&&(r.enableExplicitGC=!1),yj(r)}catch(e){let t=`[MATILDA] WARNING: Invalid memory pressure config; using defaults. Error: ${ne(e)}`;return Qt.stderr.write(`${t}
2199
- `),A5e.warn(t),{...DR}}return r}function wj(r,e){let t=Qt.env[r];if(!t)return e;let n=Number(t);if(!Number.isFinite(n))throw new Error(`${r} must be a finite number`);return n}var L5e=[R.READ_FILE,R.EDIT,R.NOTEBOOK_EDIT,R.SHELL],N5e=Object.freeze(new Set),qde=!1,xp=class{sessionId;sessionData;pendingStartupWorktreeNotice=null;debugLogger;toolRegistry;pendingMcpBudgetCallback;promptRegistry;subagentManager;memoryPressureConfig;memoryPressureMonitor;backgroundTaskRegistry=new GA;monitorRegistry=new CE;backgroundAgentResumeService;backgroundShellRegistry=new EE;workflowRunRegistry=new kE;fileReadCache=new Py;extensionManager;skillManager=null;permissionManager=null;modelInvocableCommandsProvider=null;modelInvocableCommandsExecutor=null;pendingInlineAnnouncedSkillKeys=new Set;fileSystemService;contentGeneratorConfig;contentGeneratorConfigSources={};contentGenerator;embeddingModel;modelsConfig;modelProvidersConfig;sandbox;targetDir;workspaceContext;debugMode;inputFormat;outputFormat;includePartialMessages;question;systemPrompt;appendSystemPrompt;coreTools;allowedTools;excludeTools;disabledSlashCommands;disabledSkillNamesProvider;disabledTools;permissionsAllow;permissionsAsk;permissionsDeny;permissionsAutoMode;toolDiscoveryCommand;toolCallCommand;mcpServerCommand;mcpServers;runtimeMcpServers=new Map;lspEnabled;lspClient;lspInitializationError;allowedMcpServers;excludedMcpServers;pendingMcpServers;sessionSubagents;userMemory;sdkMode;geminiMdFileCount;conditionalRulesRegistry;contextRuleExcludes;approvalMode;prePlanMode;planGateState;planGateEntryCounter=0;autoModeDenialState=tg();accessibility;telemetrySettings;outboundCorrelationSettings;gitCoAuthor;usageStatisticsEnabled;fileReadCacheDisabled;geminiClient;baseLlmClient;cronScheduler=null;fileFiltering;fileDiscoveryService=null;sessionService=void 0;sessionStorageDir;sessionRuntimeBaseDir;sessionStorage;sessionStoragePinned;chatRecordingService=void 0;fileCheckpointingEnabled;toolResultBudget={bytesWritten:0};fileHistoryService;proxy;cwd;explicitIncludeDirectories;bugCommand;outputLanguageFilePath;noBrowser;folderTrustFeature;folderTrust;ideMode;maxSessionTurns;maxWallTimeSeconds;maxToolCalls;clearContextOnIdle;sessionTokenLimit;listExtensions;overrideExtensions;cliVersion;runtimeStatusEnabled=!1;experimentalZedIntegration=!1;cronEnabled=!0;agentTeamEnabled=!1;workflowsEnabled=!1;computerUseEnabled=!0;computerUseMaxImageDimension;emitToolUseSummaries=!0;chatRecordingEnabled;loadMemoryFromIncludeDirectories=!1;importFormat;chatCompression;interactive;trustedFolder;useRipgrep;useBuiltinRipgrep;shouldUseNodePtyShell;preventSystemSleep;skipNextSpeakerCheck;shellExecutionConfig;arenaManager=null;arenaManagerChangeCallback=null;arenaAgentClient;teamManager=null;teamManagerChangeCallbacks=new Set;teamContext=null;agentsSettings;worktreeSettings;skipLoopDetection;skipStartupContext;bareMode;warnings;allowedHttpHookUrls;onPersistPermissionRuleCallback;onRefreshPermissionsFromDiskCallback;initialized=!1;storage;sessionTransitionMutex=new za;runtimeStatusWrite=Promise.resolve();fileExclusions;truncateToolOutputThreshold;truncateToolOutputLines;toolOutputBatchBudget;eventEmitter;channel;jsonFd;jsonFile;jsonPartials;jsonSchema;inputFile;plansDir;plansDirectoryConfigured;defaultFileEncoding;enableManagedAutoMemory;enableManagedAutoDream;enableAutoSkill;fastModel;modelDisplayName;disableAllHooks;stopHookBlockingCap;userHooks;projectHooks;hooks;hookSystem;messageBus;memoryManager;modelChangeListeners=new Set;constructor(e){this.sessionId=e.sessionId??Bde(),!qde&&Qt.env&&(Qt.env.MATILDA_CODE_SESSION_ID=this.sessionId,qde=!0),this.sessionData=e.sessionData,YR(this),this.debugLogger=F(),this.embeddingModel=e.embeddingModel??TP,this.fileSystemService=new GT,this.sandbox=e.sandbox,this.targetDir=Vr.resolve(e.targetDir),this.sessionStoragePinned=e.sessionStorageDir!==void 0,this.sessionStorageDir=Vr.resolve(e.sessionStorageDir??this.targetDir),this.sessionRuntimeBaseDir=e.sessionRuntimeBaseDir?Vr.resolve(e.sessionRuntimeBaseDir):void 0,this.plansDirectoryConfigured=!!e.plansDirectory?.trim(),this.plansDir=fe.getPlansDir(this.targetDir,e.plansDirectory),this.explicitIncludeDirectories=Array.from(new Set(e.includeDirectories??[])),this.workspaceContext=new Da(this.targetDir,this.explicitIncludeDirectories),this.debugMode=e.debugMode,this.inputFormat=e.inputFormat??"text";let t=O5e(e.outputFormat??e.output?.format);this.outputFormat=t??"text",this.includePartialMessages=e.includePartialMessages??!1,this.question=e.question,this.systemPrompt=e.systemPrompt,this.appendSystemPrompt=e.appendSystemPrompt,this.coreTools=e.coreTools,this.allowedTools=e.allowedTools,this.excludeTools=e.excludeTools,this.disabledSlashCommands=Object.freeze([...e.disabledSlashCommands??[]]),this.disabledSkillNamesProvider=e.disabledSkillNamesProvider??null,this.disabledTools=new Set(e.disabledTools??[]),this.permissionsAllow=e.permissions?.allow||[],this.permissionsAsk=e.permissions?.ask||[],this.permissionsDeny=e.permissions?.deny||[],this.permissionsAutoMode=e.permissions?.autoMode??{},this.toolDiscoveryCommand=e.toolDiscoveryCommand,this.toolCallCommand=e.toolCallCommand,this.mcpServerCommand=e.mcpServerCommand,this.mcpServers=e.mcpServers,this.lspEnabled=e.lsp?.enabled??!1,this.lspClient=e.lspClient,this.allowedMcpServers=e.allowedMcpServers,this.excludedMcpServers=e.excludedMcpServers,this.pendingMcpServers=e.pendingMcpServers,this.sessionSubagents=e.sessionSubagents??[],this.sdkMode=e.sdkMode??!1,this.userMemory=e.userMemory??"",this.geminiMdFileCount=e.geminiMdFileCount??0,this.contextRuleExcludes=e.contextRuleExcludes??[],this.approvalMode=e.approvalMode??"default",this.accessibility=e.accessibility??{},this.telemetrySettings={enabled:e.telemetry?.enabled??!1,target:e.telemetry?.target??CP,otlpEndpoint:e.telemetry?.otlpEndpoint,otlpProtocol:e.telemetry?.otlpProtocol,otlpTracesEndpoint:e.telemetry?.otlpTracesEndpoint,otlpLogsEndpoint:e.telemetry?.otlpLogsEndpoint,otlpMetricsEndpoint:e.telemetry?.otlpMetricsEndpoint,logPrompts:e.telemetry?.logPrompts??!0,includeSensitiveSpanAttributes:e.telemetry?.includeSensitiveSpanAttributes??!1,outfile:e.telemetry?.outfile,resourceAttributes:e.telemetry?.resourceAttributes,metrics:e.telemetry?.metrics,resourceAttributeWarnings:e.telemetry?.resourceAttributeWarnings},this.outboundCorrelationSettings={propagateTraceContext:e.outboundCorrelation?.propagateTraceContext??!1},this.gitCoAuthor={...R5e(e.gitCoAuthor),name:"Matilda-Coder",email:"matilda@maincode.com"},this.usageStatisticsEnabled=e.usageStatisticsEnabled??!1,this.fileReadCacheDisabled=e.fileReadCacheDisabled??!1,this.outputLanguageFilePath=e.outputLanguageFilePath,this.fileFiltering={respectGitIgnore:e.fileFiltering?.respectGitIgnore??!0,respectMatildaIgnore:e.fileFiltering?.respectMatildaIgnore??!0,enableRecursiveFileSearch:e.fileFiltering?.enableRecursiveFileSearch??!0,enableFuzzySearch:e.fileFiltering?.enableFuzzySearch??!0},this.fileCheckpointingEnabled=e.fileCheckpointingEnabled??(!e.sdkMode&&(e.interactive??!1)),this.proxy=e.proxy,this.cwd=e.cwd??Qt.cwd(),this.fileDiscoveryService=e.fileDiscoveryService??null,this.bugCommand=e.bugCommand,this.maxSessionTurns=e.maxSessionTurns??-1,this.maxWallTimeSeconds=e.maxWallTimeSeconds??-1,this.maxToolCalls=e.maxToolCalls??-1;let n=e.clearContextOnIdle,s=n?.toolResultsThresholdMinutes??5;this.clearContextOnIdle={toolResultsThresholdMinutes:s,toolResultsNumToKeep:n?.toolResultsNumToKeep??5,toolResultsTotalCharsThreshold:n?.toolResultsTotalCharsThreshold??((n?.toolResultsThresholdMinutes??0)<0?-1:5e5)},this.sessionTokenLimit=e.sessionTokenLimit??-1,this.experimentalZedIntegration=e.experimentalZedIntegration??!1,this.cronEnabled=e.cronEnabled??!0,this.agentTeamEnabled=e.agentTeamEnabled??!1,this.workflowsEnabled=e.workflowsEnabled??!1,this.computerUseEnabled=e.computerUseEnabled??!0,this.computerUseMaxImageDimension=e.computerUseMaxImageDimension,this.emitToolUseSummaries=e.emitToolUseSummaries??!0,this.listExtensions=e.listExtensions??!1,this.overrideExtensions=e.overrideExtensions,this.noBrowser=e.noBrowser??!1,this.folderTrustFeature=e.folderTrustFeature??!1,this.folderTrust=e.folderTrust??!1,this.ideMode=e.ideMode??!1,this.modelProvidersConfig=e.modelProvidersConfig,this.cliVersion=e.cliVersion,this.chatRecordingEnabled=e.chatRecording??!0,this.loadMemoryFromIncludeDirectories=e.loadMemoryFromIncludeDirectories??!1,this.importFormat=e.importFormat??"tree",this.chatCompression=e.chatCompression,this.interactive=e.interactive??!1,this.trustedFolder=e.trustedFolder,this.skipLoopDetection=e.skipLoopDetection??!1,this.skipStartupContext=e.skipStartupContext??!1,this.bareMode=e.bareMode??!1,this.warnings=e.warnings??[],this.addLegacyPlanLocationWarning(),this.allowedHttpHookUrls=e.allowedHttpHookUrls??[],this.onPersistPermissionRuleCallback=e.onPersistPermissionRule,this.onRefreshPermissionsFromDiskCallback=e.onRefreshPermissionsFromDisk,this.useRipgrep=e.useRipgrep??!0,this.useBuiltinRipgrep=e.useBuiltinRipgrep??!0,this.shouldUseNodePtyShell=e.shouldUseNodePtyShell??n4(),this.preventSystemSleep=e.preventSystemSleep??!0,this.skipNextSpeakerCheck=e.skipNextSpeakerCheck??!0,this.shellExecutionConfig={terminalWidth:e.shellExecutionConfig?.terminalWidth??80,terminalHeight:e.shellExecutionConfig?.terminalHeight??24,showColor:e.shellExecutionConfig?.showColor??!1,pager:e.shellExecutionConfig?.pager??"cat",maxBufferedOutputBytes:e.shellExecutionConfig?.maxBufferedOutputBytes},this.truncateToolOutputThreshold=e.truncateToolOutputThreshold??P5e,this.truncateToolOutputLines=e.truncateToolOutputLines??M5e,this.toolOutputBatchBudget=e.toolOutputBatchBudget??I5e,this.channel=e.channel,this.jsonFd=e.jsonFd,this.jsonFile=e.jsonFile,this.jsonPartials=e.jsonPartials??!0,this.jsonSchema=e.jsonSchema,this.inputFile=e.inputFile,this.defaultFileEncoding=e.defaultFileEncoding,this.storage=new fe(this.targetDir),this.sessionStorage=new fe(this.sessionStorageDir,this.sessionRuntimeBaseDir),this.inputFormat=e.inputFormat??"text",this.fileExclusions=new t2(this),this.eventEmitter=e.eventEmitter,this.arenaAgentClient=Sv.create(),this.agentsSettings=e.agents??{},this.worktreeSettings=e.worktree??{},e.contextFileName&&Qj(e.contextFileName),this.modelsConfig=new av({initialAuthType:e.authType??e.generationConfig?.authType,modelProvidersConfig:this.modelProvidersConfig,generationConfig:{model:e.model,...e.generationConfig||{},baseUrl:e.generationConfig?.baseUrl},generationConfigSources:e.generationConfigSources,onModelChange:this.handleModelChange.bind(this)}),this.telemetrySettings.enabled&&C2(this);let o=this.getProxy();o&&(0,FR.setGlobalDispatcher)(new FR.ProxyAgent(o)),this.geminiClient=new IR(this),this.chatRecordingService=this.chatRecordingEnabled?new oh(this):void 0,this.extensionManager=new kA({workspaceDir:this.targetDir,enabledExtensionOverrides:this.overrideExtensions,isWorkspaceTrusted:this.isTrustedFolder()}),this.enableManagedAutoMemory=e.enableManagedAutoMemory??!0,this.enableManagedAutoDream=e.enableManagedAutoDream??!0,this.enableAutoSkill=e.enableAutoSkill??!0,this.fastModel=e.fastModel||void 0,this.modelDisplayName=e.modelDisplayName||void 0,this.disableAllHooks=e.disableAllHooks??!1,this.stopHookBlockingCap=c0(e.stopHookBlockingCap),this.userHooks=e.userHooks,this.projectHooks=e.projectHooks,this.hooks=e.hooks,this.memoryManager=new Fb}async initialize(e){if(this.initialized)throw Error("Config was already initialized");this.initialized=!0,this.debugLogger.info("Config initialization started"),this.getFileService(),this.promptRegistry=new LR,this.extensionManager.setConfig(this);let t=this.getExplicitExtensionNames();this.getBareMode()?t.length>0&&await this.extensionManager.refreshCache({names:t}):await this.extensionManager.refreshCache(),this.debugLogger.debug("Extension manager initialized"),this.getDisableAllHooks()?this.debugLogger.debug("Hook system disabled, skipping initialization"):(this.hookSystem=new Bp(this),await this.hookSystem.initialize(),this.debugLogger.debug("Hook system initialized"),this.messageBus=new vb,this.messageBus.subscribe("hook-execution-request",async o=>{try{let a=this.hookSystem;if(!a){this.messageBus?.publish({type:"hook-execution-response",correlationId:o.correlationId,success:!1,error:new Error("Hook system not initialized")});return}if(o.signal?.aborted){this.messageBus?.publish({type:"hook-execution-response",correlationId:o.correlationId,success:!1,error:new Error("Hook execution cancelled (aborted)")});return}let l,c,u=o.input||{},d=o.signal;switch(o.eventName){case"UserPromptSubmit":l=await a.fireUserPromptSubmitEvent(u.prompt||"",d);break;case"UserPromptExpansion":l=await a.fireUserPromptExpansionEvent(u.command_name||"",u.command_args||"",u.prompt||"",d);break;case"Stop":{let h=await a.fireStopEvent(u.stop_hook_active||!1,u.last_assistant_message||"",d);l=h.finalOutput?ct("Stop",h.finalOutput):void 0,c=h.allOutputs.length;break}case"PreToolUse":{l=await a.firePreToolUseEvent(u.tool_name||"",u.tool_input||{},u.tool_use_id||"",u.permission_mode??"default",d);break}case"PostToolUse":l=await a.firePostToolUseEvent(u.tool_name||"",u.tool_input||{},u.tool_response||{},u.tool_use_id||"",u.permission_mode||"default",d);break;case"PostToolUseFailure":l=await a.firePostToolUseFailureEvent(u.tool_use_id||"",u.tool_name||"",u.tool_input||{},u.error||"",u.is_interrupt,u.permission_mode||"default",d);break;case"PostToolBatch":l=await a.firePostToolBatchEvent(u.tool_calls||[],u.permission_mode||"default",d);break;case"Notification":l=await a.fireNotificationEvent(u.message||"",u.notification_type||"permission_prompt",u.title||void 0,d);break;case"PermissionRequest":l=await a.firePermissionRequestEvent(u.tool_name||"",u.tool_input||{},u.permission_mode||"default",u.permission_suggestions||void 0,d);break;case"PermissionDenied":l=await a.firePermissionDeniedEvent(u.tool_name||"",u.tool_input||{},u.tool_use_id||"",u.reason||"classifier_blocked",d);break;case"SubagentStart":l=await a.fireSubagentStartEvent(u.agent_id||"",u.agent_type||"",u.permission_mode||"default",d);break;case"SubagentStop":l=await a.fireSubagentStopEvent(u.agent_id||"",u.agent_type||"",u.agent_transcript_path||"",u.last_assistant_message||"",u.stop_hook_active||!1,u.permission_mode||"default",d);break;default:this.debugLogger.warn(`Unknown hook event: ${o.eventName}`),l=void 0}this.messageBus?.publish({type:"hook-execution-response",correlationId:o.correlationId,success:!0,output:l,stopHookCount:c})}catch(a){this.debugLogger.warn(`Hook execution failed: ${a}`),this.messageBus?.publish({type:"hook-execution-response",correlationId:o.correlationId,success:!1,error:a instanceof Error?a:new Error(String(a))})}}),this.debugLogger.debug("MessageBus initialized with hook subscription")),this.subagentManager=new q_(this),this.skillManager=new Y_(this),this.getBareMode()?await this.skillManager.refreshCache():await this.skillManager.startWatching(),this.debugLogger.debug("Skill manager initialized"),this.memoryPressureConfig=D5e(),this.memoryPressureMonitor=new jb(this,this.memoryPressureConfig),this.permissionManager=new Qm(this),this.permissionManager.initialize(),this.debugLogger.debug("Permission manager initialized"),this.sessionSubagents.length>0&&this.subagentManager.loadSessionSubagents(this.sessionSubagents),this.getBareMode()||await this.extensionManager.refreshCache(),await this.refreshHierarchicalMemory("session_start"),this.debugLogger.debug("Hierarchical memory loaded");let n=Qt.env.MATILDA_CODE_LEGACY_MCP_BLOCKING==="1",s=this.getBareMode()||!n||e?.skipMcpDiscovery===!0;this.toolRegistry=await this.createToolRegistry(e?.sendSdkMcpMessage,s?{skipDiscovery:!0}:void 0),Xn("tool_registry_created",{toolCount:this.toolRegistry.getAllToolNames().length,mcpInline:!s}),this.debugLogger.info(`Tool registry initialized with ${this.toolRegistry.getAllToolNames().length} tools`),e?.skipGeminiInitialization?this.debugLogger.info("Gemini client initialization skipped"):(await this.geminiClient.initialize(),this.debugLogger.info("Gemini client initialized")),this.modelsConfig.detectAndCaptureRuntimeModel(),await this.toolRegistry.warmAll({strict:!0}),s&&!this.getBareMode()&&!e?.skipMcpDiscovery&&this.startMcpDiscoveryInBackground(),new hz().getInstallationId(),tP(this,new hP(this)),this.debugLogger.info("Config initialization completed"),this.getBareMode()||(async()=>{try{let a=await new us(this.targetDir).getRepoTopLevel()??this.targetDir,l=Vr.join(a,".matilda","worktrees");try{await Wde.access(l)}catch{this.debugLogger.debug(`Stale worktree sweep skipped: ${l} does not exist`);return}let c=await Nde(a);c>0?this.debugLogger.info(`Stale worktree sweep removed ${c} ephemeral worktree(s) under ${a}`):this.debugLogger.debug(`Stale worktree sweep ran under ${a}: nothing to remove`)}catch(o){this.debugLogger.warn(`Stale worktree sweep failed (non-fatal): ${o}`)}})()}mcpDiscoveryPromise;startMcpDiscoveryInBackground(){let e=this.toolRegistry.getMcpClientManager?.();if(!e){this.debugLogger.debug("Skipping background MCP discovery: ToolRegistry has no MCP client manager");return}this.mcpDiscoveryPromise=e.discoverAllMcpToolsIncremental(this).then(async()=>{try{await this.geminiClient?.setTools()}catch(t){this.debugLogger.error(`setTools() after background MCP discovery failed: ${t instanceof Error?t.message:String(t)}`)}}).catch(t=>{this.debugLogger.error(`Background MCP discovery failed: ${t instanceof Error?t.message:String(t)}`)})}async waitForMcpReady(){this.mcpDiscoveryPromise&&await this.mcpDiscoveryPromise}getFailedMcpServerNames(){let e=this.getMcpServers();if(!e)return[];let t=[];for(let n of Object.keys(e))this.isMcpServerDisabled(n)||this.isMcpServerPendingApproval(n)||fT(n)!=="connected"&&t.push(n);return t}async refreshHierarchicalMemory(e="refresh"){let{memoryContent:t,fileCount:n,conditionalRules:s,projectRoot:o}=await yue(this.getWorkingDir(),this.getMemoryDiscoveryDirectories(),this.getFileService(),this.getExtensionContextFilePaths(),this.isTrustedFolder(),this.getImportFormat(),this.contextRuleExcludes,{explicitOnly:this.getBareMode(),loadReason:e,onInstructionsLoaded:bR(()=>this.hookSystem)});if(this.getManagedAutoMemoryEnabled()){let[a,l]=await Promise.all([S3(this.getProjectRoot()),T3().catch(()=>null)]);this.setUserMemory(this.memoryManager.appendToUserMemory(t,Dr(this.getProjectRoot()),a,{memoryDir:ti(),indexContent:l}))}else this.setUserMemory(t);this.setGeminiMdFileCount(n),this.conditionalRulesRegistry=new _b(s,o)}buildMemoryContextWarning(e){let t=this.getContentGeneratorConfig()?.contextWindowSize??this.modelsConfig.getGenerationConfig().contextWindowSize??rm(this.getModel(),"input");if(!t||t<=0||!e)return;let n=Math.ceil(e.length/es),s=Math.floor(t*jde);if(!(n<=s))return`Warning: Loaded MATILDA.md/context instructions use about ${n.toLocaleString()} tokens, more than ${Math.round(jde*100)}% of this model's ${t.toLocaleString()} token context window. Consider trimming long always-loaded context or moving details into on-demand files.`}getMemoryDiscoveryDirectories(){return this.shouldLoadMemoryFromIncludeDirectories()?this.getBareMode()?this.explicitIncludeDirectories:[...this.getWorkspaceContext().getDirectories()]:[]}getConditionalRulesRegistry(){return this.conditionalRulesRegistry}setConditionalRulesRegistry(e){this.conditionalRulesRegistry=e}getContextRuleExcludes(){return this.contextRuleExcludes}getContentGenerator(){return Bm()?.contentGenerator??this.contentGenerator}getModelsConfig(){return this.modelsConfig}updateCredentials(e,t){this.modelsConfig.updateCredentials(e,t)}reloadModelProvidersConfig(e){this.modelsConfig.reloadModelProvidersConfig(e)}async refreshAuth(e,t){let n=this.modelsConfig.getModel();this.modelsConfig.syncAfterAuthRefresh(e,n);let s=this.modelsConfig.consumeRequireCachedCredentialsFlag(),{config:o,sources:a}=RP(this,e,this.modelsConfig.getGenerationConfig(),this.modelsConfig.getGenerationConfigSources(),{strictModelProvider:this.modelsConfig.isStrictModelProviderSelection()}),l=o;this.contentGenerator=await Hd(l,this,s?!0:t),this.contentGeneratorConfig=l,this.contentGeneratorConfigSources=a,this.baseLlmClient=new fm(this.contentGenerator,this);let c=this.getMessageBus();!this.getDisableAllHooks()&&c&&zm(c,`Successfully authenticated with ${e}`,"auth_success","Authentication successful").catch(()=>{})}getBaseLlmClient(){if(!this.baseLlmClient)if(this.contentGenerator)this.baseLlmClient=new fm(this.getContentGenerator(),this);else throw new Error("BaseLlmClient not initialized. Ensure authentication has occurred and ContentGenerator is ready.");return this.baseLlmClient}getSessionId(){return this.sessionId}getWarnings(){let e=this.buildMemoryContextWarning(this.getUserMemory());return e?[...this.warnings,e]:this.warnings}getDebugLogger(){return this.debugLogger}async startNewSession(e,t){return this.sessionTransitionMutex.runExclusive(async()=>{let n=this.chatRecordingService;try{n?.finalize()}catch{}await n?.releaseTranscriptOwnership();let s=this.sessionId;if(this.sessionId=e??Bde(),Qt.env&&(Qt.env.MATILDA_CODE_SESSION_ID=this.sessionId),this.sessionData=t,YR(this),this.debugLogger=F(),this.chatRecordingService=this.chatRecordingEnabled?new oh(this):void 0,this.getFileReadCache().clear(),this.toolResultBudget.bytesWritten=0,this.getMemoryPressureMonitor()?.resetForNewSession(),this.fileHistoryService=void 0,T2(this.sessionId),v2(),oi.resetInstance(),this.initialized&&tP(this,new hP(this)),this.runtimeStatusEnabled&&s!==this.sessionId){let o=this.sessionStorage.getRuntimeStatusPath(s),a=this.sessionStorage.getRuntimeStatusPath(this.sessionId),l=this.cliVersion??null,c=this.targetDir,u=this.sessionId;this.queueRuntimeStatusWrite(async()=>{await dW(o),await x0(a,{sessionId:u,workDir:c,matildaVersion:l})})}return this.sessionId})}markRuntimeStatusEnabled(){this.runtimeStatusEnabled=!0}queueRuntimeStatusWrite(e){this.runtimeStatusWrite=this.runtimeStatusWrite.catch(()=>{}).then(e).catch(()=>{})}async flushRuntimeStatusWrites(){await this.runtimeStatusWrite.catch(()=>{})}async refreshCurrentRuntimeStatus(e){this.runtimeStatusEnabled&&(this.queueRuntimeStatusWrite(async()=>{await x0(this.sessionStorage.getRuntimeStatusPath(this.sessionId),{sessionId:this.sessionId,workDir:e,matildaVersion:this.cliVersion??null})}),await this.flushRuntimeStatusWrites())}getResumedSessionData(){return this.sessionData}shouldLoadMemoryFromIncludeDirectories(){return this.loadMemoryFromIncludeDirectories}getImportFormat(){return this.importFormat}getContentGeneratorConfig(){return Bm()?.contentGeneratorConfig??this.contentGeneratorConfig}getContentGeneratorConfigSources(){return Object.keys(this.contentGeneratorConfigSources).length===0&&this.modelsConfig?this.modelsConfig.getGenerationConfigSources():this.contentGeneratorConfigSources}getModel(){return this.getContentGeneratorConfig()?.model||this.modelsConfig.getModel()}getModelDisplayName(){return this.modelDisplayName||this.modelsConfig.getModelDisplayName(this.getModel())}getPublicModelId(e){return this.modelsConfig.getPublicModelId(e)}isManagedMatildaModel(e){return this.modelsConfig.isManagedMatildaModel(e)}onModelChange(e){return this.modelChangeListeners.add(e),()=>{this.modelChangeListeners.delete(e)}}notifyModelChangeListeners(){let e=this.getModel();for(let t of this.modelChangeListeners)t(e)}getFastModel(){let e=this.resolveFastModelSelector();if(!e||!(e.authType?this.getAllConfiguredModels([e.authType]):this.getAllConfiguredModels()).some(s=>s.id===e.modelId))return;let n=ni(this.fastModel);return n?.authType?`${n.authType}:${e.modelId}`:e.modelId}resolveFastModelSelector(){if(this.fastModel)try{return ni(this.fastModel,{currentAuthType:this.getContentGeneratorConfig()?.authType,getAvailableModels:e=>this.getAllConfiguredModels(e)})}catch{return}}setFastModel(e){this.fastModel=e||void 0}async setModel(e,t){await this.modelsConfig.setModel(e,t),this.contentGeneratorConfig&&(this.contentGeneratorConfig.model=e),this.notifyModelChangeListeners()}async handleModelChange(e,t){if(this.contentGeneratorConfig){if(e==="matilda-oauth"&&!t){let{config:n,sources:s}=RP(this,e,this.modelsConfig.getGenerationConfig(),this.modelsConfig.getGenerationConfigSources(),{strictModelProvider:this.modelsConfig.isStrictModelProviderSelection()});this.contentGeneratorConfig.model=n.model,this.contentGeneratorConfig.samplingParams=n.samplingParams,this.contentGeneratorConfig.contextWindowSize=n.contextWindowSize,this.contentGeneratorConfig.enableCacheControl=n.enableCacheControl,this.contentGeneratorConfig.splitToolMedia=n.splitToolMedia,"model"in s&&(this.contentGeneratorConfigSources.model=s.model),"samplingParams"in s&&(this.contentGeneratorConfigSources.samplingParams=s.samplingParams),"enableCacheControl"in s&&(this.contentGeneratorConfigSources.enableCacheControl=s.enableCacheControl),"contextWindowSize"in s&&(this.contentGeneratorConfigSources.contextWindowSize=s.contextWindowSize),"splitToolMedia"in s&&(this.contentGeneratorConfigSources.splitToolMedia=s.splitToolMedia);return}await this.refreshAuth(e)}}getAvailableModels(){return this.modelsConfig.getAvailableModels()}getAvailableModelsForAuthType(e){return this.modelsConfig.getAvailableModelsForAuthType(e)}getAllConfiguredModels(e){return this.modelsConfig.getAllConfiguredModels(e)}getActiveRuntimeModelSnapshot(){return this.modelsConfig.getActiveRuntimeModelSnapshot()}async switchModel(e,t,n){await this.modelsConfig.switchModel(e,t,n),this.notifyModelChangeListeners()}getMaxSessionTurns(){return this.maxSessionTurns}getMaxWallTimeSeconds(){return this.maxWallTimeSeconds}getMaxToolCalls(){return this.maxToolCalls}getClearContextOnIdle(){return this.clearContextOnIdle}getSessionTokenLimit(){return this.sessionTokenLimit}getEmbeddingModel(){return this.embeddingModel}getSandbox(){return this.sandbox}isRestrictiveSandbox(){let e=this.getSandbox(),t=Qt.env.SEATBELT_PROFILE,n=Qt.env.SANDBOX,s=Qt.env.MATILDA_DESKTOP_SANDBOX_NONCE,o=Qt.env.MATILDA_DESKTOP_SANDBOX_ACTIVE;return(e?.command==="sandbox-exec"||n==="sandbox-exec")&&!!t&&t.startsWith("restrictive-")&&(!s||o===s)}getTargetDir(){return this.targetDir}getCurrentSessionArtifactMoves(e,t){let n=Vr.join(e.getProjectDir(),"chats"),s=Vr.join(t.getProjectDir(),"chats");return[`${this.sessionId}.jsonl`,`${this.sessionId}.runtime.json`,`${this.sessionId}.worktree.json`].map(o=>({from:Vr.join(n,o),to:Vr.join(s,o)}))}moveFile(e,t){try{bt.renameSync(e,t)}catch(n){if(n.code!=="EXDEV")throw n;let s=!1;try{bt.copyFileSync(e,t),s=!0,bt.unlinkSync(e)}catch(o){if(s)try{bt.unlinkSync(t)}catch{}throw o}}}moveCurrentSessionArtifacts(e,t){let n=[];for(let{from:s,to:o}of this.getCurrentSessionArtifactMoves(e,t))if(bt.existsSync(s)){bt.mkdirSync(Vr.dirname(o),{recursive:!0});try{this.moveFile(s,o),n.push({from:s,to:o})}catch(a){for(let l of n.reverse())try{bt.mkdirSync(Vr.dirname(l.from),{recursive:!0}),this.moveFile(l.to,l.from)}catch(c){this.debugLogger.warn("Failed to roll back moved session artifact",c)}throw a}}}async prepareSessionArtifactMigration(e,t,n){this.chatRecordingService?.finalize(),await this.chatRecordingService?.releaseTranscriptOwnership(),await this.flushRuntimeStatusWrites();try{this.moveCurrentSessionArtifacts(e,t)}catch(s){try{Qt.chdir(n)}catch(o){this.debugLogger.warn("Failed to roll back working directory after session artifact migration failed",o)}throw s}}async relocateWorkingDirectory(e,t){let n=bt.realpathSync(Qt.cwd()),s=Vr.resolve(e),o=t??bt.realpathSync(s);if(!bt.statSync(s).isDirectory())throw new Error(`Path is not a directory: ${s}`);let a=Da.resolveRootDirectories(o,this.explicitIncludeDirectories);Qt.chdir(s);let l=bt.realpathSync(Qt.cwd());if(l!==o)throw Qt.chdir(n),new Error(`Changed directory to ${l}, expected ${o}.`);let c=this.sessionStorage,u=new fe(o);this.sessionStoragePinned||await this.prepareSessionArtifactMigration(c,u,n),this.targetDir=o,this.cwd=o,this.storage=u,this.sessionStoragePinned||(this.sessionStorage=u,this.sessionStorageDir=o,this.chatRecordingService?.resetStoragePaths(),this.sessionService=void 0),await this.refreshCurrentRuntimeStatus(o),this.workspaceContext.applyRootDirectories(a),this.fileDiscoveryService=null,this.fileHistoryService=void 0,this.getFileReadCache().clear();try{return await this.refreshHierarchicalMemory(),{}}catch(d){return{memoryRefreshError:d}}}setPendingStartupWorktreeNotice(e){this.pendingStartupWorktreeNotice=e}consumePendingStartupWorktreeNotice(){let e=this.pendingStartupWorktreeNotice;return this.pendingStartupWorktreeNotice=null,e}getProjectRoot(){return this.targetDir}getCwd(){return this.targetDir}getWorkspaceContext(){return this.workspaceContext}getToolRegistry(){return this.toolRegistry}async shutdown(){try{if(!this.initialized)return;try{this.chatRecordingService?.finalize(),await this.chatRecordingService?.releaseTranscriptOwnership()}catch{}this.skillManager?.stopWatching(),this.toolRegistry&&await this.toolRegistry.stop(),this.backgroundTaskRegistry.abortAll(),this.monitorRegistry.abortAll({notify:!1}),this.backgroundShellRegistry.abortAll(),await this.cleanupArenaRuntime(),await this.cleanupTeamRuntime()}catch(e){this.debugLogger.error("Error during Config shutdown:",e)}finally{S2()&&await E2()}}getPromptRegistry(){return this.promptRegistry}getDebugMode(){return this.debugMode}getQuestion(){return this.question}getSystemPrompt(){return this.systemPrompt}getAppendSystemPrompt(){return this.appendSystemPrompt}getCoreTools(){return this.getBareMode()?L5e:this.coreTools}getPermissionsAllow(){let e=this.permissionsAllow??[],t=[...this.allowedTools??[]];if(t.length===0)return e.length>0?e:[];let n=[...e];for(let s of t)s&&!n.includes(s)&&n.push(s);return n}getPermissionsAsk(){return this.permissionsAsk}getPermissionsDeny(){let e=this.permissionsDeny??[],t=this.excludeTools??[];if(t.length===0)return e.length>0?e:[];let n=[...e];for(let s of t)s&&!n.includes(s)&&n.push(s);return n}getToolDiscoveryCommand(){return this.toolDiscoveryCommand}getDisabledSlashCommands(){return this.disabledSlashCommands}getDisabledSkillNames(){return this.disabledSkillNamesProvider?.()??N5e}getDisabledTools(){return this.disabledTools}setDisabledTools(e){this.disabledTools=new Set(e)}getToolCallCommand(){return this.toolCallCommand}getMcpServerCommand(){return this.mcpServerCommand}mcpTransportPool;setMcpTransportPool(e){this.mcpTransportPool=e}getMcpTransportPool(){return this.mcpTransportPool}getSettingsMcpServers(){return this.mcpServers}getMcpServers(){let e={...this.mcpServers||{}},t=this.getActiveExtensions();for(let n of t)Object.entries(n.config.mcpServers||{}).forEach(([s,o])=>{e[s]||(e[s]={...o,extensionName:n.config.name})});for(let[n,s]of this.runtimeMcpServers)e[n]=s;return this.allowedMcpServers&&(e=Object.fromEntries(Object.entries(e).filter(([n])=>this.allowedMcpServers?.includes(n)))),e}getExcludedMcpServers(){return this.excludedMcpServers}setExcludedMcpServers(e){this.excludedMcpServers=e}isMcpServerDisabled(e){return this.excludedMcpServers?.includes(e)??!1}isMcpServerPendingApproval(e){return this.pendingMcpServers?.includes(e)??!1}approveMcpServerForSession(e){this.pendingMcpServers&&(this.pendingMcpServers=this.pendingMcpServers.filter(t=>t!==e))}addMcpServers(e){if(this.initialized)throw new Error("Cannot modify mcpServers after initialization");this.mcpServers={...this.mcpServers,...e}}addRuntimeMcpServer(e,t){this.runtimeMcpServers.set(e,t)}removeRuntimeMcpServer(e){return this.runtimeMcpServers.delete(e)}isLspEnabled(){return this.lspEnabled&&!this.getBareMode()}getLspClient(){return this.lspClient}getLspStatusSnapshot(){if(!this.isLspEnabled())return this.createLspStatusSnapshot(!1);let e=this.lspClient?.getStatusSnapshot?.();return e?{...e,enabled:!0,initializationError:this.lspInitializationError??e.initializationError}:this.lspClient?{...this.createLspStatusSnapshot(!0),statusUnavailable:!0}:this.createLspStatusSnapshot(!0,this.lspInitializationError??"LSP client is not initialized")}createLspStatusSnapshot(e,t){return{enabled:e,configuredServers:0,readyServers:0,failedServers:0,inProgressServers:0,notStartedServers:0,servers:[],...t?{initializationError:t}:{}}}setLspClient(e){if(this.initialized)throw new Error("Cannot set LSP client after initialization");this.lspClient=e}setLspInitializationError(e){if(this.initialized)throw new Error("Cannot set LSP status after initialization");this.lspInitializationError=e instanceof Error?e.message:e}getSessionSubagents(){return this.sessionSubagents}setSessionSubagents(e){if(this.initialized)throw new Error("Cannot modify sessionSubagents after initialization");this.sessionSubagents=e}getSdkMode(){return this.sdkMode}setSdkMode(e){this.sdkMode=e}getUserMemory(){return this.userMemory}getOutputLanguageFilePath(){return this.outputLanguageFilePath}setOutputLanguageFilePath(e){this.outputLanguageFilePath=e}setUserMemory(e){this.userMemory=e}getGeminiMdFileCount(){return this.geminiMdFileCount}setGeminiMdFileCount(e){this.geminiMdFileCount=e}getArenaManager(){return this.arenaManager}setArenaManager(e){this.arenaManager=e,this.arenaManagerChangeCallback?.(e)}onArenaManagerChange(e){this.arenaManagerChangeCallback=e}getArenaAgentClient(){return this.arenaAgentClient}getAgentsSettings(){return this.agentsSettings}getTeamManager(){return this.teamManager}setTeamManager(e){this.teamManager=e;for(let t of this.teamManagerChangeCallbacks)t(e)}onTeamManagerChange(e,t){t&&this.teamManagerChangeCallbacks.delete(t),e&&this.teamManagerChangeCallbacks.add(e)}getTeamContext(){return this.teamContext}setTeamContext(e){this.teamContext=e}async cleanupTeamRuntime(){let e=this.teamManager;e&&(await e.cleanup(),this.setTeamManager(null),this.setTeamContext(null))}getWorktreeSymlinkDirectories(){return this.worktreeSettings.symlinkDirectories??[]}async cleanupArenaRuntime(e){let t=this.arenaManager;t&&(!e&&this.agentsSettings.arena?.preserveArtifacts?await t.cleanupRuntime():await t.cleanup(),this.setArenaManager(null))}getApprovalMode(){return this.approvalMode}getAutoModeSettings(){return this.permissionsAutoMode}getAutoModeDenialState(){return this.autoModeDenialState}setAutoModeDenialState(e){this.autoModeDenialState=e}getPrePlanMode(){return this.prePlanMode??"default"}getPlanGateState(){return this.planGateState}setApprovalMode(e){if(!this.isTrustedFolder()&&e!=="default"&&e!=="plan")throw new _j("Cannot enable privileged approval modes in an untrusted folder.");e==="plan"&&this.approvalMode!=="plan"?(this.prePlanMode=this.approvalMode,this.planGateState=bq(++this.planGateEntryCounter)):e!=="plan"&&this.approvalMode==="plan"&&(this.prePlanMode=void 0,this.planGateState=void 0);let t=e==="auto"?"default":e,n=this.approvalMode;this.permissionManager&&n==="auto"&&this.permissionManager.restoreDangerousRules(),n!==t&&(this.autoModeDenialState=lI()),this.approvalMode=t}getPlansDir(){return this.plansDir}assertPlansDirWithinTargetDir(){this.plansDirectoryConfigured&&fe.assertPathWithinDirectory(this.plansDir,this.targetDir,"plansDirectory must resolve within the project root.")}assertPlanFilePathWithinTargetDir(e){this.plansDirectoryConfigured&&fe.assertPathWithinDirectory(e,this.targetDir,"plansDirectory must resolve within the project root.")}addLegacyPlanLocationWarning(){try{if(!this.plansDirectoryConfigured)return;let e=fe.getPlansDir(),t=this.getPlanFileNames(e);if(t.length===0)return;let n=new Set(this.getPlanFileNames(this.plansDir));if(t.filter(o=>!n.has(o)).length===0)return;this.warnings.push(`Warning: Saved plan files exist at ${e}, but plansDirectory is configured to use ${this.plansDir}. Move existing plan files to ${this.plansDir} if you want to keep using them.`)}catch(e){let t=`Failed to check legacy plan directory migration warning: ${e instanceof Error?e.message:String(e)}`;this.warnings.push(t),this.debugLogger.warn(t,e)}}getPlanFileNames(e){try{return bt.readdirSync(e).filter(t=>t.endsWith(".md"))}catch(t){let n=t.code;if(n==="ENOENT")return[];if(n==="EACCES"||n==="EPERM"){let s=`Failed to read plan directory ${e}: ${t instanceof Error?t.message:String(t)}`;return this.warnings.push(s),this.debugLogger.warn(s,t),[]}throw t}}getPlanFilePath(){return Vr.join(this.plansDir,`${fe.sanitizePlanSessionId(this.sessionId)}.md`)}savePlan(e){this.assertPlansDirWithinTargetDir();let t=this.getPlanFilePath(),n=Vr.dirname(t);bt.mkdirSync(n,{recursive:!0});let s=t+".tmp";bt.writeFileSync(s,e,"utf-8");try{bt.renameSync(s,t)}catch(o){if(o.code!=="EXDEV")throw o;bt.copyFileSync(s,t),bt.unlinkSync(s)}try{this.assertPlanFilePathWithinTargetDir(t)}catch(o){try{bt.unlinkSync(t)}catch{}throw o}}loadPlan(){this.assertPlansDirWithinTargetDir();let e=this.getPlanFilePath();this.assertPlanFilePathWithinTargetDir(e);try{return bt.readFileSync(e,"utf-8")}catch(t){if(typeof t=="object"&&t!==null&&"code"in t&&t.code==="ENOENT")return;throw t}}getInputFormat(){return this.inputFormat}getIncludePartialMessages(){return this.includePartialMessages}getAccessibility(){return this.accessibility}getTelemetryEnabled(){return this.telemetrySettings.enabled??!1}getTelemetryLogPromptsEnabled(){return this.telemetrySettings.logPrompts??!0}getTelemetryIncludeSensitiveSpanAttributes(){return this.telemetrySettings.includeSensitiveSpanAttributes??!1}getTelemetryOtlpEndpoint(){return this.telemetrySettings.otlpEndpoint??sz}getTelemetryOtlpProtocol(){return this.telemetrySettings.otlpProtocol??"grpc"}getTelemetryOtlpTracesEndpoint(){return this.telemetrySettings.otlpTracesEndpoint}getTelemetryOtlpLogsEndpoint(){return this.telemetrySettings.otlpLogsEndpoint}getTelemetryOtlpMetricsEndpoint(){return this.telemetrySettings.otlpMetricsEndpoint}getTelemetryTarget(){return this.telemetrySettings.target??CP}getTelemetryResourceAttributes(){return this.telemetrySettings.resourceAttributes??{}}getTelemetryMetricsIncludeSessionId(){return this.telemetrySettings.metrics?.includeSessionId??!1}getTelemetryResourceAttributeWarnings(){return this.telemetrySettings.resourceAttributeWarnings??[]}getOutboundCorrelationPropagateTraceContext(){return this.outboundCorrelationSettings.propagateTraceContext??!1}getTelemetryOutfile(){return this.telemetrySettings.outfile}getGitCoAuthor(){return this.gitCoAuthor}getGeminiClient(){return this.geminiClient}getMemoryPressureMonitor(){if(!Object.prototype.hasOwnProperty.call(this,"memoryPressureMonitor")&&this.memoryPressureMonitor){let t=this.memoryPressureConfig;if(!t)throw new Error("Inherited memory pressure monitor is missing config");this.memoryPressureConfig={...t},this.memoryPressureMonitor=new jb(this,this.memoryPressureConfig)}return this.memoryPressureMonitor}getCronScheduler(){return this.cronScheduler||(this.cronScheduler=new CT(this.getProjectRoot())),this.cronScheduler}isCronEnabled(){return Qt.env.MATILDA_CODE_DISABLE_CRON==="1"?!1:this.cronEnabled}isAgentTeamEnabled(){return Qt.env.MATILDA_CODE_ENABLE_AGENT_TEAM==="1"?!0:this.agentTeamEnabled}isWorkflowsEnabled(){return Qt.env.MATILDA_CODE_DISABLE_WORKFLOWS==="1"?!1:Qt.env.MATILDA_CODE_ENABLE_WORKFLOWS==="1"?!0:this.workflowsEnabled}setWorkflowsEnabled(e){this.workflowsEnabled=e}isComputerUseEnabled(){return this.computerUseEnabled}getComputerUseMaxImageDimension(){return this.computerUseMaxImageDimension}getEmitToolUseSummaries(){let e=Qt.env.MATILDA_CODE_EMIT_TOOL_USE_SUMMARIES;return e==="0"||e==="false"?!1:e==="1"||e==="true"?!0:this.emitToolUseSummaries}getEnableRecursiveFileSearch(){return this.fileFiltering.enableRecursiveFileSearch}getFileFilteringEnableFuzzySearch(){return this.fileFiltering.enableFuzzySearch}getFileFilteringRespectGitIgnore(){return this.fileFiltering.respectGitIgnore}getFileFilteringRespectMatildaIgnore(){return this.fileFiltering.respectMatildaIgnore}getFileFilteringOptions(){return{respectGitIgnore:this.fileFiltering.respectGitIgnore,respectMatildaIgnore:this.fileFiltering.respectMatildaIgnore}}getCustomExcludes(){return[]}getFileCheckpointingEnabled(){return this.fileCheckpointingEnabled}enableFileCheckpointing(){this.fileCheckpointingEnabled=!0,this.fileHistoryService=void 0}getFileHistoryService(){if(!this.fileHistoryService){let e=new Ov(this.sessionId,this.fileCheckpointingEnabled,this.cwd,n=>{this.fileHistoryService===e&&this.getChatRecordingService()?.recordFileHistorySnapshot(n)});this.fileHistoryService=e;let t=this.sessionData?.fileHistorySnapshots;t?.length&&e.isEnabled()&&(e.restoreFromSnapshots(t),e.validateRestoredSnapshots().catch(n=>{this.debugLogger.error(`FileHistory: validateRestoredSnapshots failed: ${n}`)}))}return this.fileHistoryService}getProxy(){return _ue(this.proxy)}getWorkingDir(){return this.cwd}getBugCommand(){return this.bugCommand}getFileService(){return this.fileDiscoveryService||(this.fileDiscoveryService=new xl(this.targetDir)),this.fileDiscoveryService}getUsageStatisticsEnabled(){return this.usageStatisticsEnabled}getExtensionContextFilePaths(){return[...this.getActiveExtensions().flatMap(t=>t.contextFiles),...this.outputLanguageFilePath?[this.outputLanguageFilePath]:[]]}getExperimentalZedIntegration(){return this.experimentalZedIntegration}getListExtensions(){return this.listExtensions}getExtensionManager(){return this.extensionManager}getHookSystem(){return this.hookSystem}hasHooksForEvent(e,t){return this.hookSystem?.hasHooksForEvent(e,t??this.getSessionId())??!1}getDisableAllHooks(){return this.disableAllHooks||this.getBareMode()}getStopHookBlockingCap(){return this.stopHookBlockingCap}getManagedAutoMemoryEnabled(){return this.enableManagedAutoMemory&&!this.getBareMode()}getManagedAutoDreamEnabled(){return this.enableManagedAutoDream&&!this.getBareMode()}getAutoSkillEnabled(){return this.enableAutoSkill&&!this.getBareMode()}getPreventSystemSleepEnabled(){return this.preventSystemSleep}getMemoryManager(){return this.memoryManager}getMessageBus(){return this.messageBus}setMessageBus(e){this.messageBus=e}getProjectHooks(){return this.getBareMode()||!this.isTrustedFolder()?void 0:this.projectHooks??this.hooks}getUserHooks(){return this.getBareMode()?void 0:this.userHooks??this.hooks}getExtensions(){let e=this.extensionManager.getLoadedExtensions();if(this.overrideExtensions){let t=new Set(this.overrideExtensions.map(n=>n.toLowerCase()));return e.filter(n=>t.has(n.name.toLowerCase()))}else return e}getExplicitExtensionNames(){return(this.overrideExtensions??[]).filter(e=>e.trim()!==""&&e.toLowerCase()!=="none")}getActiveExtensions(){return this.getExtensions().filter(e=>e.isActive)}getBlockedMcpServers(){let e={...this.mcpServers||{}},t=this.getActiveExtensions();for(let s of t)Object.entries(s.config.mcpServers||{}).forEach(([o,a])=>{e[o]||(e[o]={...a,extensionName:s.config.name})});let n=[];return this.allowedMcpServers&&Object.entries(e).forEach(([s,o])=>{this.allowedMcpServers?.includes(s)||n.push({name:s,extensionName:o.extensionName||""})}),n}getNoBrowser(){return this.noBrowser}isBrowserLaunchSuppressed(){return this.getNoBrowser()||!lz()}getIdeMode(){return this.ideMode}getFolderTrustFeature(){return this.folderTrustFeature}getFolderTrust(){return this.folderTrust}getAllowedHttpHookUrls(){return this.getBareMode()?[]:this.allowedHttpHookUrls}isTrustedFolder(){let e=Uu.get();return e?.workspaceState?.isTrusted!==void 0?e.workspaceState.isTrusted:this.trustedFolder??!0}setIdeMode(e){this.ideMode=e}getAuthType(){return this.getContentGeneratorConfig()?.authType}getCliVersion(){return this.cliVersion}getChannel(){return this.channel}getJsonFd(){return this.jsonFd}getJsonFile(){return this.jsonFile}getJsonPartials(){return this.jsonPartials}getJsonSchema(){return this.jsonSchema}getInputFile(){return this.inputFile}getDefaultFileEncoding(){return this.defaultFileEncoding}getFileSystemService(){return this.fileSystemService}setFileSystemService(e){this.fileSystemService=e}getChatCompression(){return this.chatCompression}isInteractive(){return this.interactive}getUseRipgrep(){return this.useRipgrep}getUseBuiltinRipgrep(){return this.useBuiltinRipgrep}getShouldUseNodePtyShell(){return this.shouldUseNodePtyShell}getSkipNextSpeakerCheck(){return this.skipNextSpeakerCheck}getShellExecutionConfig(){return this.shellExecutionConfig}setShellExecutionConfig(e){this.shellExecutionConfig={terminalWidth:e.terminalWidth??this.shellExecutionConfig.terminalWidth,terminalHeight:e.terminalHeight??this.shellExecutionConfig.terminalHeight,showColor:e.showColor??this.shellExecutionConfig.showColor,pager:e.pager??this.shellExecutionConfig.pager,maxBufferedOutputBytes:e.maxBufferedOutputBytes??this.shellExecutionConfig.maxBufferedOutputBytes}}getScreenReader(){return this.accessibility.screenReader??!1}getSkipLoopDetection(){return this.skipLoopDetection}getSkipStartupContext(){return this.skipStartupContext}getBareMode(){return this.bareMode}getTruncateToolOutputThreshold(){return this.truncateToolOutputThreshold<=0?Number.POSITIVE_INFINITY:this.truncateToolOutputThreshold}getTruncateToolOutputLines(){return this.truncateToolOutputLines<=0?Number.POSITIVE_INFINITY:this.truncateToolOutputLines}getToolOutputBatchBudget(){return this.toolOutputBatchBudget<=0?Number.POSITIVE_INFINITY:this.toolOutputBatchBudget}trackToolResultBytes(e){this.toolResultBudget.bytesWritten+=e}getToolResultBytesWritten(){return this.toolResultBudget.bytesWritten}getOutputFormat(){return this.outputFormat}getChatRecordingService(){if(this.chatRecordingEnabled)return this.chatRecordingService||(this.chatRecordingService=new oh(this)),this.chatRecordingService}getTranscriptPath(){if(!this.chatRecordingEnabled)return"";let e=this.sessionStorage.getProjectDir(),n=`${this.getSessionId()}.jsonl`;return Vr.join(e,"chats",n)}getSessionService(){return this.sessionService||(this.sessionService=new Uv(this.sessionStorageDir,this.sessionRuntimeBaseDir)),this.sessionService}getFileExclusions(){return this.fileExclusions}getSubagentManager(){return this.subagentManager}getBackgroundTaskRegistry(){return this.backgroundTaskRegistry}getMonitorRegistry(){return this.monitorRegistry}getBackgroundAgentResumeService(){return this.backgroundAgentResumeService||(this.backgroundAgentResumeService=new KA(this)),this.backgroundAgentResumeService}async loadPausedBackgroundAgents(e=this.getSessionId()){return this.getBackgroundAgentResumeService().loadPausedBackgroundAgents(e)}async resumeBackgroundAgent(e,t){return this.getBackgroundAgentResumeService().resumeBackgroundAgent(e,t)}abandonBackgroundAgent(e){return this.getBackgroundAgentResumeService().abandonBackgroundAgent(e)}getBackgroundShellRegistry(){return this.backgroundShellRegistry}getWorkflowRunRegistry(){return this.workflowRunRegistry}getFileReadCache(){return Object.prototype.hasOwnProperty.call(this,"fileReadCache")||(this.fileReadCache=new Py),this.fileReadCache}getFileReadCacheDisabled(){return this.fileReadCacheDisabled}getShouldAvoidPermissionPrompts(){return!1}getSkillManager(){return this.skillManager}setModelInvocableCommandsProvider(e){this.modelInvocableCommandsProvider=e}getModelInvocableCommandsProvider(){return this.modelInvocableCommandsProvider}setModelInvocableCommandsExecutor(e){this.modelInvocableCommandsExecutor=e}getModelInvocableCommandsExecutor(){return this.modelInvocableCommandsExecutor}addInlineAnnouncedSkillKeys(e){for(let t of e)this.pendingInlineAnnouncedSkillKeys.add(t)}consumeInlineAnnouncedSkillKeys(){let e=this.pendingInlineAnnouncedSkillKeys;return this.pendingInlineAnnouncedSkillKeys=new Set,e}getPermissionManager(){return this.permissionManager}getOnPersistPermissionRule(){return this.onPersistPermissionRuleCallback}getOnRefreshPermissionsFromDisk(){return this.onRefreshPermissionsFromDiskCallback}async createToolRegistry(e,t){let n=new mT(this,this.eventEmitter,e),s=async(a,l)=>{let c=!0;try{c=this.permissionManager?await this.permissionManager.isToolEnabled(a):!0}catch(u){this.debugLogger.warn(`Failed to check permissions for tool "${a}", skipping registration:`,u);return}c&&n.registerFactory(a,l)},o=async()=>{if(!this.jsonSchema||t?.forSubAgent)return;let a=this.jsonSchema;await s(R.STRUCTURED_OUTPUT,async()=>{let{SyntheticOutputTool:l}=await import("./syntheticOutput-QEUQIVQJ.js");return new l(a)})};if(this.getBareMode())return await s(R.READ_FILE,async()=>{let{ReadFileTool:a}=await import("./read-file-J5UBJYDO.js");return new a(this)}),await s(R.EDIT,async()=>{let{EditTool:a}=await import("./edit-EZH4FRBA.js");return new a(this)}),await s(R.NOTEBOOK_EDIT,async()=>{let{NotebookEditTool:a}=await import("./notebook-edit-FNCOZCKQ.js");return new a(this)}),await s(R.SHELL,async()=>{let{ShellTool:a}=await import("./shell-CTE2Z3PU.js");return new a(this)}),await o(),this.debugLogger.debug(`ToolRegistry created: ${JSON.stringify(n.getAllToolNames())} (${n.getAllToolNames().length} tools)`),n;if(await s(R.TOOL_SEARCH,async()=>{let{ToolSearchTool:a}=await import("./tool-search-OWJC3UTX.js");return new a(this)}),await s(R.AGENT,async()=>{let{AgentTool:a}=await import("./agent-IL7T4I2K.js");return new a(this)}),await s(R.TASK_STOP,async()=>{let{TaskStopTool:a}=await import("./task-stop-JO3CXG2K.js");return new a(this)}),await s(R.SEND_MESSAGE,async()=>{let{SendMessageTool:a}=await import("./send-message-XXRROIL7.js");return new a(this)}),await s(R.SKILL,async()=>{let{SkillTool:a}=await import("./skill-ZEEJW7MU.js");return new a(this)}),await s(R.LS,async()=>{let{LSTool:a}=await import("./ls-CLDNF3YS.js");return new a(this)}),await s(R.READ_FILE,async()=>{let{ReadFileTool:a}=await import("./read-file-J5UBJYDO.js");return new a(this)}),this.getUseRipgrep()){let a=!1,l;try{a=await zK(this.getUseBuiltinRipgrep())}catch(c){l=ne(c)}a?await s(R.GREP,async()=>{let{RipGrepTool:c}=await import("./ripGrep-6EYEXCRW.js");return new c(this)}):(x2(this,new z2(this.getUseRipgrep(),this.getUseBuiltinRipgrep(),l||"ripgrep is not available")),await s(R.GREP,async()=>{let{GrepTool:c}=await import("./grep-RITQSEH3.js");return new c(this)}))}else await s(R.GREP,async()=>{let{GrepTool:a}=await import("./grep-RITQSEH3.js");return new a(this)});if(await s(R.GLOB,async()=>{let{GlobTool:a}=await import("./glob-ZZX5YQEW.js");return new a(this)}),await s(R.EDIT,async()=>{let{EditTool:a}=await import("./edit-EZH4FRBA.js");return new a(this)}),await s(R.NOTEBOOK_EDIT,async()=>{let{NotebookEditTool:a}=await import("./notebook-edit-FNCOZCKQ.js");return new a(this)}),await s(R.WRITE_FILE,async()=>{let{WriteFileTool:a}=await import("./write-file-4K5POBXD.js");return new a(this)}),await s(R.SHELL,async()=>{let{ShellTool:a}=await import("./shell-CTE2Z3PU.js");return new a(this)}),await s(R.TODO_WRITE,async()=>{let{TodoWriteTool:a}=await import("./todoWrite-7BZMVNBC.js");return new a(this)}),await s(R.UPDATE_GOAL,async()=>{let{UpdateGoalTool:a}=await import("./update-goal-CF6G57J7.js");return new a(this)}),await s(R.ASK_USER_QUESTION,async()=>{let{AskUserQuestionTool:a}=await import("./askUserQuestion-MJ4FTAOQ.js");return new a(this)}),this.sdkMode||(await s(R.EXIT_PLAN_MODE,async()=>{let{ExitPlanModeTool:a}=await import("./exitPlanMode-XIZ2N2BH.js");return new a(this)}),await s(R.ENTER_PLAN_MODE,async()=>{let{EnterPlanModeTool:a}=await import("./enterPlanMode-3RRWLKZY.js");return new a(this)})),await s(R.ENTER_WORKTREE,async()=>{let{EnterWorktreeTool:a}=await import("./enter-worktree-2NFK4Q5V.js");return new a(this)}),await s(R.EXIT_WORKTREE,async()=>{let{ExitWorktreeTool:a}=await import("./exit-worktree-ROPZ6KRN.js");return new a(this)}),await s(R.WEB_FETCH,async()=>{let{WebFetchTool:a}=await import("./web-fetch-K575OWZ7.js");return new a(this)}),await s(R.WEB_SEARCH,async()=>{let{WebSearchTool:a}=await import("./web-search-F6JRBXFV.js");return new a(this)}),await s(R.SYMBOL_SEARCH,async()=>{let{SymbolSearchTool:a}=await import("./symbol-search-3MVTK4KV.js");return new a(this)}),this.isLspEnabled()&&this.getLspClient()&&await s(R.LSP,async()=>{let{LspTool:a}=await import("./lsp-7SKRKR5Q.js");return new a(this)}),await o(),this.isCronEnabled()&&(await s(R.CRON_CREATE,async()=>{let{CronCreateTool:a}=await import("./cron-create-BTTPO3JC.js");return new a(this)}),await s(R.CRON_LIST,async()=>{let{CronListTool:a}=await import("./cron-list-J4HRR46K.js");return new a(this)}),await s(R.CRON_DELETE,async()=>{let{CronDeleteTool:a}=await import("./cron-delete-U55RHRID.js");return new a(this)})),this.isAgentTeamEnabled()&&(await s(R.TEAM_CREATE,async()=>{let{TeamCreateTool:a}=await import("./team-create-XO32YS6Q.js");return new a(this)}),await s(R.TEAM_DELETE,async()=>{let{TeamDeleteTool:a}=await import("./team-delete-4YYLUV23.js");return new a(this)}),await s(R.TASK_CREATE,async()=>{let{TaskCreateTool:a}=await import("./task-create-AEJQ73GE.js");return new a(this)}),await s(R.TASK_UPDATE,async()=>{let{TaskUpdateTool:a}=await import("./task-update-3YY37VFN.js");return new a(this)}),await s(R.TASK_LIST,async()=>{let{TaskListTool:a}=await import("./task-list-ZEJTNZ2O.js");return new a(this)})),this.isWorkflowsEnabled()&&await s(R.WORKFLOW,async()=>{let{WorkflowTool:a}=await import("./workflow-UFWS3C22.js");return new a(this)}),this.isComputerUseEnabled()){let{registerComputerUseTools:a}=await import("./computer-use-LL6VH2YY.js");await a(s,this)}if(await s(R.MONITOR,async()=>{let{MonitorTool:a}=await import("./monitor-DNWGCVNF.js");return new a(this)}),this.pendingMcpBudgetCallback){let a=n.getMcpClientManager();a&&typeof a.setOnBudgetEvent=="function"&&a.setOnBudgetEvent(this.pendingMcpBudgetCallback),this.pendingMcpBudgetCallback=void 0}return t?.skipDiscovery||await n.discoverAllTools(),this.debugLogger.debug(`ToolRegistry created: ${JSON.stringify(n.getAllToolNames())} (${n.getAllToolNames().length} tools)`),n}setMcpBudgetEventCallback(e){if(this.toolRegistry){let t=this.toolRegistry.getMcpClientManager?.();t&&typeof t.setOnBudgetEvent=="function"&&t.setOnBudgetEvent(e),this.pendingMcpBudgetCallback=void 0;return}this.pendingMcpBudgetCallback=e}};g();var F5e="refs/notes/ai-attribution";function Gde(r,e){let t=JSON.stringify(r);return Buffer.byteLength(t,"utf-8")>30720?null:{command:"git",args:["notes",`--ref=${F5e}`,"add","-f","-m",t,e]}}var bhe=Ge(il(),1);g();import*as Vde from"node:fs";var zb=class extends Error{constructor(t,n){super(t);this.errorType=n;Object.setPrototypeOf(this,new.target.prototype)}name="StructuredToolError"};function $R(r){return r instanceof zb||typeof r=="object"&&r!==null&&r.name==="StructuredToolError"&&"errorType"in r}async function Kde(r,e,t,n={}){let s;try{s=await Vde.promises.stat(e)}catch(h){let f=h?.code;if(f==="ENOENT"){if(n.expectExisting){let w=`File ${e} disappeared after the model read it (stat now returns ENOENT). Re-read with the ${R.READ_FILE} tool \u2014 the path may have been deleted or moved \u2014 before retrying ${t} it.`;return{ok:!1,type:"file_changed_since_read",rawMessage:w,displayMessage:`file disappeared after last read; re-run ${R.READ_FILE} first.`}}return{ok:!0}}let p=`Could not stat ${e} to verify prior read (${f??"unknown error"}). Re-read with the ${R.READ_FILE} tool, then retry ${t} it.`,y=t==="editing"?"editing this file":"overwriting this file";return{ok:!1,type:"prior_read_verification_failed",rawMessage:p,displayMessage:`cannot verify prior read of ${e}; re-run ${R.READ_FILE} before ${y}.`}}if(s.isDirectory()){let h=t==="editing"?"edit":"overwrite",f=`${e} is a directory. The Edit / WriteFile tools only operate on regular files. Use a different mechanism (e.g. the shell tool) if you need to ${h} the contents of this directory.`;return{ok:!1,type:"target_is_directory",rawMessage:f,displayMessage:`path is a directory; cannot ${h} via this tool.`}}if(!s.isFile()){let h=t==="editing"?"edit":"overwrite",f=`${e} is a FIFO / socket / character or block device. The Edit / WriteFile tools only operate on regular files; the ${R.READ_FILE} tool also rejects these targets. Use a different mechanism (e.g. shell tool with the appropriate command) if you need to ${h} this path.`;return{ok:!1,type:"edit_requires_prior_read",rawMessage:f,displayMessage:`special file; cannot ${h} via this tool.`}}let o=r.check(s);if(o.state==="fresh"&&o.entry.lastReadAt!==void 0&&o.entry.lastReadCacheable)return{ok:!0};if(o.state==="stale"){let h=`File ${e} has been modified since you last read it (mtime or size changed). Re-read it with the ${R.READ_FILE} tool before ${t} it to ensure your changes are based on current content.`;return{ok:!1,type:"file_changed_since_read",rawMessage:h,displayMessage:`file changed since last read; re-run ${R.READ_FILE} first.`}}if(o.state==="fresh"&&o.entry.lastReadAt!==void 0&&!o.entry.lastReadCacheable){let h=t==="editing"?"edit":"overwrite",f=`File ${e} is a binary / image / audio / video / PDF / notebook payload that the ${R.READ_FILE} tool returns as a structured value rather than as plain text. The Edit / WriteFile tools cannot mutate that payload safely \u2014 re-reading it would not change this. If this is a Jupyter notebook (.ipynb), use the ${R.NOTEBOOK_EDIT} tool for cell-level edits after reading it. For other non-text files, use a different mechanism (e.g. shell tool with an appropriate writer) if you need to ${h} it.`;return{ok:!1,type:"edit_requires_prior_read",rawMessage:f,displayMessage:`non-text payload; cannot ${h} via this tool.`}}let a=t==="editing"?"edit":"overwrite",l=t==="editing"?"editing this file":"overwriting this file";if(t==="editing"&&n.autoStampUnread!==!1)return r.recordRead(e,s,{full:!0,cacheable:!0}),{ok:!0};let u=t==="editing"?`(a partial read with offset / limit is fine \u2014 you only need to have seen the bytes you intend to ${a})`:"(read the full file \u2014 overwriting replaces every byte, so any unseen bytes would be discarded)",d=`File ${e} has not been read in this session. Use the ${R.READ_FILE} tool first to load the current content ${u} before ${t} it.`;return{ok:!1,type:"edit_requires_prior_read",rawMessage:d,displayMessage:`${R.READ_FILE} required before ${l}.`}}g();var Zde=Ge(il(),1);var Yde=new Set(["+","?","|","(",")","{","}"]),$5e=new Set(["*","+","?"]);function Qde(r){let e=r.trim(),t=e.match(/^\s*sed\s+/);if(!t)return null;let n;try{n=(0,Zde.parse)(e.slice(t[0].length),f=>`$${f}`)}catch{return null}let s=[];for(let f of n){if(typeof f!="string")return null;s.push(f)}let o=!1,a=!1,l=null,c=null,u=0;for(;u<s.length;){let f=s[u];if(U5e(f)){for(let p of f.slice(1))p==="i"?o=!0:a=!0;u++;continue}if(f==="-i"){o=!0,u++,u<s.length&&s[u]===""&&u++;continue}if(f==="--in-place"){o=!0,u++;continue}if(f==="--in-place="){o=!0,u++;continue}if(f.startsWith("-i")||f.startsWith("--in-place="))return null;if(f==="-E"||f==="-r"||f==="--regexp-extended"){a=!0,u++;continue}if(f==="-e"||f==="--expression"){if(l!==null||u+1>=s.length)return null;l=s[u+1],u+=2;continue}if(f.startsWith("--expression=")){if(l!==null)return null;l=f.slice(13),u++;continue}if(f.startsWith("-"))return null;if(l===null)l=f;else if(c===null)c=f;else return null;u++}if(!o||!l||!c||H5e(l)||c.startsWith("~")||c.includes("$"))return null;let d=V5e(l);if(d===null)return null;let h={filePath:c,...d,extendedRegex:a};return B5e(h)?h:null}function U5e(r){if(!r.startsWith("-")||r.startsWith("--")||r.length<=2)return!1;let e=r.slice(1);return!(e.startsWith("i")||!/^[Eri]+$/u.test(e))}function H5e(r){return r.includes("`")||/\$(?:[A-Za-z_][A-Za-z0-9_]*|\{|\(|\d|[#?@$!*])/u.test(r)}function B5e(r){try{let e=rhe(r);return j5e(e)||z5e(e)||(new RegExp(e),q5e(r.replacement,W5e(e)))?!1:!G5e(e)}catch{return!1}}function j5e(r){return/\[\[:[A-Za-z]+:\]\]/u.test(r)}function z5e(r){return/\\[<>dDwWsS]/u.test(r)}function q5e(r,e){for(let t=0;t<r.length;t++){if(r[t]!=="\\")continue;let n=r[t+1];if(n!==void 0&&n>="1"&&n<="9"&&Number(n)>e)return!0;t++}return!1}function W5e(r){let e=0;for(let t=0;t<r.length;t++){let n=r[t];if(n==="\\"){t++;continue}if(n==="["){t=ehe(r,t);continue}n==="("&&r[t+1]!=="?"&&e++}return e}function G5e(r){let e=[];for(let t=0;t<r.length;t++){let n=r[t];if(n==="\\"){t++;continue}if(n==="["){t=ehe(r,t);continue}if(n==="("){e.push({hasAlternation:!1,hasQuantifier:!1});continue}if(n==="|"&&e.length>0){e[e.length-1].hasAlternation=!0;continue}if(n===")"){let o=e.pop();if(o===void 0)continue;let a=Jde(r,t+1);if(a!==null){if(o.hasAlternation||o.hasQuantifier)return!0;e.length>0&&(e[e.length-1].hasQuantifier=!0),t=a-1}if(e.length>0){let l=e[e.length-1];l.hasAlternation||=o.hasAlternation,l.hasQuantifier||=o.hasQuantifier}continue}let s=Jde(r,t);s!==null&&(e.length>0&&(e[e.length-1].hasQuantifier=!0),t=s-1)}return!1}function ehe(r,e){for(let t=e+1;t<r.length;t++){if(r[t]==="\\"){t++;continue}if(r[t]==="]")return t}return r.length-1}function Jde(r,e){let t=r[e];if(t===void 0)return null;if($5e.has(t))return e+1;if(t!=="{")return null;let n=e+1,s=!1;for(;Xde(r[n]);)s=!0,n++;if(!s)return null;if(r[n]===",")for(n++;Xde(r[n]);)n++;return r[n]==="}"?n+1:null}function Xde(r){return r!==void 0&&r>="0"&&r<="9"}function V5e(r){if(/[\r\n]/.test(r)||!r.startsWith("s/"))return null;let e=r.slice(2),t="",n="",s="",o="pattern";for(let a=0;a<e.length;a++){let l=e[a];if(l==="\\"&&a+1<e.length){let c=l+e[a+1];o==="pattern"?t+=c:o==="replacement"?n+=c:s+=c,a++;continue}if(l==="/"){if(o==="pattern")o="replacement";else if(o==="replacement")o="flags";else return null;continue}o==="pattern"?t+=l:o==="replacement"?n+=l:s+=l}return!t||o!=="flags"||!K5e(s)||Y5e(n)?null:{pattern:t,replacement:n,flags:s}}function K5e(r){if(!/^[g0-9]*$/.test(r))return!1;let e=r.match(/\d+/g)??[];return e.length>1?!1:e.length===0?!0:/^[1-9][0-9]*$/.test(e[0])}function Y5e(r){for(let e=0;e<r.length;e++){if(r[e]!=="\\")continue;let t=r[e+1];if(t===void 0||!/[\\/&1-9]/.test(t))return!0;e++}return!1}function the(r,e){if(r.length===0)return"";let t=rhe(e),n=X5e(e.flags),s=e.flags.includes("g");try{let o=new RegExp(t,"g"),a=r.split(/(\n)/);return(r.endsWith(`
2199
+ `),A5e.warn(t),{...DR}}return r}function wj(r,e){let t=Qt.env[r];if(!t)return e;let n=Number(t);if(!Number.isFinite(n))throw new Error(`${r} must be a finite number`);return n}var L5e=[R.READ_FILE,R.EDIT,R.NOTEBOOK_EDIT,R.SHELL],N5e=Object.freeze(new Set),qde=!1,xp=class{sessionId;sessionData;pendingStartupWorktreeNotice=null;debugLogger;toolRegistry;pendingMcpBudgetCallback;promptRegistry;subagentManager;memoryPressureConfig;memoryPressureMonitor;backgroundTaskRegistry=new GA;monitorRegistry=new CE;backgroundAgentResumeService;backgroundShellRegistry=new EE;workflowRunRegistry=new kE;fileReadCache=new Py;extensionManager;skillManager=null;permissionManager=null;modelInvocableCommandsProvider=null;modelInvocableCommandsExecutor=null;pendingInlineAnnouncedSkillKeys=new Set;fileSystemService;contentGeneratorConfig;contentGeneratorConfigSources={};contentGenerator;embeddingModel;modelsConfig;modelProvidersConfig;sandbox;targetDir;workspaceContext;debugMode;inputFormat;outputFormat;includePartialMessages;question;systemPrompt;appendSystemPrompt;coreTools;allowedTools;excludeTools;disabledSlashCommands;disabledSkillNamesProvider;disabledTools;permissionsAllow;permissionsAsk;permissionsDeny;permissionsAutoMode;toolDiscoveryCommand;toolCallCommand;mcpServerCommand;mcpServers;runtimeMcpServers=new Map;lspEnabled;lspClient;lspInitializationError;allowedMcpServers;excludedMcpServers;pendingMcpServers;sessionSubagents;userMemory;sdkMode;geminiMdFileCount;conditionalRulesRegistry;contextRuleExcludes;approvalMode;prePlanMode;planGateState;planGateEntryCounter=0;autoModeDenialState=tg();accessibility;telemetrySettings;outboundCorrelationSettings;gitCoAuthor;usageStatisticsEnabled;fileReadCacheDisabled;geminiClient;baseLlmClient;cronScheduler=null;fileFiltering;fileDiscoveryService=null;sessionService=void 0;sessionStorageDir;sessionRuntimeBaseDir;sessionStorage;sessionStoragePinned;chatRecordingService=void 0;fileCheckpointingEnabled;toolResultBudget={bytesWritten:0};fileHistoryService;proxy;cwd;explicitIncludeDirectories;bugCommand;outputLanguageFilePath;noBrowser;folderTrustFeature;folderTrust;ideMode;maxSessionTurns;maxWallTimeSeconds;maxToolCalls;clearContextOnIdle;sessionTokenLimit;listExtensions;overrideExtensions;cliVersion;runtimeStatusEnabled=!1;experimentalZedIntegration=!1;cronEnabled=!0;agentTeamEnabled=!1;workflowsEnabled=!1;computerUseEnabled=!0;computerUseMaxImageDimension;emitToolUseSummaries=!0;chatRecordingEnabled;loadMemoryFromIncludeDirectories=!1;importFormat;chatCompression;interactive;trustedFolder;useRipgrep;useBuiltinRipgrep;shouldUseNodePtyShell;preventSystemSleep;skipNextSpeakerCheck;shellExecutionConfig;arenaManager=null;arenaManagerChangeCallback=null;arenaAgentClient;teamManager=null;teamManagerChangeCallbacks=new Set;teamContext=null;agentsSettings;worktreeSettings;skipLoopDetection;skipStartupContext;bareMode;warnings;allowedHttpHookUrls;onPersistPermissionRuleCallback;onRefreshPermissionsFromDiskCallback;initialized=!1;storage;sessionTransitionMutex=new za;runtimeStatusWrite=Promise.resolve();fileExclusions;truncateToolOutputThreshold;truncateToolOutputLines;toolOutputBatchBudget;eventEmitter;channel;jsonFd;jsonFile;jsonPartials;jsonSchema;inputFile;plansDir;plansDirectoryConfigured;defaultFileEncoding;enableManagedAutoMemory;enableManagedAutoDream;enableAutoSkill;fastModel;modelDisplayName;disableAllHooks;stopHookBlockingCap;userHooks;projectHooks;hooks;hookSystem;messageBus;memoryManager;modelChangeListeners=new Set;constructor(e){this.sessionId=e.sessionId??Bde(),!qde&&Qt.env&&(Qt.env.MATILDA_CODE_SESSION_ID=this.sessionId,qde=!0),this.sessionData=e.sessionData,YR(this),this.debugLogger=F(),this.embeddingModel=e.embeddingModel??TP,this.fileSystemService=new GT,this.sandbox=e.sandbox,this.targetDir=Vr.resolve(e.targetDir),this.sessionStoragePinned=e.sessionStorageDir!==void 0,this.sessionStorageDir=Vr.resolve(e.sessionStorageDir??this.targetDir),this.sessionRuntimeBaseDir=e.sessionRuntimeBaseDir?Vr.resolve(e.sessionRuntimeBaseDir):void 0,this.plansDirectoryConfigured=!!e.plansDirectory?.trim(),this.plansDir=fe.getPlansDir(this.targetDir,e.plansDirectory),this.explicitIncludeDirectories=Array.from(new Set(e.includeDirectories??[])),this.workspaceContext=new Da(this.targetDir,this.explicitIncludeDirectories),this.debugMode=e.debugMode,this.inputFormat=e.inputFormat??"text";let t=O5e(e.outputFormat??e.output?.format);this.outputFormat=t??"text",this.includePartialMessages=e.includePartialMessages??!1,this.question=e.question,this.systemPrompt=e.systemPrompt,this.appendSystemPrompt=e.appendSystemPrompt,this.coreTools=e.coreTools,this.allowedTools=e.allowedTools,this.excludeTools=e.excludeTools,this.disabledSlashCommands=Object.freeze([...e.disabledSlashCommands??[]]),this.disabledSkillNamesProvider=e.disabledSkillNamesProvider??null,this.disabledTools=new Set(e.disabledTools??[]),this.permissionsAllow=e.permissions?.allow||[],this.permissionsAsk=e.permissions?.ask||[],this.permissionsDeny=e.permissions?.deny||[],this.permissionsAutoMode=e.permissions?.autoMode??{},this.toolDiscoveryCommand=e.toolDiscoveryCommand,this.toolCallCommand=e.toolCallCommand,this.mcpServerCommand=e.mcpServerCommand,this.mcpServers=e.mcpServers,this.lspEnabled=e.lsp?.enabled??!1,this.lspClient=e.lspClient,this.allowedMcpServers=e.allowedMcpServers,this.excludedMcpServers=e.excludedMcpServers,this.pendingMcpServers=e.pendingMcpServers,this.sessionSubagents=e.sessionSubagents??[],this.sdkMode=e.sdkMode??!1,this.userMemory=e.userMemory??"",this.geminiMdFileCount=e.geminiMdFileCount??0,this.contextRuleExcludes=e.contextRuleExcludes??[],this.approvalMode=e.approvalMode??"default",this.accessibility=e.accessibility??{},this.telemetrySettings={enabled:e.telemetry?.enabled??!1,target:e.telemetry?.target??CP,otlpEndpoint:e.telemetry?.otlpEndpoint,otlpProtocol:e.telemetry?.otlpProtocol,otlpTracesEndpoint:e.telemetry?.otlpTracesEndpoint,otlpLogsEndpoint:e.telemetry?.otlpLogsEndpoint,otlpMetricsEndpoint:e.telemetry?.otlpMetricsEndpoint,logPrompts:e.telemetry?.logPrompts??!0,includeSensitiveSpanAttributes:e.telemetry?.includeSensitiveSpanAttributes??!1,outfile:e.telemetry?.outfile,resourceAttributes:e.telemetry?.resourceAttributes,metrics:e.telemetry?.metrics,resourceAttributeWarnings:e.telemetry?.resourceAttributeWarnings},this.outboundCorrelationSettings={propagateTraceContext:e.outboundCorrelation?.propagateTraceContext??!1},this.gitCoAuthor={...R5e(e.gitCoAuthor),name:"Matilda-Coder",email:"matilda@maincode.com"},this.usageStatisticsEnabled=e.usageStatisticsEnabled??!1,this.fileReadCacheDisabled=e.fileReadCacheDisabled??!1,this.outputLanguageFilePath=e.outputLanguageFilePath,this.fileFiltering={respectGitIgnore:e.fileFiltering?.respectGitIgnore??!0,respectMatildaIgnore:e.fileFiltering?.respectMatildaIgnore??!0,enableRecursiveFileSearch:e.fileFiltering?.enableRecursiveFileSearch??!0,enableFuzzySearch:e.fileFiltering?.enableFuzzySearch??!0},this.fileCheckpointingEnabled=e.fileCheckpointingEnabled??(!e.sdkMode&&(e.interactive??!1)),this.proxy=e.proxy,this.cwd=e.cwd??Qt.cwd(),this.fileDiscoveryService=e.fileDiscoveryService??null,this.bugCommand=e.bugCommand,this.maxSessionTurns=e.maxSessionTurns??-1,this.maxWallTimeSeconds=e.maxWallTimeSeconds??-1,this.maxToolCalls=e.maxToolCalls??-1;let n=e.clearContextOnIdle,s=n?.toolResultsThresholdMinutes??5;this.clearContextOnIdle={toolResultsThresholdMinutes:s,toolResultsNumToKeep:n?.toolResultsNumToKeep??5,toolResultsTotalCharsThreshold:n?.toolResultsTotalCharsThreshold??((n?.toolResultsThresholdMinutes??0)<0?-1:5e5)},this.sessionTokenLimit=e.sessionTokenLimit??-1,this.experimentalZedIntegration=e.experimentalZedIntegration??!1,this.cronEnabled=e.cronEnabled??!0,this.agentTeamEnabled=e.agentTeamEnabled??!1,this.workflowsEnabled=e.workflowsEnabled??!1,this.computerUseEnabled=e.computerUseEnabled??!0,this.computerUseMaxImageDimension=e.computerUseMaxImageDimension,this.emitToolUseSummaries=e.emitToolUseSummaries??!0,this.listExtensions=e.listExtensions??!1,this.overrideExtensions=e.overrideExtensions,this.noBrowser=e.noBrowser??!1,this.folderTrustFeature=e.folderTrustFeature??!1,this.folderTrust=e.folderTrust??!1,this.ideMode=e.ideMode??!1,this.modelProvidersConfig=e.modelProvidersConfig,this.cliVersion=e.cliVersion,this.chatRecordingEnabled=e.chatRecording??!0,this.loadMemoryFromIncludeDirectories=e.loadMemoryFromIncludeDirectories??!1,this.importFormat=e.importFormat??"tree",this.chatCompression=e.chatCompression,this.interactive=e.interactive??!1,this.trustedFolder=e.trustedFolder,this.skipLoopDetection=e.skipLoopDetection??!1,this.skipStartupContext=e.skipStartupContext??!1,this.bareMode=e.bareMode??!1,this.warnings=e.warnings??[],this.addLegacyPlanLocationWarning(),this.allowedHttpHookUrls=e.allowedHttpHookUrls??[],this.onPersistPermissionRuleCallback=e.onPersistPermissionRule,this.onRefreshPermissionsFromDiskCallback=e.onRefreshPermissionsFromDisk,this.useRipgrep=e.useRipgrep??!0,this.useBuiltinRipgrep=e.useBuiltinRipgrep??!0,this.shouldUseNodePtyShell=e.shouldUseNodePtyShell??n4(),this.preventSystemSleep=e.preventSystemSleep??!0,this.skipNextSpeakerCheck=e.skipNextSpeakerCheck??!0,this.shellExecutionConfig={terminalWidth:e.shellExecutionConfig?.terminalWidth??80,terminalHeight:e.shellExecutionConfig?.terminalHeight??24,showColor:e.shellExecutionConfig?.showColor??!1,pager:e.shellExecutionConfig?.pager??"cat",maxBufferedOutputBytes:e.shellExecutionConfig?.maxBufferedOutputBytes},this.truncateToolOutputThreshold=e.truncateToolOutputThreshold??P5e,this.truncateToolOutputLines=e.truncateToolOutputLines??M5e,this.toolOutputBatchBudget=e.toolOutputBatchBudget??I5e,this.channel=e.channel,this.jsonFd=e.jsonFd,this.jsonFile=e.jsonFile,this.jsonPartials=e.jsonPartials??!0,this.jsonSchema=e.jsonSchema,this.inputFile=e.inputFile,this.defaultFileEncoding=e.defaultFileEncoding,this.storage=new fe(this.targetDir),this.sessionStorage=new fe(this.sessionStorageDir,this.sessionRuntimeBaseDir),this.inputFormat=e.inputFormat??"text",this.fileExclusions=new t2(this),this.eventEmitter=e.eventEmitter,this.arenaAgentClient=Sv.create(),this.agentsSettings=e.agents??{},this.worktreeSettings=e.worktree??{},e.contextFileName&&Qj(e.contextFileName),this.modelsConfig=new av({initialAuthType:e.authType??e.generationConfig?.authType,modelProvidersConfig:this.modelProvidersConfig,generationConfig:{model:e.model,...e.generationConfig||{},baseUrl:e.generationConfig?.baseUrl},generationConfigSources:e.generationConfigSources,onModelChange:this.handleModelChange.bind(this)}),this.telemetrySettings.enabled&&C2(this);let o=this.getProxy();o&&(0,FR.setGlobalDispatcher)(new FR.ProxyAgent(o)),this.geminiClient=new IR(this),this.chatRecordingService=this.chatRecordingEnabled?new oh(this):void 0,this.extensionManager=new kA({workspaceDir:this.targetDir,enabledExtensionOverrides:this.overrideExtensions,isWorkspaceTrusted:this.isTrustedFolder()}),this.enableManagedAutoMemory=e.enableManagedAutoMemory??!0,this.enableManagedAutoDream=e.enableManagedAutoDream??!0,this.enableAutoSkill=e.enableAutoSkill??!0,this.fastModel=e.fastModel||void 0,this.modelDisplayName=e.modelDisplayName||void 0,this.disableAllHooks=e.disableAllHooks??!1,this.stopHookBlockingCap=c0(e.stopHookBlockingCap),this.userHooks=e.userHooks,this.projectHooks=e.projectHooks,this.hooks=e.hooks,this.memoryManager=new Fb}async initialize(e){if(this.initialized)throw Error("Config was already initialized");this.initialized=!0,this.debugLogger.info("Config initialization started"),this.getFileService(),this.promptRegistry=new LR,this.extensionManager.setConfig(this);let t=this.getExplicitExtensionNames();this.getBareMode()?t.length>0&&await this.extensionManager.refreshCache({names:t}):await this.extensionManager.refreshCache(),this.debugLogger.debug("Extension manager initialized"),this.getDisableAllHooks()?this.debugLogger.debug("Hook system disabled, skipping initialization"):(this.hookSystem=new Bp(this),await this.hookSystem.initialize(),this.debugLogger.debug("Hook system initialized"),this.messageBus=new vb,this.messageBus.subscribe("hook-execution-request",async o=>{try{let a=this.hookSystem;if(!a){this.messageBus?.publish({type:"hook-execution-response",correlationId:o.correlationId,success:!1,error:new Error("Hook system not initialized")});return}if(o.signal?.aborted){this.messageBus?.publish({type:"hook-execution-response",correlationId:o.correlationId,success:!1,error:new Error("Hook execution cancelled (aborted)")});return}let l,c,u=o.input||{},d=o.signal;switch(o.eventName){case"UserPromptSubmit":l=await a.fireUserPromptSubmitEvent(u.prompt||"",d);break;case"UserPromptExpansion":l=await a.fireUserPromptExpansionEvent(u.command_name||"",u.command_args||"",u.prompt||"",d);break;case"Stop":{let h=await a.fireStopEvent(u.stop_hook_active||!1,u.last_assistant_message||"",d);l=h.finalOutput?ct("Stop",h.finalOutput):void 0,c=h.allOutputs.length;break}case"PreToolUse":{l=await a.firePreToolUseEvent(u.tool_name||"",u.tool_input||{},u.tool_use_id||"",u.permission_mode??"default",d);break}case"PostToolUse":l=await a.firePostToolUseEvent(u.tool_name||"",u.tool_input||{},u.tool_response||{},u.tool_use_id||"",u.permission_mode||"default",d);break;case"PostToolUseFailure":l=await a.firePostToolUseFailureEvent(u.tool_use_id||"",u.tool_name||"",u.tool_input||{},u.error||"",u.is_interrupt,u.permission_mode||"default",d);break;case"PostToolBatch":l=await a.firePostToolBatchEvent(u.tool_calls||[],u.permission_mode||"default",d);break;case"Notification":l=await a.fireNotificationEvent(u.message||"",u.notification_type||"permission_prompt",u.title||void 0,d);break;case"PermissionRequest":l=await a.firePermissionRequestEvent(u.tool_name||"",u.tool_input||{},u.permission_mode||"default",u.permission_suggestions||void 0,d);break;case"PermissionDenied":l=await a.firePermissionDeniedEvent(u.tool_name||"",u.tool_input||{},u.tool_use_id||"",u.reason||"classifier_blocked",d);break;case"SubagentStart":l=await a.fireSubagentStartEvent(u.agent_id||"",u.agent_type||"",u.permission_mode||"default",d);break;case"SubagentStop":l=await a.fireSubagentStopEvent(u.agent_id||"",u.agent_type||"",u.agent_transcript_path||"",u.last_assistant_message||"",u.stop_hook_active||!1,u.permission_mode||"default",d);break;default:this.debugLogger.warn(`Unknown hook event: ${o.eventName}`),l=void 0}this.messageBus?.publish({type:"hook-execution-response",correlationId:o.correlationId,success:!0,output:l,stopHookCount:c})}catch(a){this.debugLogger.warn(`Hook execution failed: ${a}`),this.messageBus?.publish({type:"hook-execution-response",correlationId:o.correlationId,success:!1,error:a instanceof Error?a:new Error(String(a))})}}),this.debugLogger.debug("MessageBus initialized with hook subscription")),this.subagentManager=new q_(this),this.skillManager=new Y_(this),this.getBareMode()?await this.skillManager.refreshCache():await this.skillManager.startWatching(),this.debugLogger.debug("Skill manager initialized"),this.memoryPressureConfig=D5e(),this.memoryPressureMonitor=new jb(this,this.memoryPressureConfig),this.permissionManager=new Qm(this),this.permissionManager.initialize(),this.debugLogger.debug("Permission manager initialized"),this.sessionSubagents.length>0&&this.subagentManager.loadSessionSubagents(this.sessionSubagents),this.getBareMode()||await this.extensionManager.refreshCache(),await this.refreshHierarchicalMemory("session_start"),this.debugLogger.debug("Hierarchical memory loaded");let n=Qt.env.MATILDA_CODE_LEGACY_MCP_BLOCKING==="1",s=this.getBareMode()||!n||e?.skipMcpDiscovery===!0;this.toolRegistry=await this.createToolRegistry(e?.sendSdkMcpMessage,s?{skipDiscovery:!0}:void 0),Xn("tool_registry_created",{toolCount:this.toolRegistry.getAllToolNames().length,mcpInline:!s}),this.debugLogger.info(`Tool registry initialized with ${this.toolRegistry.getAllToolNames().length} tools`),e?.skipGeminiInitialization?this.debugLogger.info("Gemini client initialization skipped"):(await this.geminiClient.initialize(),this.debugLogger.info("Gemini client initialized")),this.modelsConfig.detectAndCaptureRuntimeModel(),await this.toolRegistry.warmAll({strict:!0}),s&&!this.getBareMode()&&!e?.skipMcpDiscovery&&this.startMcpDiscoveryInBackground(),new hz().getInstallationId(),tP(this,new hP(this)),this.debugLogger.info("Config initialization completed"),this.getBareMode()||(async()=>{try{let a=await new us(this.targetDir).getRepoTopLevel()??this.targetDir,l=Vr.join(a,".matilda","worktrees");try{await Wde.access(l)}catch{this.debugLogger.debug(`Stale worktree sweep skipped: ${l} does not exist`);return}let c=await Nde(a);c>0?this.debugLogger.info(`Stale worktree sweep removed ${c} ephemeral worktree(s) under ${a}`):this.debugLogger.debug(`Stale worktree sweep ran under ${a}: nothing to remove`)}catch(o){this.debugLogger.warn(`Stale worktree sweep failed (non-fatal): ${o}`)}})()}mcpDiscoveryPromise;startMcpDiscoveryInBackground(){let e=this.toolRegistry.getMcpClientManager?.();if(!e){this.debugLogger.debug("Skipping background MCP discovery: ToolRegistry has no MCP client manager");return}this.mcpDiscoveryPromise=e.discoverAllMcpToolsIncremental(this).then(async()=>{try{await this.geminiClient?.setTools()}catch(t){this.debugLogger.error(`setTools() after background MCP discovery failed: ${t instanceof Error?t.message:String(t)}`)}}).catch(t=>{this.debugLogger.error(`Background MCP discovery failed: ${t instanceof Error?t.message:String(t)}`)})}async waitForMcpReady(){this.mcpDiscoveryPromise&&await this.mcpDiscoveryPromise}getFailedMcpServerNames(){let e=this.getMcpServers();if(!e)return[];let t=[];for(let n of Object.keys(e))this.isMcpServerDisabled(n)||this.isMcpServerPendingApproval(n)||fT(n)!=="connected"&&t.push(n);return t}async refreshHierarchicalMemory(e="refresh"){let{memoryContent:t,fileCount:n,conditionalRules:s,projectRoot:o}=await yue(this.getWorkingDir(),this.getMemoryDiscoveryDirectories(),this.getFileService(),this.getExtensionContextFilePaths(),this.isTrustedFolder(),this.getImportFormat(),this.contextRuleExcludes,{explicitOnly:this.getBareMode(),loadReason:e,onInstructionsLoaded:bR(()=>this.hookSystem)});if(this.getManagedAutoMemoryEnabled()){let[a,l]=await Promise.all([S3(this.getProjectRoot()),T3().catch(()=>null)]);this.setUserMemory(this.memoryManager.appendToUserMemory(t,Dr(this.getProjectRoot()),a,{memoryDir:ti(),indexContent:l}))}else this.setUserMemory(t);this.setGeminiMdFileCount(n),this.conditionalRulesRegistry=new _b(s,o)}buildMemoryContextWarning(e){let t=this.getContentGeneratorConfig()?.contextWindowSize??this.modelsConfig.getGenerationConfig().contextWindowSize??rm(this.getModel(),"input");if(!t||t<=0||!e)return;let n=Math.ceil(e.length/es),s=Math.floor(t*jde);if(!(n<=s))return`Warning: Loaded MATILDA.md/context instructions use about ${n.toLocaleString()} tokens, more than ${Math.round(jde*100)}% of this model's ${t.toLocaleString()} token context window. Consider trimming long always-loaded context or moving details into on-demand files.`}getMemoryDiscoveryDirectories(){return this.shouldLoadMemoryFromIncludeDirectories()?this.getBareMode()?this.explicitIncludeDirectories:[...this.getWorkspaceContext().getDirectories()]:[]}getConditionalRulesRegistry(){return this.conditionalRulesRegistry}setConditionalRulesRegistry(e){this.conditionalRulesRegistry=e}getContextRuleExcludes(){return this.contextRuleExcludes}getContentGenerator(){return Bm()?.contentGenerator??this.contentGenerator}getModelsConfig(){return this.modelsConfig}updateCredentials(e,t){this.modelsConfig.updateCredentials(e,t)}reloadModelProvidersConfig(e){this.modelsConfig.reloadModelProvidersConfig(e)}async refreshAuth(e,t){let n=this.modelsConfig.getModel();this.modelsConfig.syncAfterAuthRefresh(e,n);let s=this.modelsConfig.consumeRequireCachedCredentialsFlag(),{config:o,sources:a}=RP(this,e,this.modelsConfig.getGenerationConfig(),this.modelsConfig.getGenerationConfigSources(),{strictModelProvider:this.modelsConfig.isStrictModelProviderSelection()}),l=o;this.contentGenerator=await Hd(l,this,s?!0:t),this.contentGeneratorConfig=l,this.contentGeneratorConfigSources=a,this.baseLlmClient=new fm(this.contentGenerator,this);let c=this.getMessageBus();!this.getDisableAllHooks()&&c&&zm(c,`Successfully authenticated with ${e}`,"auth_success","Authentication successful").catch(()=>{})}getBaseLlmClient(){if(!this.baseLlmClient)if(this.contentGenerator)this.baseLlmClient=new fm(this.getContentGenerator(),this);else throw new Error("BaseLlmClient not initialized. Ensure authentication has occurred and ContentGenerator is ready.");return this.baseLlmClient}getSessionId(){return this.sessionId}getWarnings(){let e=this.buildMemoryContextWarning(this.getUserMemory());return e?[...this.warnings,e]:this.warnings}getDebugLogger(){return this.debugLogger}async startNewSession(e,t){return this.sessionTransitionMutex.runExclusive(async()=>{let n=this.chatRecordingService;try{n?.finalize()}catch{}await n?.releaseTranscriptOwnership();let s=this.sessionId;if(this.sessionId=e??Bde(),Qt.env&&(Qt.env.MATILDA_CODE_SESSION_ID=this.sessionId),this.sessionData=t,YR(this),this.debugLogger=F(),this.chatRecordingService=this.chatRecordingEnabled?new oh(this):void 0,this.getFileReadCache().clear(),this.toolResultBudget.bytesWritten=0,this.getMemoryPressureMonitor()?.resetForNewSession(),this.fileHistoryService=void 0,T2(this.sessionId),v2(),oi.resetInstance(),this.initialized&&tP(this,new hP(this)),this.runtimeStatusEnabled&&s!==this.sessionId){let o=this.sessionStorage.getRuntimeStatusPath(s),a=this.sessionStorage.getRuntimeStatusPath(this.sessionId),l=this.cliVersion??null,c=this.targetDir,u=this.sessionId;this.queueRuntimeStatusWrite(async()=>{await dW(o),await x0(a,{sessionId:u,workDir:c,matildaVersion:l})})}return this.sessionId})}markRuntimeStatusEnabled(){this.runtimeStatusEnabled=!0}queueRuntimeStatusWrite(e){this.runtimeStatusWrite=this.runtimeStatusWrite.catch(()=>{}).then(e).catch(()=>{})}async flushRuntimeStatusWrites(){await this.runtimeStatusWrite.catch(()=>{})}async refreshCurrentRuntimeStatus(e){this.runtimeStatusEnabled&&(this.queueRuntimeStatusWrite(async()=>{await x0(this.sessionStorage.getRuntimeStatusPath(this.sessionId),{sessionId:this.sessionId,workDir:e,matildaVersion:this.cliVersion??null})}),await this.flushRuntimeStatusWrites())}getResumedSessionData(){return this.sessionData}shouldLoadMemoryFromIncludeDirectories(){return this.loadMemoryFromIncludeDirectories}getImportFormat(){return this.importFormat}getContentGeneratorConfig(){return Bm()?.contentGeneratorConfig??this.contentGeneratorConfig}getContentGeneratorConfigSources(){return Object.keys(this.contentGeneratorConfigSources).length===0&&this.modelsConfig?this.modelsConfig.getGenerationConfigSources():this.contentGeneratorConfigSources}getModel(){return this.getContentGeneratorConfig()?.model||this.modelsConfig.getModel()}getModelDisplayName(){return this.modelDisplayName||this.modelsConfig.getModelDisplayName(this.getModel())}getPublicModelId(e){return this.modelsConfig.getPublicModelId(e)}isManagedMatildaModel(e){return this.modelsConfig.isManagedMatildaModel(e)}onModelChange(e){return this.modelChangeListeners.add(e),()=>{this.modelChangeListeners.delete(e)}}notifyModelChangeListeners(){let e=this.getModel();for(let t of this.modelChangeListeners)t(e)}getFastModel(){let e=this.resolveFastModelSelector();if(!e||!(e.authType?this.getAllConfiguredModels([e.authType]):this.getAllConfiguredModels()).some(s=>s.id===e.modelId))return;let n=ni(this.fastModel);return n?.authType?`${n.authType}:${e.modelId}`:e.modelId}resolveFastModelSelector(){if(this.fastModel)try{return ni(this.fastModel,{currentAuthType:this.getContentGeneratorConfig()?.authType,getAvailableModels:e=>this.getAllConfiguredModels(e)})}catch{return}}setFastModel(e){this.fastModel=e||void 0}async setModel(e,t){await this.modelsConfig.setModel(e,t),this.contentGeneratorConfig&&(this.contentGeneratorConfig.model=e),this.notifyModelChangeListeners()}async handleModelChange(e,t){if(this.contentGeneratorConfig){if(e==="matilda-oauth"&&!t){let{config:n,sources:s}=RP(this,e,this.modelsConfig.getGenerationConfig(),this.modelsConfig.getGenerationConfigSources(),{strictModelProvider:this.modelsConfig.isStrictModelProviderSelection()});this.contentGeneratorConfig.model=n.model,this.contentGeneratorConfig.samplingParams=n.samplingParams,this.contentGeneratorConfig.contextWindowSize=n.contextWindowSize,this.contentGeneratorConfig.enableCacheControl=n.enableCacheControl,this.contentGeneratorConfig.splitToolMedia=n.splitToolMedia,"model"in s&&(this.contentGeneratorConfigSources.model=s.model),"samplingParams"in s&&(this.contentGeneratorConfigSources.samplingParams=s.samplingParams),"enableCacheControl"in s&&(this.contentGeneratorConfigSources.enableCacheControl=s.enableCacheControl),"contextWindowSize"in s&&(this.contentGeneratorConfigSources.contextWindowSize=s.contextWindowSize),"splitToolMedia"in s&&(this.contentGeneratorConfigSources.splitToolMedia=s.splitToolMedia);return}await this.refreshAuth(e)}}getAvailableModels(){return this.modelsConfig.getAvailableModels()}getAvailableModelsForAuthType(e){return this.modelsConfig.getAvailableModelsForAuthType(e)}getAllConfiguredModels(e){return this.modelsConfig.getAllConfiguredModels(e)}getActiveRuntimeModelSnapshot(){return this.modelsConfig.getActiveRuntimeModelSnapshot()}async switchModel(e,t,n){await this.modelsConfig.switchModel(e,t,n),this.notifyModelChangeListeners()}getMaxSessionTurns(){return this.maxSessionTurns}getMaxWallTimeSeconds(){return this.maxWallTimeSeconds}getMaxToolCalls(){return this.maxToolCalls}getClearContextOnIdle(){return this.clearContextOnIdle}getSessionTokenLimit(){return this.sessionTokenLimit}getEmbeddingModel(){return this.embeddingModel}getSandbox(){return this.sandbox}isRestrictiveSandbox(){let e=this.getSandbox(),t=Qt.env.SEATBELT_PROFILE,n=Qt.env.SANDBOX,s=Qt.env.MATILDA_DESKTOP_SANDBOX_NONCE,o=Qt.env.MATILDA_DESKTOP_SANDBOX_ACTIVE;return(e?.command==="sandbox-exec"||n==="sandbox-exec")&&!!t&&t.startsWith("restrictive-")&&(!s||o===s)}getTargetDir(){return this.targetDir}getCurrentSessionArtifactMoves(e,t){let n=Vr.join(e.getProjectDir(),"chats"),s=Vr.join(t.getProjectDir(),"chats");return[`${this.sessionId}.jsonl`,`${this.sessionId}.runtime.json`,`${this.sessionId}.worktree.json`].map(o=>({from:Vr.join(n,o),to:Vr.join(s,o)}))}moveFile(e,t){try{bt.renameSync(e,t)}catch(n){if(n.code!=="EXDEV")throw n;let s=!1;try{bt.copyFileSync(e,t),s=!0,bt.unlinkSync(e)}catch(o){if(s)try{bt.unlinkSync(t)}catch{}throw o}}}moveCurrentSessionArtifacts(e,t){let n=[];for(let{from:s,to:o}of this.getCurrentSessionArtifactMoves(e,t))if(bt.existsSync(s)){bt.mkdirSync(Vr.dirname(o),{recursive:!0});try{this.moveFile(s,o),n.push({from:s,to:o})}catch(a){for(let l of n.reverse())try{bt.mkdirSync(Vr.dirname(l.from),{recursive:!0}),this.moveFile(l.to,l.from)}catch(c){this.debugLogger.warn("Failed to roll back moved session artifact",c)}throw a}}}async prepareSessionArtifactMigration(e,t,n){this.chatRecordingService?.finalize(),await this.chatRecordingService?.releaseTranscriptOwnership(),await this.flushRuntimeStatusWrites();try{this.moveCurrentSessionArtifacts(e,t)}catch(s){try{Qt.chdir(n)}catch(o){this.debugLogger.warn("Failed to roll back working directory after session artifact migration failed",o)}throw s}}async relocateWorkingDirectory(e,t){let n=bt.realpathSync(Qt.cwd()),s=Vr.resolve(e),o=t??bt.realpathSync(s);if(!bt.statSync(s).isDirectory())throw new Error(`Path is not a directory: ${s}`);let a=Da.resolveRootDirectories(o,this.explicitIncludeDirectories);Qt.chdir(s);let l=bt.realpathSync(Qt.cwd());if(l!==o)throw Qt.chdir(n),new Error(`Changed directory to ${l}, expected ${o}.`);let c=this.sessionStorage,u=new fe(o);this.sessionStoragePinned||await this.prepareSessionArtifactMigration(c,u,n),this.targetDir=o,this.cwd=o,this.storage=u,this.sessionStoragePinned||(this.sessionStorage=u,this.sessionStorageDir=o,this.chatRecordingService?.resetStoragePaths(),this.sessionService=void 0),await this.refreshCurrentRuntimeStatus(o),this.workspaceContext.applyRootDirectories(a),this.fileDiscoveryService=null,this.fileHistoryService=void 0,this.getFileReadCache().clear();try{return await this.refreshHierarchicalMemory(),{}}catch(d){return{memoryRefreshError:d}}}setPendingStartupWorktreeNotice(e){this.pendingStartupWorktreeNotice=e}consumePendingStartupWorktreeNotice(){let e=this.pendingStartupWorktreeNotice;return this.pendingStartupWorktreeNotice=null,e}getProjectRoot(){return this.targetDir}getCwd(){return this.targetDir}getWorkspaceContext(){return this.workspaceContext}getToolRegistry(){return this.toolRegistry}async shutdown(){try{if(!this.initialized)return;try{this.chatRecordingService?.finalize(),await this.chatRecordingService?.releaseTranscriptOwnership()}catch{}this.skillManager?.stopWatching(),this.toolRegistry&&await this.toolRegistry.stop(),this.backgroundTaskRegistry.abortAll(),this.monitorRegistry.abortAll({notify:!1}),this.backgroundShellRegistry.abortAll(),await this.cleanupArenaRuntime(),await this.cleanupTeamRuntime()}catch(e){this.debugLogger.error("Error during Config shutdown:",e)}finally{S2()&&await E2()}}getPromptRegistry(){return this.promptRegistry}getDebugMode(){return this.debugMode}getQuestion(){return this.question}getSystemPrompt(){return this.systemPrompt}getAppendSystemPrompt(){return this.appendSystemPrompt}getCoreTools(){return this.getBareMode()?L5e:this.coreTools}getPermissionsAllow(){let e=this.permissionsAllow??[],t=[...this.allowedTools??[]];if(t.length===0)return e.length>0?e:[];let n=[...e];for(let s of t)s&&!n.includes(s)&&n.push(s);return n}getPermissionsAsk(){return this.permissionsAsk}getPermissionsDeny(){let e=this.permissionsDeny??[],t=this.excludeTools??[];if(t.length===0)return e.length>0?e:[];let n=[...e];for(let s of t)s&&!n.includes(s)&&n.push(s);return n}getToolDiscoveryCommand(){return this.toolDiscoveryCommand}getDisabledSlashCommands(){return this.disabledSlashCommands}getDisabledSkillNames(){return this.disabledSkillNamesProvider?.()??N5e}getDisabledTools(){return this.disabledTools}setDisabledTools(e){this.disabledTools=new Set(e)}getToolCallCommand(){return this.toolCallCommand}getMcpServerCommand(){return this.mcpServerCommand}mcpTransportPool;setMcpTransportPool(e){this.mcpTransportPool=e}getMcpTransportPool(){return this.mcpTransportPool}getSettingsMcpServers(){return this.mcpServers}getMcpServers(){let e={...this.mcpServers||{}},t=this.getActiveExtensions();for(let n of t)Object.entries(n.config.mcpServers||{}).forEach(([s,o])=>{e[s]||(e[s]={...o,extensionName:n.config.name})});for(let[n,s]of this.runtimeMcpServers)e[n]=s;return this.allowedMcpServers&&(e=Object.fromEntries(Object.entries(e).filter(([n])=>this.allowedMcpServers?.includes(n)))),e}getExcludedMcpServers(){return this.excludedMcpServers}setExcludedMcpServers(e){this.excludedMcpServers=e}isMcpServerDisabled(e){return this.excludedMcpServers?.includes(e)??!1}isMcpServerPendingApproval(e){return this.pendingMcpServers?.includes(e)??!1}approveMcpServerForSession(e){this.pendingMcpServers&&(this.pendingMcpServers=this.pendingMcpServers.filter(t=>t!==e))}addMcpServers(e){if(this.initialized)throw new Error("Cannot modify mcpServers after initialization");this.mcpServers={...this.mcpServers,...e}}addRuntimeMcpServer(e,t){this.runtimeMcpServers.set(e,t)}removeRuntimeMcpServer(e){return this.runtimeMcpServers.delete(e)}isLspEnabled(){return this.lspEnabled&&!this.getBareMode()}getLspClient(){return this.lspClient}getLspStatusSnapshot(){if(!this.isLspEnabled())return this.createLspStatusSnapshot(!1);let e=this.lspClient?.getStatusSnapshot?.();return e?{...e,enabled:!0,initializationError:this.lspInitializationError??e.initializationError}:this.lspClient?{...this.createLspStatusSnapshot(!0),statusUnavailable:!0}:this.createLspStatusSnapshot(!0,this.lspInitializationError??"LSP client is not initialized")}createLspStatusSnapshot(e,t){return{enabled:e,configuredServers:0,readyServers:0,failedServers:0,inProgressServers:0,notStartedServers:0,servers:[],...t?{initializationError:t}:{}}}setLspClient(e){if(this.initialized)throw new Error("Cannot set LSP client after initialization");this.lspClient=e}setLspInitializationError(e){if(this.initialized)throw new Error("Cannot set LSP status after initialization");this.lspInitializationError=e instanceof Error?e.message:e}getSessionSubagents(){return this.sessionSubagents}setSessionSubagents(e){if(this.initialized)throw new Error("Cannot modify sessionSubagents after initialization");this.sessionSubagents=e}getSdkMode(){return this.sdkMode}setSdkMode(e){this.sdkMode=e}getUserMemory(){return this.userMemory}getOutputLanguageFilePath(){return this.outputLanguageFilePath}setOutputLanguageFilePath(e){this.outputLanguageFilePath=e}setUserMemory(e){this.userMemory=e}getGeminiMdFileCount(){return this.geminiMdFileCount}setGeminiMdFileCount(e){this.geminiMdFileCount=e}getArenaManager(){return this.arenaManager}setArenaManager(e){this.arenaManager=e,this.arenaManagerChangeCallback?.(e)}onArenaManagerChange(e){this.arenaManagerChangeCallback=e}getArenaAgentClient(){return this.arenaAgentClient}getAgentsSettings(){return this.agentsSettings}getTeamManager(){return this.teamManager}setTeamManager(e){this.teamManager=e;for(let t of this.teamManagerChangeCallbacks)t(e)}onTeamManagerChange(e,t){t&&this.teamManagerChangeCallbacks.delete(t),e&&this.teamManagerChangeCallbacks.add(e)}getTeamContext(){return this.teamContext}setTeamContext(e){this.teamContext=e}async cleanupTeamRuntime(){let e=this.teamManager;e&&(await e.cleanup(),this.setTeamManager(null),this.setTeamContext(null))}getWorktreeSymlinkDirectories(){return this.worktreeSettings.symlinkDirectories??[]}async cleanupArenaRuntime(e){let t=this.arenaManager;t&&(!e&&this.agentsSettings.arena?.preserveArtifacts?await t.cleanupRuntime():await t.cleanup(),this.setArenaManager(null))}getApprovalMode(){return this.approvalMode}getAutoModeSettings(){return this.permissionsAutoMode}getAutoModeDenialState(){return this.autoModeDenialState}setAutoModeDenialState(e){this.autoModeDenialState=e}getPrePlanMode(){return this.prePlanMode??"default"}getPlanGateState(){return this.planGateState}setApprovalMode(e){if(!this.isTrustedFolder()&&e!=="default"&&e!=="plan")throw new _j("Cannot enable privileged approval modes in an untrusted folder.");e==="plan"&&this.approvalMode!=="plan"?(this.prePlanMode=this.approvalMode,this.planGateState=bq(++this.planGateEntryCounter)):e!=="plan"&&this.approvalMode==="plan"&&(this.prePlanMode=void 0,this.planGateState=void 0);let t=e==="auto"?"default":e,n=this.approvalMode;this.permissionManager&&n==="auto"&&this.permissionManager.restoreDangerousRules(),n!==t&&(this.autoModeDenialState=lI()),this.approvalMode=t}getPlansDir(){return this.plansDir}assertPlansDirWithinTargetDir(){this.plansDirectoryConfigured&&fe.assertPathWithinDirectory(this.plansDir,this.targetDir,"plansDirectory must resolve within the project root.")}assertPlanFilePathWithinTargetDir(e){this.plansDirectoryConfigured&&fe.assertPathWithinDirectory(e,this.targetDir,"plansDirectory must resolve within the project root.")}addLegacyPlanLocationWarning(){try{if(!this.plansDirectoryConfigured)return;let e=fe.getPlansDir(),t=this.getPlanFileNames(e);if(t.length===0)return;let n=new Set(this.getPlanFileNames(this.plansDir));if(t.filter(o=>!n.has(o)).length===0)return;this.warnings.push(`Warning: Saved plan files exist at ${e}, but plansDirectory is configured to use ${this.plansDir}. Move existing plan files to ${this.plansDir} if you want to keep using them.`)}catch(e){let t=`Failed to check legacy plan directory migration warning: ${e instanceof Error?e.message:String(e)}`;this.warnings.push(t),this.debugLogger.warn(t,e)}}getPlanFileNames(e){try{return bt.readdirSync(e).filter(t=>t.endsWith(".md"))}catch(t){let n=t.code;if(n==="ENOENT")return[];if(n==="EACCES"||n==="EPERM"){let s=`Failed to read plan directory ${e}: ${t instanceof Error?t.message:String(t)}`;return this.warnings.push(s),this.debugLogger.warn(s,t),[]}throw t}}getPlanFilePath(){return Vr.join(this.plansDir,`${fe.sanitizePlanSessionId(this.sessionId)}.md`)}savePlan(e){this.assertPlansDirWithinTargetDir();let t=this.getPlanFilePath(),n=Vr.dirname(t);bt.mkdirSync(n,{recursive:!0});let s=t+".tmp";bt.writeFileSync(s,e,"utf-8");try{bt.renameSync(s,t)}catch(o){if(o.code!=="EXDEV")throw o;bt.copyFileSync(s,t),bt.unlinkSync(s)}try{this.assertPlanFilePathWithinTargetDir(t)}catch(o){try{bt.unlinkSync(t)}catch{}throw o}}loadPlan(){this.assertPlansDirWithinTargetDir();let e=this.getPlanFilePath();this.assertPlanFilePathWithinTargetDir(e);try{return bt.readFileSync(e,"utf-8")}catch(t){if(typeof t=="object"&&t!==null&&"code"in t&&t.code==="ENOENT")return;throw t}}getInputFormat(){return this.inputFormat}getIncludePartialMessages(){return this.includePartialMessages}getAccessibility(){return this.accessibility}getTelemetryEnabled(){return this.telemetrySettings.enabled??!1}getTelemetryLogPromptsEnabled(){return this.telemetrySettings.logPrompts??!0}getTelemetryIncludeSensitiveSpanAttributes(){return this.telemetrySettings.includeSensitiveSpanAttributes??!1}getTelemetryOtlpEndpoint(){return this.telemetrySettings.otlpEndpoint??sz}getTelemetryOtlpProtocol(){return this.telemetrySettings.otlpProtocol??"grpc"}getTelemetryOtlpTracesEndpoint(){return this.telemetrySettings.otlpTracesEndpoint}getTelemetryOtlpLogsEndpoint(){return this.telemetrySettings.otlpLogsEndpoint}getTelemetryOtlpMetricsEndpoint(){return this.telemetrySettings.otlpMetricsEndpoint}getTelemetryTarget(){return this.telemetrySettings.target??CP}getTelemetryResourceAttributes(){return this.telemetrySettings.resourceAttributes??{}}getTelemetryMetricsIncludeSessionId(){return this.telemetrySettings.metrics?.includeSessionId??!1}getTelemetryResourceAttributeWarnings(){return this.telemetrySettings.resourceAttributeWarnings??[]}getOutboundCorrelationPropagateTraceContext(){return this.outboundCorrelationSettings.propagateTraceContext??!1}getTelemetryOutfile(){return this.telemetrySettings.outfile}getGitCoAuthor(){return this.gitCoAuthor}getGeminiClient(){return this.geminiClient}getMemoryPressureMonitor(){if(!Object.prototype.hasOwnProperty.call(this,"memoryPressureMonitor")&&this.memoryPressureMonitor){let t=this.memoryPressureConfig;if(!t)throw new Error("Inherited memory pressure monitor is missing config");this.memoryPressureConfig={...t},this.memoryPressureMonitor=new jb(this,this.memoryPressureConfig)}return this.memoryPressureMonitor}getCronScheduler(){return this.cronScheduler||(this.cronScheduler=new CT(this.getProjectRoot())),this.cronScheduler}isCronEnabled(){return Qt.env.MATILDA_CODE_DISABLE_CRON==="1"?!1:this.cronEnabled}isAgentTeamEnabled(){return Qt.env.MATILDA_CODE_ENABLE_AGENT_TEAM==="1"?!0:this.agentTeamEnabled}isWorkflowsEnabled(){return Qt.env.MATILDA_CODE_DISABLE_WORKFLOWS==="1"?!1:Qt.env.MATILDA_CODE_ENABLE_WORKFLOWS==="1"?!0:this.workflowsEnabled}setWorkflowsEnabled(e){this.workflowsEnabled=e}isComputerUseEnabled(){return this.computerUseEnabled}getComputerUseMaxImageDimension(){return this.computerUseMaxImageDimension}getEmitToolUseSummaries(){let e=Qt.env.MATILDA_CODE_EMIT_TOOL_USE_SUMMARIES;return e==="0"||e==="false"?!1:e==="1"||e==="true"?!0:this.emitToolUseSummaries}getEnableRecursiveFileSearch(){return this.fileFiltering.enableRecursiveFileSearch}getFileFilteringEnableFuzzySearch(){return this.fileFiltering.enableFuzzySearch}getFileFilteringRespectGitIgnore(){return this.fileFiltering.respectGitIgnore}getFileFilteringRespectMatildaIgnore(){return this.fileFiltering.respectMatildaIgnore}getFileFilteringOptions(){return{respectGitIgnore:this.fileFiltering.respectGitIgnore,respectMatildaIgnore:this.fileFiltering.respectMatildaIgnore}}getCustomExcludes(){return[]}getFileCheckpointingEnabled(){return this.fileCheckpointingEnabled}enableFileCheckpointing(){this.fileCheckpointingEnabled=!0,this.fileHistoryService=void 0}getFileHistoryService(){if(!this.fileHistoryService){let e=new Ov(this.sessionId,this.fileCheckpointingEnabled,this.cwd,n=>{this.fileHistoryService===e&&this.getChatRecordingService()?.recordFileHistorySnapshot(n)});this.fileHistoryService=e;let t=this.sessionData?.fileHistorySnapshots;t?.length&&e.isEnabled()&&(e.restoreFromSnapshots(t),e.validateRestoredSnapshots().catch(n=>{this.debugLogger.error(`FileHistory: validateRestoredSnapshots failed: ${n}`)}))}return this.fileHistoryService}getProxy(){return _ue(this.proxy)}getWorkingDir(){return this.cwd}getBugCommand(){return this.bugCommand}getFileService(){return this.fileDiscoveryService||(this.fileDiscoveryService=new xl(this.targetDir)),this.fileDiscoveryService}getUsageStatisticsEnabled(){return this.usageStatisticsEnabled}getExtensionContextFilePaths(){return[...this.getActiveExtensions().flatMap(t=>t.contextFiles),...this.outputLanguageFilePath?[this.outputLanguageFilePath]:[]]}getExperimentalZedIntegration(){return this.experimentalZedIntegration}getListExtensions(){return this.listExtensions}getExtensionManager(){return this.extensionManager}getHookSystem(){return this.hookSystem}hasHooksForEvent(e,t){return this.hookSystem?.hasHooksForEvent(e,t??this.getSessionId())??!1}getDisableAllHooks(){return this.disableAllHooks||this.getBareMode()}getStopHookBlockingCap(){return this.stopHookBlockingCap}getManagedAutoMemoryEnabled(){return this.enableManagedAutoMemory&&!this.getBareMode()}getManagedAutoDreamEnabled(){return this.enableManagedAutoDream&&!this.getBareMode()}getAutoSkillEnabled(){return this.enableAutoSkill&&!this.getBareMode()}getPreventSystemSleepEnabled(){return this.preventSystemSleep}getMemoryManager(){return this.memoryManager}getMessageBus(){return this.messageBus}setMessageBus(e){this.messageBus=e}getProjectHooks(){return this.getBareMode()||!this.isTrustedFolder()?void 0:this.projectHooks??this.hooks}getUserHooks(){return this.getBareMode()?void 0:this.userHooks??this.hooks}getExtensions(){let e=this.extensionManager.getLoadedExtensions();if(this.overrideExtensions){let t=new Set(this.overrideExtensions.map(n=>n.toLowerCase()));return e.filter(n=>t.has(n.name.toLowerCase()))}else return e}getExplicitExtensionNames(){return(this.overrideExtensions??[]).filter(e=>e.trim()!==""&&e.toLowerCase()!=="none")}getActiveExtensions(){return this.getExtensions().filter(e=>e.isActive)}getBlockedMcpServers(){let e={...this.mcpServers||{}},t=this.getActiveExtensions();for(let s of t)Object.entries(s.config.mcpServers||{}).forEach(([o,a])=>{e[o]||(e[o]={...a,extensionName:s.config.name})});let n=[];return this.allowedMcpServers&&Object.entries(e).forEach(([s,o])=>{this.allowedMcpServers?.includes(s)||n.push({name:s,extensionName:o.extensionName||""})}),n}getNoBrowser(){return this.noBrowser}isBrowserLaunchSuppressed(){return this.getNoBrowser()||!lz()}getIdeMode(){return this.ideMode}getFolderTrustFeature(){return this.folderTrustFeature}getFolderTrust(){return this.folderTrust}getAllowedHttpHookUrls(){return this.getBareMode()?[]:this.allowedHttpHookUrls}isTrustedFolder(){let e=Uu.get();return e?.workspaceState?.isTrusted!==void 0?e.workspaceState.isTrusted:this.trustedFolder??!0}setIdeMode(e){this.ideMode=e}getAuthType(){return this.getContentGeneratorConfig()?.authType}getCliVersion(){return this.cliVersion}getChannel(){return this.channel}getJsonFd(){return this.jsonFd}getJsonFile(){return this.jsonFile}getJsonPartials(){return this.jsonPartials}getJsonSchema(){return this.jsonSchema}getInputFile(){return this.inputFile}getDefaultFileEncoding(){return this.defaultFileEncoding}getFileSystemService(){return this.fileSystemService}setFileSystemService(e){this.fileSystemService=e}getChatCompression(){return this.chatCompression}isInteractive(){return this.interactive}getUseRipgrep(){return this.useRipgrep}getUseBuiltinRipgrep(){return this.useBuiltinRipgrep}getShouldUseNodePtyShell(){return this.shouldUseNodePtyShell}getSkipNextSpeakerCheck(){return this.skipNextSpeakerCheck}getShellExecutionConfig(){return this.shellExecutionConfig}setShellExecutionConfig(e){this.shellExecutionConfig={terminalWidth:e.terminalWidth??this.shellExecutionConfig.terminalWidth,terminalHeight:e.terminalHeight??this.shellExecutionConfig.terminalHeight,showColor:e.showColor??this.shellExecutionConfig.showColor,pager:e.pager??this.shellExecutionConfig.pager,maxBufferedOutputBytes:e.maxBufferedOutputBytes??this.shellExecutionConfig.maxBufferedOutputBytes}}getScreenReader(){return this.accessibility.screenReader??!1}getSkipLoopDetection(){return this.skipLoopDetection}getSkipStartupContext(){return this.skipStartupContext}getBareMode(){return this.bareMode}getTruncateToolOutputThreshold(){return this.truncateToolOutputThreshold<=0?Number.POSITIVE_INFINITY:this.truncateToolOutputThreshold}getTruncateToolOutputLines(){return this.truncateToolOutputLines<=0?Number.POSITIVE_INFINITY:this.truncateToolOutputLines}getToolOutputBatchBudget(){return this.toolOutputBatchBudget<=0?Number.POSITIVE_INFINITY:this.toolOutputBatchBudget}trackToolResultBytes(e){this.toolResultBudget.bytesWritten+=e}getToolResultBytesWritten(){return this.toolResultBudget.bytesWritten}getOutputFormat(){return this.outputFormat}getChatRecordingService(){if(this.chatRecordingEnabled)return this.chatRecordingService||(this.chatRecordingService=new oh(this)),this.chatRecordingService}getTranscriptPath(){if(!this.chatRecordingEnabled)return"";let e=this.sessionStorage.getProjectDir(),n=`${this.getSessionId()}.jsonl`;return Vr.join(e,"chats",n)}getSessionService(){return this.sessionService||(this.sessionService=new Uv(this.sessionStorageDir,this.sessionRuntimeBaseDir)),this.sessionService}getFileExclusions(){return this.fileExclusions}getSubagentManager(){return this.subagentManager}getBackgroundTaskRegistry(){return this.backgroundTaskRegistry}getMonitorRegistry(){return this.monitorRegistry}getBackgroundAgentResumeService(){return this.backgroundAgentResumeService||(this.backgroundAgentResumeService=new KA(this)),this.backgroundAgentResumeService}async loadPausedBackgroundAgents(e=this.getSessionId()){return this.getBackgroundAgentResumeService().loadPausedBackgroundAgents(e)}async resumeBackgroundAgent(e,t){return this.getBackgroundAgentResumeService().resumeBackgroundAgent(e,t)}abandonBackgroundAgent(e){return this.getBackgroundAgentResumeService().abandonBackgroundAgent(e)}getBackgroundShellRegistry(){return this.backgroundShellRegistry}getWorkflowRunRegistry(){return this.workflowRunRegistry}getFileReadCache(){return Object.prototype.hasOwnProperty.call(this,"fileReadCache")||(this.fileReadCache=new Py),this.fileReadCache}getFileReadCacheDisabled(){return this.fileReadCacheDisabled}getShouldAvoidPermissionPrompts(){return!1}getSkillManager(){return this.skillManager}setModelInvocableCommandsProvider(e){this.modelInvocableCommandsProvider=e}getModelInvocableCommandsProvider(){return this.modelInvocableCommandsProvider}setModelInvocableCommandsExecutor(e){this.modelInvocableCommandsExecutor=e}getModelInvocableCommandsExecutor(){return this.modelInvocableCommandsExecutor}addInlineAnnouncedSkillKeys(e){for(let t of e)this.pendingInlineAnnouncedSkillKeys.add(t)}consumeInlineAnnouncedSkillKeys(){let e=this.pendingInlineAnnouncedSkillKeys;return this.pendingInlineAnnouncedSkillKeys=new Set,e}getPermissionManager(){return this.permissionManager}getOnPersistPermissionRule(){return this.onPersistPermissionRuleCallback}getOnRefreshPermissionsFromDisk(){return this.onRefreshPermissionsFromDiskCallback}async createToolRegistry(e,t){let n=new mT(this,this.eventEmitter,e),s=async(a,l)=>{let c=!0;try{c=this.permissionManager?await this.permissionManager.isToolEnabled(a):!0}catch(u){this.debugLogger.warn(`Failed to check permissions for tool "${a}", skipping registration:`,u);return}c&&n.registerFactory(a,l)},o=async()=>{if(!this.jsonSchema||t?.forSubAgent)return;let a=this.jsonSchema;await s(R.STRUCTURED_OUTPUT,async()=>{let{SyntheticOutputTool:l}=await import("./syntheticOutput-QEUQIVQJ.js");return new l(a)})};if(this.getBareMode())return await s(R.READ_FILE,async()=>{let{ReadFileTool:a}=await import("./read-file-J5UBJYDO.js");return new a(this)}),await s(R.EDIT,async()=>{let{EditTool:a}=await import("./edit-CVFKTJ7G.js");return new a(this)}),await s(R.NOTEBOOK_EDIT,async()=>{let{NotebookEditTool:a}=await import("./notebook-edit-WK6NUSID.js");return new a(this)}),await s(R.SHELL,async()=>{let{ShellTool:a}=await import("./shell-XGVUYVXY.js");return new a(this)}),await o(),this.debugLogger.debug(`ToolRegistry created: ${JSON.stringify(n.getAllToolNames())} (${n.getAllToolNames().length} tools)`),n;if(await s(R.TOOL_SEARCH,async()=>{let{ToolSearchTool:a}=await import("./tool-search-OWJC3UTX.js");return new a(this)}),await s(R.AGENT,async()=>{let{AgentTool:a}=await import("./agent-HFMBAASZ.js");return new a(this)}),await s(R.TASK_STOP,async()=>{let{TaskStopTool:a}=await import("./task-stop-JO3CXG2K.js");return new a(this)}),await s(R.SEND_MESSAGE,async()=>{let{SendMessageTool:a}=await import("./send-message-XXRROIL7.js");return new a(this)}),await s(R.SKILL,async()=>{let{SkillTool:a}=await import("./skill-DQMUM4ZC.js");return new a(this)}),await s(R.LS,async()=>{let{LSTool:a}=await import("./ls-CLDNF3YS.js");return new a(this)}),await s(R.READ_FILE,async()=>{let{ReadFileTool:a}=await import("./read-file-J5UBJYDO.js");return new a(this)}),this.getUseRipgrep()){let a=!1,l;try{a=await zK(this.getUseBuiltinRipgrep())}catch(c){l=ne(c)}a?await s(R.GREP,async()=>{let{RipGrepTool:c}=await import("./ripGrep-R55EA2GB.js");return new c(this)}):(x2(this,new z2(this.getUseRipgrep(),this.getUseBuiltinRipgrep(),l||"ripgrep is not available")),await s(R.GREP,async()=>{let{GrepTool:c}=await import("./grep-GZETX354.js");return new c(this)}))}else await s(R.GREP,async()=>{let{GrepTool:a}=await import("./grep-GZETX354.js");return new a(this)});if(await s(R.GLOB,async()=>{let{GlobTool:a}=await import("./glob-FZNZJN65.js");return new a(this)}),await s(R.EDIT,async()=>{let{EditTool:a}=await import("./edit-CVFKTJ7G.js");return new a(this)}),await s(R.NOTEBOOK_EDIT,async()=>{let{NotebookEditTool:a}=await import("./notebook-edit-WK6NUSID.js");return new a(this)}),await s(R.WRITE_FILE,async()=>{let{WriteFileTool:a}=await import("./write-file-UJBDQOXN.js");return new a(this)}),await s(R.SHELL,async()=>{let{ShellTool:a}=await import("./shell-XGVUYVXY.js");return new a(this)}),await s(R.TODO_WRITE,async()=>{let{TodoWriteTool:a}=await import("./todoWrite-7BZMVNBC.js");return new a(this)}),await s(R.UPDATE_GOAL,async()=>{let{UpdateGoalTool:a}=await import("./update-goal-CF6G57J7.js");return new a(this)}),await s(R.ASK_USER_QUESTION,async()=>{let{AskUserQuestionTool:a}=await import("./askUserQuestion-MJ4FTAOQ.js");return new a(this)}),this.sdkMode||(await s(R.EXIT_PLAN_MODE,async()=>{let{ExitPlanModeTool:a}=await import("./exitPlanMode-KQINMKFC.js");return new a(this)}),await s(R.ENTER_PLAN_MODE,async()=>{let{EnterPlanModeTool:a}=await import("./enterPlanMode-LMRR4777.js");return new a(this)})),await s(R.ENTER_WORKTREE,async()=>{let{EnterWorktreeTool:a}=await import("./enter-worktree-LJBEPBPI.js");return new a(this)}),await s(R.EXIT_WORKTREE,async()=>{let{ExitWorktreeTool:a}=await import("./exit-worktree-V7KTGJSX.js");return new a(this)}),await s(R.WEB_FETCH,async()=>{let{WebFetchTool:a}=await import("./web-fetch-K575OWZ7.js");return new a(this)}),await s(R.WEB_SEARCH,async()=>{let{WebSearchTool:a}=await import("./web-search-F6JRBXFV.js");return new a(this)}),await s(R.SYMBOL_SEARCH,async()=>{let{SymbolSearchTool:a}=await import("./symbol-search-3MVTK4KV.js");return new a(this)}),this.isLspEnabled()&&this.getLspClient()&&await s(R.LSP,async()=>{let{LspTool:a}=await import("./lsp-7SKRKR5Q.js");return new a(this)}),await o(),this.isCronEnabled()&&(await s(R.CRON_CREATE,async()=>{let{CronCreateTool:a}=await import("./cron-create-BTTPO3JC.js");return new a(this)}),await s(R.CRON_LIST,async()=>{let{CronListTool:a}=await import("./cron-list-J4HRR46K.js");return new a(this)}),await s(R.CRON_DELETE,async()=>{let{CronDeleteTool:a}=await import("./cron-delete-U55RHRID.js");return new a(this)})),this.isAgentTeamEnabled()&&(await s(R.TEAM_CREATE,async()=>{let{TeamCreateTool:a}=await import("./team-create-C6VPLV6L.js");return new a(this)}),await s(R.TEAM_DELETE,async()=>{let{TeamDeleteTool:a}=await import("./team-delete-4YYLUV23.js");return new a(this)}),await s(R.TASK_CREATE,async()=>{let{TaskCreateTool:a}=await import("./task-create-AEJQ73GE.js");return new a(this)}),await s(R.TASK_UPDATE,async()=>{let{TaskUpdateTool:a}=await import("./task-update-3YY37VFN.js");return new a(this)}),await s(R.TASK_LIST,async()=>{let{TaskListTool:a}=await import("./task-list-ZEJTNZ2O.js");return new a(this)})),this.isWorkflowsEnabled()&&await s(R.WORKFLOW,async()=>{let{WorkflowTool:a}=await import("./workflow-JEXF4MOH.js");return new a(this)}),this.isComputerUseEnabled()){let{registerComputerUseTools:a}=await import("./computer-use-D32TORJM.js");await a(s,this)}if(await s(R.MONITOR,async()=>{let{MonitorTool:a}=await import("./monitor-MI2Y2MO2.js");return new a(this)}),this.pendingMcpBudgetCallback){let a=n.getMcpClientManager();a&&typeof a.setOnBudgetEvent=="function"&&a.setOnBudgetEvent(this.pendingMcpBudgetCallback),this.pendingMcpBudgetCallback=void 0}return t?.skipDiscovery||await n.discoverAllTools(),this.debugLogger.debug(`ToolRegistry created: ${JSON.stringify(n.getAllToolNames())} (${n.getAllToolNames().length} tools)`),n}setMcpBudgetEventCallback(e){if(this.toolRegistry){let t=this.toolRegistry.getMcpClientManager?.();t&&typeof t.setOnBudgetEvent=="function"&&t.setOnBudgetEvent(e),this.pendingMcpBudgetCallback=void 0;return}this.pendingMcpBudgetCallback=e}};g();var F5e="refs/notes/ai-attribution";function Gde(r,e){let t=JSON.stringify(r);return Buffer.byteLength(t,"utf-8")>30720?null:{command:"git",args:["notes",`--ref=${F5e}`,"add","-f","-m",t,e]}}var bhe=Ge(il(),1);g();import*as Vde from"node:fs";var zb=class extends Error{constructor(t,n){super(t);this.errorType=n;Object.setPrototypeOf(this,new.target.prototype)}name="StructuredToolError"};function $R(r){return r instanceof zb||typeof r=="object"&&r!==null&&r.name==="StructuredToolError"&&"errorType"in r}async function Kde(r,e,t,n={}){let s;try{s=await Vde.promises.stat(e)}catch(h){let f=h?.code;if(f==="ENOENT"){if(n.expectExisting){let w=`File ${e} disappeared after the model read it (stat now returns ENOENT). Re-read with the ${R.READ_FILE} tool \u2014 the path may have been deleted or moved \u2014 before retrying ${t} it.`;return{ok:!1,type:"file_changed_since_read",rawMessage:w,displayMessage:`file disappeared after last read; re-run ${R.READ_FILE} first.`}}return{ok:!0}}let p=`Could not stat ${e} to verify prior read (${f??"unknown error"}). Re-read with the ${R.READ_FILE} tool, then retry ${t} it.`,y=t==="editing"?"editing this file":"overwriting this file";return{ok:!1,type:"prior_read_verification_failed",rawMessage:p,displayMessage:`cannot verify prior read of ${e}; re-run ${R.READ_FILE} before ${y}.`}}if(s.isDirectory()){let h=t==="editing"?"edit":"overwrite",f=`${e} is a directory. The Edit / WriteFile tools only operate on regular files. Use a different mechanism (e.g. the shell tool) if you need to ${h} the contents of this directory.`;return{ok:!1,type:"target_is_directory",rawMessage:f,displayMessage:`path is a directory; cannot ${h} via this tool.`}}if(!s.isFile()){let h=t==="editing"?"edit":"overwrite",f=`${e} is a FIFO / socket / character or block device. The Edit / WriteFile tools only operate on regular files; the ${R.READ_FILE} tool also rejects these targets. Use a different mechanism (e.g. shell tool with the appropriate command) if you need to ${h} this path.`;return{ok:!1,type:"edit_requires_prior_read",rawMessage:f,displayMessage:`special file; cannot ${h} via this tool.`}}let o=r.check(s);if(o.state==="fresh"&&o.entry.lastReadAt!==void 0&&o.entry.lastReadCacheable)return{ok:!0};if(o.state==="stale"){let h=`File ${e} has been modified since you last read it (mtime or size changed). Re-read it with the ${R.READ_FILE} tool before ${t} it to ensure your changes are based on current content.`;return{ok:!1,type:"file_changed_since_read",rawMessage:h,displayMessage:`file changed since last read; re-run ${R.READ_FILE} first.`}}if(o.state==="fresh"&&o.entry.lastReadAt!==void 0&&!o.entry.lastReadCacheable){let h=t==="editing"?"edit":"overwrite",f=`File ${e} is a binary / image / audio / video / PDF / notebook payload that the ${R.READ_FILE} tool returns as a structured value rather than as plain text. The Edit / WriteFile tools cannot mutate that payload safely \u2014 re-reading it would not change this. If this is a Jupyter notebook (.ipynb), use the ${R.NOTEBOOK_EDIT} tool for cell-level edits after reading it. For other non-text files, use a different mechanism (e.g. shell tool with an appropriate writer) if you need to ${h} it.`;return{ok:!1,type:"edit_requires_prior_read",rawMessage:f,displayMessage:`non-text payload; cannot ${h} via this tool.`}}let a=t==="editing"?"edit":"overwrite",l=t==="editing"?"editing this file":"overwriting this file";if(t==="editing"&&n.autoStampUnread!==!1)return r.recordRead(e,s,{full:!0,cacheable:!0}),{ok:!0};let u=t==="editing"?`(a partial read with offset / limit is fine \u2014 you only need to have seen the bytes you intend to ${a})`:"(read the full file \u2014 overwriting replaces every byte, so any unseen bytes would be discarded)",d=`File ${e} has not been read in this session. Use the ${R.READ_FILE} tool first to load the current content ${u} before ${t} it.`;return{ok:!1,type:"edit_requires_prior_read",rawMessage:d,displayMessage:`${R.READ_FILE} required before ${l}.`}}g();var Zde=Ge(il(),1);var Yde=new Set(["+","?","|","(",")","{","}"]),$5e=new Set(["*","+","?"]);function Qde(r){let e=r.trim(),t=e.match(/^\s*sed\s+/);if(!t)return null;let n;try{n=(0,Zde.parse)(e.slice(t[0].length),f=>`$${f}`)}catch{return null}let s=[];for(let f of n){if(typeof f!="string")return null;s.push(f)}let o=!1,a=!1,l=null,c=null,u=0;for(;u<s.length;){let f=s[u];if(U5e(f)){for(let p of f.slice(1))p==="i"?o=!0:a=!0;u++;continue}if(f==="-i"){o=!0,u++,u<s.length&&s[u]===""&&u++;continue}if(f==="--in-place"){o=!0,u++;continue}if(f==="--in-place="){o=!0,u++;continue}if(f.startsWith("-i")||f.startsWith("--in-place="))return null;if(f==="-E"||f==="-r"||f==="--regexp-extended"){a=!0,u++;continue}if(f==="-e"||f==="--expression"){if(l!==null||u+1>=s.length)return null;l=s[u+1],u+=2;continue}if(f.startsWith("--expression=")){if(l!==null)return null;l=f.slice(13),u++;continue}if(f.startsWith("-"))return null;if(l===null)l=f;else if(c===null)c=f;else return null;u++}if(!o||!l||!c||H5e(l)||c.startsWith("~")||c.includes("$"))return null;let d=V5e(l);if(d===null)return null;let h={filePath:c,...d,extendedRegex:a};return B5e(h)?h:null}function U5e(r){if(!r.startsWith("-")||r.startsWith("--")||r.length<=2)return!1;let e=r.slice(1);return!(e.startsWith("i")||!/^[Eri]+$/u.test(e))}function H5e(r){return r.includes("`")||/\$(?:[A-Za-z_][A-Za-z0-9_]*|\{|\(|\d|[#?@$!*])/u.test(r)}function B5e(r){try{let e=rhe(r);return j5e(e)||z5e(e)||(new RegExp(e),q5e(r.replacement,W5e(e)))?!1:!G5e(e)}catch{return!1}}function j5e(r){return/\[\[:[A-Za-z]+:\]\]/u.test(r)}function z5e(r){return/\\[<>dDwWsS]/u.test(r)}function q5e(r,e){for(let t=0;t<r.length;t++){if(r[t]!=="\\")continue;let n=r[t+1];if(n!==void 0&&n>="1"&&n<="9"&&Number(n)>e)return!0;t++}return!1}function W5e(r){let e=0;for(let t=0;t<r.length;t++){let n=r[t];if(n==="\\"){t++;continue}if(n==="["){t=ehe(r,t);continue}n==="("&&r[t+1]!=="?"&&e++}return e}function G5e(r){let e=[];for(let t=0;t<r.length;t++){let n=r[t];if(n==="\\"){t++;continue}if(n==="["){t=ehe(r,t);continue}if(n==="("){e.push({hasAlternation:!1,hasQuantifier:!1});continue}if(n==="|"&&e.length>0){e[e.length-1].hasAlternation=!0;continue}if(n===")"){let o=e.pop();if(o===void 0)continue;let a=Jde(r,t+1);if(a!==null){if(o.hasAlternation||o.hasQuantifier)return!0;e.length>0&&(e[e.length-1].hasQuantifier=!0),t=a-1}if(e.length>0){let l=e[e.length-1];l.hasAlternation||=o.hasAlternation,l.hasQuantifier||=o.hasQuantifier}continue}let s=Jde(r,t);s!==null&&(e.length>0&&(e[e.length-1].hasQuantifier=!0),t=s-1)}return!1}function ehe(r,e){for(let t=e+1;t<r.length;t++){if(r[t]==="\\"){t++;continue}if(r[t]==="]")return t}return r.length-1}function Jde(r,e){let t=r[e];if(t===void 0)return null;if($5e.has(t))return e+1;if(t!=="{")return null;let n=e+1,s=!1;for(;Xde(r[n]);)s=!0,n++;if(!s)return null;if(r[n]===",")for(n++;Xde(r[n]);)n++;return r[n]==="}"?n+1:null}function Xde(r){return r!==void 0&&r>="0"&&r<="9"}function V5e(r){if(/[\r\n]/.test(r)||!r.startsWith("s/"))return null;let e=r.slice(2),t="",n="",s="",o="pattern";for(let a=0;a<e.length;a++){let l=e[a];if(l==="\\"&&a+1<e.length){let c=l+e[a+1];o==="pattern"?t+=c:o==="replacement"?n+=c:s+=c,a++;continue}if(l==="/"){if(o==="pattern")o="replacement";else if(o==="replacement")o="flags";else return null;continue}o==="pattern"?t+=l:o==="replacement"?n+=l:s+=l}return!t||o!=="flags"||!K5e(s)||Y5e(n)?null:{pattern:t,replacement:n,flags:s}}function K5e(r){if(!/^[g0-9]*$/.test(r))return!1;let e=r.match(/\d+/g)??[];return e.length>1?!1:e.length===0?!0:/^[1-9][0-9]*$/.test(e[0])}function Y5e(r){for(let e=0;e<r.length;e++){if(r[e]!=="\\")continue;let t=r[e+1];if(t===void 0||!/[\\/&1-9]/.test(t))return!0;e++}return!1}function the(r,e){if(r.length===0)return"";let t=rhe(e),n=X5e(e.flags),s=e.flags.includes("g");try{let o=new RegExp(t,"g"),a=r.split(/(\n)/);return(r.endsWith(`
2200
2200
  `)?a.slice(0,-1):a).map((c,u)=>u%2===1?c:Z5e(c,o,e.replacement,{occurrence:n,replaceAll:s})).join("")}catch(o){throw new Error(`sed pattern simulation failed: ${ne(o)}`)}}function rhe(r){let e=J5e(r.pattern);if(r.extendedRegex)return e;let t="",n=!1;for(let s=0;s<e.length;s++){let o=e[s];if(n){if(o==="\\"){t+="\\\\";continue}o==="]"&&(n=!1),t+=o;continue}if(o==="["){n=!0,t+=o;continue}if(o==="\\"&&s+1<e.length){let a=e[s+1];Yde.has(a)?t+=a:a==="\\"?t+="\\\\":t+=o+a,s++;continue}if(o==="^"&&s!==0){t+="\\^";continue}if(o==="$"&&s!==e.length-1){t+="\\$";continue}t+=Yde.has(o)?`\\${o}`:o}return t}function J5e(r){let e="";for(let t=0;t<r.length;t++){let n=r[t];if(n==="\\"&&r[t+1]==="/"){e+="/",t++;continue}e+=n}return e}function X5e(r){let e=r.match(/[1-9][0-9]*/);return e?Number(e[0]):null}function Z5e(r,e,t,n){let s=0,o=!1,a=-1;return e.lastIndex=0,r.replace(e,(...l)=>{let c=String(l[0]),u=Number(l[l.length-2]);if(c.length===0&&u===a&&s>0&&o)return"";if(s++,o=c.length>0,a=u+c.length,!(n.occurrence===null?n.replaceAll||s===1:n.replaceAll?s>=n.occurrence:s===n.occurrence))return String(l[0]);let h=l.slice(1,-2).map(f=>f===void 0?"":String(f));return Q5e(c,h,t)})}function Q5e(r,e,t){let n="";for(let s=0;s<t.length;s++){let o=t[s];if(o==="\\"&&s+1<t.length){let a=t[s+1];a==="/"?n+="/":a==="&"?n+="&":a==="\\"?n+="\\":a>="1"&&a<="9"?n+=e[Number(a)-1]??"":n+=o+a,s++;continue}n+=o==="&"?r:o}return n}g();import{isAbsolute as eKe}from"node:path";import{fileURLToPath as tKe,pathToFileURL as rKe}from"node:url";var she=5e3,nKe=10,nhe=200,sKe=5;function UR(r){let e=r.severity??"error";return e==="error"||e==="warning"?e:void 0}function iKe(r){let e=r.replace(/\s+/g," ").trim(),t=[...e];return t.length>nhe?`${t.slice(0,nhe).join("")}\u2026`:e}function ihe(r,e){let t=e.filter(c=>UR(c)==="error").length,n=e.length-t,s=[t>0?`${t} error${t===1?"":"s"}`:"",n>0?`${n} warning${n===1?"":"s"}`:""].filter(Boolean).join(", "),o=e.slice(0,nKe),a=o.map(c=>{let u=(c.range.start.line??0)+1,d=(c.range.start.character??0)+1,h=UR(c)??"error",f=c.code!==void 0?` [${c.code}]`:"",p=c.source?` (${c.source})`:"";return` [${h}] ${u}:${d} ${iKe(c.message)}${f}${p}`}),l=e.length-o.length;return l>0&&a.push(` ... and ${l} more`),`LSP diagnostics for ${r} (${s}):
2201
2201
  ${a.join(`
2202
2202
  `)}`}async function N8t(r,e){try{if(!r.isLspEnabled())return;let t=r.getLspClient();if(!t||!eKe(e))return;let n=rKe(e).toString();t.invalidateDocument?.(n);let s=t.diagnostics(n);s.catch(()=>{});let o,a;try{a=await Promise.race([s,new Promise((c,u)=>{o=setTimeout(()=>u(new Error("LSP diagnostics timed out")),she)})])}finally{o&&clearTimeout(o)}let l=a.filter(c=>UR(c)!==void 0);return l.length===0?void 0:ihe(e,l)}catch{return}}async function ohe(r){try{if(!r.isLspEnabled())return;let e=r.getLspClient();if(!e)return;let t=e.workspaceDiagnostics();t.catch(()=>{});let n,s;try{s=await Promise.race([t,new Promise((u,d)=>{n=setTimeout(()=>d(new Error("LSP workspace diagnostics timed out")),she)})])}finally{n&&clearTimeout(n)}let o=s.map(u=>({filePath:oKe(u.uri),actionable:u.diagnostics.filter(d=>UR(d)!==void 0)})).filter(u=>u.actionable.length>0);if(o.length===0)return;let a=o.slice(0,sKe),l=a.map(u=>ihe(u.filePath,u.actionable)),c=o.length-a.length;return c>0&&l.push(`... and ${c} more file${c===1?"":"s"} with diagnostics`),l.join(`