@maincode-ai/matilda-code 0.19.0 → 0.19.1

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 (35) hide show
  1. package/README.md +45 -0
  2. package/chunks/{agent-HQXJVWNV.js → agent-O7L36PRI.js} +1 -1
  3. package/chunks/{agent-headless-JEQDQMD2.js → agent-headless-ZOO3SBWV.js} +1 -1
  4. package/chunks/{chunk-RIOYZMYO.js → chunk-F2SL32K6.js} +1 -1
  5. package/chunks/{chunk-XOTRZSKL.js → chunk-JQSW4K4X.js} +1 -1
  6. package/chunks/{chunk-FZBNVQAK.js → chunk-NRYMHT3V.js} +8 -8
  7. package/chunks/{chunk-KPVNVGPT.js → chunk-WNEFIZW2.js} +1 -1
  8. package/chunks/{chunk-UCPCZNLX.js → chunk-YTY4VZHQ.js} +13 -13
  9. package/chunks/{chunk-FHR4PQU4.js → chunk-ZX6WKO3S.js} +2 -2
  10. package/chunks/{computer-use-JEQXCG32.js → computer-use-5HO7HQCB.js} +1 -1
  11. package/chunks/{contextCommand-N6WO7T6Y.js → contextCommand-3DHLUVVM.js} +1 -1
  12. package/chunks/{edit-HKSB4XDS.js → edit-GKLQRHLW.js} +1 -1
  13. package/chunks/{enter-worktree-75VMHNQL.js → enter-worktree-2NIHUGOI.js} +1 -1
  14. package/chunks/{enterPlanMode-DFXAPB2C.js → enterPlanMode-PHENGP6O.js} +1 -1
  15. package/chunks/{exit-worktree-H5O6VDZ4.js → exit-worktree-LDVCXGEZ.js} +1 -1
  16. package/chunks/{exitPlanMode-AUYIUGMB.js → exitPlanMode-U3QEDGBI.js} +1 -1
  17. package/chunks/{geminiContentGenerator-W22MIORO.js → geminiContentGenerator-56OUN5BI.js} +1 -1
  18. package/chunks/{glob-QJNBNWZR.js → glob-P43IIJJX.js} +1 -1
  19. package/chunks/{grep-MMFCVW2R.js → grep-6WULIUE2.js} +1 -1
  20. package/chunks/{matildaAgentContentGenerator-SF2SKGQZ.js → matildaAgentContentGenerator-QLZEASVN.js} +1 -1
  21. package/chunks/{matildaContentGenerator-KBHUJJSD.js → matildaContentGenerator-TGCMZZC6.js} +1 -1
  22. package/chunks/{monitor-J5QDRKDF.js → monitor-4N4X3QGD.js} +1 -1
  23. package/chunks/{notebook-edit-3JCVXLO7.js → notebook-edit-CY3IB63X.js} +1 -1
  24. package/chunks/{openaiContentGenerator-JZSNF4UJ.js → openaiContentGenerator-LBEDAHRX.js} +1 -1
  25. package/chunks/{ripGrep-6G4YGFS7.js → ripGrep-N4V3GUFZ.js} +1 -1
  26. package/chunks/{scheduler-AJOK5IA2.js → scheduler-QLV7TX35.js} +1 -1
  27. package/chunks/{serve-VOKMKJM2.js → serve-CIN26WPX.js} +1 -1
  28. package/chunks/{shell-6WBO3IXW.js → shell-C3FX4NO6.js} +1 -1
  29. package/chunks/{src-2ZZ5NI3R.js → src-CZPOL4AN.js} +1 -1
  30. package/chunks/{team-create-QIVBHWVZ.js → team-create-LB3Q5Z6M.js} +1 -1
  31. package/chunks/{web-search-3F5JHEJW.js → web-search-5PWKXHF6.js} +1 -1
  32. package/chunks/{workflow-6UA4CJQT.js → workflow-EUTO2UEN.js} +2 -2
  33. package/chunks/{write-file-3AXYXY35.js → write-file-SXD2ZXSI.js} +1 -1
  34. package/cli.js +352 -353
  35. package/package.json +3 -3
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{a as ke,b as f2,c as jR,d as p2,e as H,f as m2,g as Ye,h as vt,i as g2,j as y2,k as Zt,l as se,m as oe,n as fr,o as Lt,p as zR,q as qR,r as Et,s as zn,t as ue,u as Vt,v as w2,w as WR,x as _2,y as b2}from"./chunk-TZIDSCTF.js";import{d as E2,e as T2,g as M2,h as I2,i as O2,j as GR,m as D2}from"./chunk-FUNLOUYI.js";import{d as L2,k as VR,n as N2,p as F2}from"./chunk-R3H6IWFK.js";import{g as k2,h as x2,i as A2,m as zp,n as R2,p as P2}from"./chunk-OMZ5SGMK.js";import{a as Bt}from"./chunk-S32ZN6LD.js";import{c as UR}from"./chunk-OQ73WWR4.js";import{a as Wb,b as S2,d as XR,e as Kb}from"./chunk-RBG4ERTN.js";import{a as $2,b as H2,c as qp}from"./chunk-TXMXCR7D.js";import{a as KR}from"./chunk-YULUB745.js";import{a as U2,b as B2,c as j2,d as YR,e as z2,f as JR}from"./chunk-LQWORCPO.js";import{a as d2,b as qb,c as h2}from"./chunk-TISQNFB5.js";import{a as Vb,b as Wp}from"./chunk-QEI3OETI.js";import{b as v2,g as Gb,j as jp,k as C2,l as bs}from"./chunk-QKYGQLWC.js";import{a as et,b as kd,d as Ad,e as Rd}from"./chunk-MNGFXISD.js";import{b as Li,d as t2,f as r2,i as ot,j as n2,k as s2,l as i2,m as o2,n as a2,o as l2,p as c2,q as u2}from"./chunk-4R2OFVPK.js";import{b as xd}from"./chunk-RNKDFE2S.js";import{a as e2}from"./chunk-EMWHQSMS.js";import{a as SB}from"./chunk-S4K76QPI.js";import{B as nn,C as BR,F as Td,g as Gj,h as Yj,k as Sc,l as Bp,m as $R,o as HR,r as zb}from"./chunk-FZBNVQAK.js";import{a as Ro,c as FR}from"./chunk-4F4DA5UI.js";import{D as NR,E as Wj}from"./chunk-2MEHZGZJ.js";import{h as Ed,k as Vj,m as Kj,q as Up}from"./chunk-LN2DRVOB.js";import{a as BB,b as Oa,c as Gs,d as jB,f as zB}from"./chunk-4J6DC24J.js";import{$a as Ob,$b as Ej,$c as RR,Ab as mj,Ac as kR,B as YB,Bb as gj,Bc as xR,Cb as yj,Cc as Ao,Db as wj,Eb as _j,Ec as AR,F as vd,G as JB,Gb as yR,Ha as QB,Ic as Lj,Jb as bj,Mc as Nj,Ob as vj,Oc as Fj,Qc as Cd,Rc as $j,Sb as Sd,Sc as Hj,Tb as Sj,Ub as Cj,Va as ej,Vc as Hb,Yb as Lb,Za as tj,_a as Na,_b as wR,aa as XB,ab as rj,ac as wc,ad as vc,bb as nj,bc as _R,bd as Uj,cb as rn,cd as Ub,d as DB,da as La,dc as Tj,ec as bR,ed as PR,f as xo,fc as kj,fd as MR,g as UB,ga as Np,gb as mR,gc as vR,gd as IR,h as jn,ha as Ib,hb as sj,hc as SR,i as Da,ib as ij,ic as CR,id as OR,jb as oj,k as qB,kb as gR,kd as Bj,l as WB,lb as aj,m as GB,mb as lj,mc as xj,nb as cj,nc as Aj,ob as uj,oc as Rj,od as jj,p as gc,pb as dj,pd as zj,q as Lp,qb as hj,qd as qj,r as VB,rb as fj,rc as ER,rd as DR,s as KB,sb as pj,sc as Nb,t as yc,tc as Fb,uc as Mj,ud as LR,vb as Db,vc as Ij,vd as Bb,wd as jb,xc as TR,ya as pR,yc as Hp,za as ZB,zc as Oj}from"./chunk-DY6PIAAY.js";import{b as Di,h as Ar,k as Pj,l as _c,m as Rr,n as bc,o as Fp,s as Vs,t as $p,w as $b}from"./chunk-UY2R3ZQ4.js";import{a as Dj}from"./chunk-4M4CUQUR.js";import{b as LB,c as gde,d as yde,e as NB,f as FB,g as qs,i as Ws,j as $B,k as hR,o as HB,p as R,q as vn,r as Pb,s as Mb}from"./chunk-X6DODPXG.js";import{b as Zj,c as Qj}from"./chunk-LLQVLTPB.js";import{a as Jj,b as Po,c as Xj}from"./chunk-ESSYHTAZ.js";import{b as Ke,c as _s,e as Rb}from"./chunk-IOCF4XSR.js";import{A as kB,C as zs,D as bd,F as mc,G as xB,J as cR,K as uR,L as fe,Q as MB,R as IB,T as OB,W as dR,Y as F,a as Rt,b as xb,c as Q,d as ko,p as CB,r as EB,s as tn,w as _d,z as TB}from"./chunk-QWBNNEV2.js";import{a as fR}from"./chunk-G7R2XEEF.js";import{g as Ab,h as AB,l as RB,n as PB}from"./chunk-FWDMPRKU.js";import{a as __matilda_dirname,b as g}from"./chunk-GZPNIYVZ.js";import{a as be,c as pde,d as L,e as mde,f as Ve}from"./chunk-OWGSC52X.js";var nG=L((gXe,rG)=>{"use strict";g();rG.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 uG=L((wXe,cG)=>{"use strict";g();var lG="(?:"+["\\|\\|","\\&\\&",";;","\\|\\&","\\<\\(","\\<\\<\\<",">>",">\\&","<\\&","[&;()|<>]"].join("|")+")",sG=new RegExp("^"+lG+"$"),iG="|&;()<> \\t",Rge='"((\\\\"|[^"])*?)"',Pge="'((\\\\'|[^'])*?)'",Mge=/^#$/,oG="'",aG='"',T0="$",Uc="",Ige=4294967296;for(k0=0;k0<4;k0++)Uc+=(Ige*Math.random()).toString(16);var k0,Oge=new RegExp("^"+Uc);function Dge(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 Lge(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+Uc+JSON.stringify(n)+Uc:e+n}function Nge(r,e,t){t||(t={});var n=t.escape||"\\",s="(\\"+n+`['"`+iG+`]|[^\\s'"`+iG+"])+",o=new RegExp(["("+lG+")","("+s+"|"+Rge+"|"+Pge+")+"].join("|"),"g"),a=Dge(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(sG.test(u))return{op:u};var h=!1,d=!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 E=u.slice(y);b=E.match(/[^\w\d_]/),b?(v=E.slice(0,b.index),y+=b.index-1):(v=E,y=u.length)}return Lge(e,"",v)}for(y=0;y<u.length;y++){var m=u.charAt(y);if(p=p||!h&&(m==="*"||m==="?"),d)f+=m,d=!1;else if(h)m===h?h=!1:h==oG?f+=m:m===n?(y+=1,m=u.charAt(y),m===aG||m===n||m===T0?f+=m:f+=n+m):m===T0?f+=w():f+=m;else if(m===aG||m===oG)h=m;else{if(sG.test(m))return{op:u};if(Mge.test(m)){l=!0;var _={comment:r.slice(c.index+y+1)};return f.length?[f,_]:[_]}else m===n?d=!0:m===T0?f+=w():f+=m}}return p?{op:"glob",pattern:f}:f}).reduce(function(c,u){return typeof u>"u"?c:c.concat(u)},[])}cG.exports=function(e,t,n){var s=Nge(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("("+Uc+".*?"+Uc+")","g"));return l.length===1?o.concat(l[0]):o.concat(l.filter(Boolean).map(function(c){return Oge.test(c)?JSON.parse(c.split(Uc)[1]):c}))},[])}});var Ka=L(x0=>{"use strict";g();x0.quote=nG();x0.parse=uG()});var BG=L((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=be("fs"),nodePath=be("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 B=0,V=1;;){var G=r[e++];if(B+=(G&127)*V,V*=128,!(G&128))break}return B}function o(){var B=s();return e+=B,UTF8ArrayToString(r,e-B,B)}function a(B,V){if(B)throw new Error(V)}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),h=u[0]==1836278016||u[0]==6386541;a(!h,"need to see wasm magic number"),a(r[8]!==0,"need the dylink section to be first"),e=9;var d=s();t=e+d,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,E=3,T=1;e<t;){var A=n(),k=s();if(A===m)f.memorySize=s(),f.memoryAlign=s(),f.tableSize=s(),f.tableAlign=s();else if(A===_)for(var p=s(),y=0;y<p;++y)w=o(),f.neededDynlibs.push(w);else if(A===b)for(var P=s();P--;){var U=o(),$=s();$&S&&f.tlsExports.add(U)}else if(A===v)for(var P=s();P--;){var I=o(),U=o(),$=s();($&E)==T&&f.weakImports.add(U)}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 h=HEAP8.slice(c,c+u);return e.loadAsync?Promise.resolve(h):h}}var d=locateFile(r);if(e.loadAsync)return new Promise(function(f,p){asyncLoad(d,f,p)});if(!readBinary)throw new Error(`${d}: file not found, and synchronous loading of external files is not available`);return readBinary(d)}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,h)=>(_ts_query_matches_wasm=Module._ts_query_matches_wasm=wasmExports.ts_query_matches_wasm)(r,e,t,n,s,o,a,l,c,u,h),_ts_query_captures_wasm=Module._ts_query_captures_wasm=(r,e,t,n,s,o,a,l,c,u,h)=>(_ts_query_captures_wasm=Module._ts_query_captures_wasm=wasmExports.ts_query_captures_wasm)(r,e,t,n,s,o,a,l,c,u,h),_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 h=0,d=o.length;h<d;h++)e.includes(o[h])&&s.push(h);let a=C._malloc(SIZE_OF_INT*s.length);for(let h=0,d=s.length;h<d;h++)setValue(a+h*SIZE_OF_INT,s[h],"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 h=c;for(let d=0;d<l;d++)u[d]=unmarshalNode(this.tree,h),h+=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 ke,b as f2,c as jR,d as p2,e as H,f as m2,g as Ye,h as vt,i as g2,j as y2,k as Zt,l as se,m as oe,n as fr,o as Lt,p as zR,q as qR,r as Et,s as zn,t as ue,u as Vt,v as w2,w as WR,x as _2,y as b2}from"./chunk-TZIDSCTF.js";import{d as E2,e as T2,g as M2,h as I2,i as O2,j as GR,m as D2}from"./chunk-FUNLOUYI.js";import{d as L2,k as VR,n as N2,p as F2}from"./chunk-R3H6IWFK.js";import{g as k2,h as x2,i as A2,m as zp,n as R2,p as P2}from"./chunk-OMZ5SGMK.js";import{a as Bt}from"./chunk-S32ZN6LD.js";import{c as UR}from"./chunk-OQ73WWR4.js";import{a as Wb,b as S2,d as XR,e as Kb}from"./chunk-RBG4ERTN.js";import{a as $2,b as H2,c as qp}from"./chunk-TXMXCR7D.js";import{a as KR}from"./chunk-YULUB745.js";import{a as U2,b as B2,c as j2,d as YR,e as z2,f as JR}from"./chunk-LQWORCPO.js";import{a as d2,b as qb,c as h2}from"./chunk-TISQNFB5.js";import{a as Vb,b as Wp}from"./chunk-QEI3OETI.js";import{b as v2,g as Gb,j as jp,k as C2,l as bs}from"./chunk-QKYGQLWC.js";import{a as et,b as kd,d as Ad,e as Rd}from"./chunk-MNGFXISD.js";import{b as Li,d as t2,f as r2,i as ot,j as n2,k as s2,l as i2,m as o2,n as a2,o as l2,p as c2,q as u2}from"./chunk-4R2OFVPK.js";import{b as xd}from"./chunk-RNKDFE2S.js";import{a as e2}from"./chunk-EMWHQSMS.js";import{a as SB}from"./chunk-S4K76QPI.js";import{B as nn,C as BR,F as Td,g as Gj,h as Yj,k as Sc,l as Bp,m as $R,o as HR,r as zb}from"./chunk-NRYMHT3V.js";import{a as Ro,c as FR}from"./chunk-4F4DA5UI.js";import{D as NR,E as Wj}from"./chunk-2MEHZGZJ.js";import{h as Ed,k as Vj,m as Kj,q as Up}from"./chunk-LN2DRVOB.js";import{a as BB,b as Oa,c as Gs,d as jB,f as zB}from"./chunk-4J6DC24J.js";import{$a as Ob,$b as Ej,$c as RR,Ab as mj,Ac as kR,B as YB,Bb as gj,Bc as xR,Cb as yj,Cc as Ao,Db as wj,Eb as _j,Ec as AR,F as vd,G as JB,Gb as yR,Ha as QB,Ic as Lj,Jb as bj,Mc as Nj,Ob as vj,Oc as Fj,Qc as Cd,Rc as $j,Sb as Sd,Sc as Hj,Tb as Sj,Ub as Cj,Va as ej,Vc as Hb,Yb as Lb,Za as tj,_a as Na,_b as wR,aa as XB,ab as rj,ac as wc,ad as vc,bb as nj,bc as _R,bd as Uj,cb as rn,cd as Ub,d as DB,da as La,dc as Tj,ec as bR,ed as PR,f as xo,fc as kj,fd as MR,g as UB,ga as Np,gb as mR,gc as vR,gd as IR,h as jn,ha as Ib,hb as sj,hc as SR,i as Da,ib as ij,ic as CR,id as OR,jb as oj,k as qB,kb as gR,kd as Bj,l as WB,lb as aj,m as GB,mb as lj,mc as xj,nb as cj,nc as Aj,ob as uj,oc as Rj,od as jj,p as gc,pb as dj,pd as zj,q as Lp,qb as hj,qd as qj,r as VB,rb as fj,rc as ER,rd as DR,s as KB,sb as pj,sc as Nb,t as yc,tc as Fb,uc as Mj,ud as LR,vb as Db,vc as Ij,vd as Bb,wd as jb,xc as TR,ya as pR,yc as Hp,za as ZB,zc as Oj}from"./chunk-DY6PIAAY.js";import{b as Di,h as Ar,k as Pj,l as _c,m as Rr,n as bc,o as Fp,s as Vs,t as $p,w as $b}from"./chunk-UY2R3ZQ4.js";import{a as Dj}from"./chunk-4M4CUQUR.js";import{b as LB,c as gde,d as yde,e as NB,f as FB,g as qs,i as Ws,j as $B,k as hR,o as HB,p as R,q as vn,r as Pb,s as Mb}from"./chunk-X6DODPXG.js";import{b as Zj,c as Qj}from"./chunk-LLQVLTPB.js";import{a as Jj,b as Po,c as Xj}from"./chunk-ESSYHTAZ.js";import{b as Ke,c as _s,e as Rb}from"./chunk-IOCF4XSR.js";import{A as kB,C as zs,D as bd,F as mc,G as xB,J as cR,K as uR,L as fe,Q as MB,R as IB,T as OB,W as dR,Y as F,a as Rt,b as xb,c as Q,d as ko,p as CB,r as EB,s as tn,w as _d,z as TB}from"./chunk-QWBNNEV2.js";import{a as fR}from"./chunk-G7R2XEEF.js";import{g as Ab,h as AB,l as RB,n as PB}from"./chunk-FWDMPRKU.js";import{a as __matilda_dirname,b as g}from"./chunk-GZPNIYVZ.js";import{a as be,c as pde,d as L,e as mde,f as Ve}from"./chunk-OWGSC52X.js";var nG=L((gXe,rG)=>{"use strict";g();rG.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 uG=L((wXe,cG)=>{"use strict";g();var lG="(?:"+["\\|\\|","\\&\\&",";;","\\|\\&","\\<\\(","\\<\\<\\<",">>",">\\&","<\\&","[&;()|<>]"].join("|")+")",sG=new RegExp("^"+lG+"$"),iG="|&;()<> \\t",Rge='"((\\\\"|[^"])*?)"',Pge="'((\\\\'|[^'])*?)'",Mge=/^#$/,oG="'",aG='"',T0="$",Uc="",Ige=4294967296;for(k0=0;k0<4;k0++)Uc+=(Ige*Math.random()).toString(16);var k0,Oge=new RegExp("^"+Uc);function Dge(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 Lge(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+Uc+JSON.stringify(n)+Uc:e+n}function Nge(r,e,t){t||(t={});var n=t.escape||"\\",s="(\\"+n+`['"`+iG+`]|[^\\s'"`+iG+"])+",o=new RegExp(["("+lG+")","("+s+"|"+Rge+"|"+Pge+")+"].join("|"),"g"),a=Dge(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(sG.test(u))return{op:u};var h=!1,d=!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 E=u.slice(y);b=E.match(/[^\w\d_]/),b?(v=E.slice(0,b.index),y+=b.index-1):(v=E,y=u.length)}return Lge(e,"",v)}for(y=0;y<u.length;y++){var m=u.charAt(y);if(p=p||!h&&(m==="*"||m==="?"),d)f+=m,d=!1;else if(h)m===h?h=!1:h==oG?f+=m:m===n?(y+=1,m=u.charAt(y),m===aG||m===n||m===T0?f+=m:f+=n+m):m===T0?f+=w():f+=m;else if(m===aG||m===oG)h=m;else{if(sG.test(m))return{op:u};if(Mge.test(m)){l=!0;var _={comment:r.slice(c.index+y+1)};return f.length?[f,_]:[_]}else m===n?d=!0:m===T0?f+=w():f+=m}}return p?{op:"glob",pattern:f}:f}).reduce(function(c,u){return typeof u>"u"?c:c.concat(u)},[])}cG.exports=function(e,t,n){var s=Nge(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("("+Uc+".*?"+Uc+")","g"));return l.length===1?o.concat(l[0]):o.concat(l.filter(Boolean).map(function(c){return Oge.test(c)?JSON.parse(c.split(Uc)[1]):c}))},[])}});var Ka=L(x0=>{"use strict";g();x0.quote=nG();x0.parse=uG()});var BG=L((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=be("fs"),nodePath=be("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 B=0,V=1;;){var G=r[e++];if(B+=(G&127)*V,V*=128,!(G&128))break}return B}function o(){var B=s();return e+=B,UTF8ArrayToString(r,e-B,B)}function a(B,V){if(B)throw new Error(V)}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),h=u[0]==1836278016||u[0]==6386541;a(!h,"need to see wasm magic number"),a(r[8]!==0,"need the dylink section to be first"),e=9;var d=s();t=e+d,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,E=3,T=1;e<t;){var A=n(),k=s();if(A===m)f.memorySize=s(),f.memoryAlign=s(),f.tableSize=s(),f.tableAlign=s();else if(A===_)for(var p=s(),y=0;y<p;++y)w=o(),f.neededDynlibs.push(w);else if(A===b)for(var P=s();P--;){var U=o(),$=s();$&S&&f.tlsExports.add(U)}else if(A===v)for(var P=s();P--;){var I=o(),U=o(),$=s();($&E)==T&&f.weakImports.add(U)}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 h=HEAP8.slice(c,c+u);return e.loadAsync?Promise.resolve(h):h}}var d=locateFile(r);if(e.loadAsync)return new Promise(function(f,p){asyncLoad(d,f,p)});if(!readBinary)throw new Error(`${d}: file not found, and synchronous loading of external files is not available`);return readBinary(d)}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,h)=>(_ts_query_matches_wasm=Module._ts_query_matches_wasm=wasmExports.ts_query_matches_wasm)(r,e,t,n,s,o,a,l,c,u,h),_ts_query_captures_wasm=Module._ts_query_captures_wasm=(r,e,t,n,s,o,a,l,c,u,h)=>(_ts_query_captures_wasm=Module._ts_query_captures_wasm=wasmExports.ts_query_captures_wasm)(r,e,t,n,s,o,a,l,c,u,h),_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 h=0,d=o.length;h<d;h++)e.includes(o[h])&&s.push(h);let a=C._malloc(SIZE_OF_INT*s.length);for(let h=0,d=s.length;h<d;h++)setValue(a+h*SIZE_OF_INT,s[h],"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 h=c;for(let d=0;d<l;d++)u[d]=unmarshalNode(this.tree,h),h+=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 h=new Array(l),d=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 E=getValue(v,"i32");v+=SIZE_OF_INT;let T=getValue(v,"i32");if(v+=SIZE_OF_INT,E===PREDICATE_STEP_TYPE_CAPTURE)b.push({type:"capture",name:c[T]});else if(E===PREDICATE_STEP_TYPE_STRING)b.push({type:"string",value:u[T]});else if(b.length>0){if(b[0].type!=="string")throw new Error("Predicates must begin with a literal value");let A=b[0].value,k=!0,P=!0,U;switch(A){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 \`#${A}\` predicate. Expected 2, got ${b.length-1}`);if(b[1].type!=="capture")throw new Error(`First argument of \`#${A}\` predicate must be a capture. Got "${b[1].value}"`);if(P=!A.startsWith("any-"),b[2].type==="capture"){let V=b[1].name,G=b[2].name;y[w].push(z=>{let q=[],W=[];for(let O of z)O.name===V&&q.push(O.node),O.name===G&&W.push(O.node);let x=(O,N,D)=>D?O.text===N.text:O.text!==N.text;return P?q.every(O=>W.some(N=>x(O,N,k))):q.some(O=>W.some(N=>x(O,N,k)))})}else{U=b[1].name;let V=b[2].value,G=q=>q.text===V,z=q=>q.text!==V;y[w].push(q=>{let W=[];for(let O of q)O.name===U&&W.push(O.node);let x=k?G:z;return P?W.every(x):W.some(x)})}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 \`#${A}\` predicate. Expected 2, got ${b.length-1}.`);if(b[1].type!=="capture")throw new Error(`First argument of \`#${A}\` predicate must be a capture. Got "${b[1].value}".`);if(b[2].type!=="string")throw new Error(`Second argument of \`#${A}\` predicate must be a string. Got @${b[2].value}.`);U=b[1].name;let $=new RegExp(b[2].value);P=!A.startsWith("any-"),y[w].push(V=>{let G=[];for(let q of V)q.name===U&&G.push(q.node.text);let z=(q,W)=>W?$.test(q):!$.test(q);return G.length===0?!k:P?G.every(q=>z(q,k)):G.some(q=>z(q,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(V=>V.type!=="string"))throw new Error('Arguments to `#set!` predicate must be a strings.".');h[w]||(h[w]={}),h[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 \`#${A}\` predicate. Expected 1 or 2. Got ${b.length-1}.`);if(b.some(V=>V.type!=="string"))throw new Error(`Arguments to \`#${A}\` predicate must be a strings.".`);let I=A==="is?"?d:f;I[w]||(I[w]={}),I[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 \`#${A}\` predicate. Expected at least 1. Got ${b.length-1}.`);if(b[1].type!=="capture")throw new Error(`First argument of \`#${A}\` predicate must be a capture. Got "${b[1].value}".`);for(let V=2;V<b.length;V++)if(b[V].type!=="string")throw new Error(`Arguments to \`#${A}\` predicate must be a strings.".`);U=b[1].name;let B=b.slice(2).map(V=>V.value);y[w].push(V=>{let G=[];for(let z of V)z.name===U&&G.push(z.node.text);return G.length===0?!k:G.every(z=>B.includes(z))===k});break;default:p[w].push({operator:A,operands:b.slice(1)})}b.length=0}}Object.freeze(h[w]),Object.freeze(d[w]),Object.freeze(f[w])}return C._free(n),new Query(INTERNAL,s,c,y,p,Object.freeze(h),Object.freeze(d),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=be("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:
@@ -2172,7 +2172,7 @@ ${kd(r)}
2172
2172
  The current date is: ${G}. Note: This is the authoritative current date \u2014 it may differ from the "Today's date" mentioned earlier in the conversation startup context.
2173
2173
  </system-reminder>`),this.lastInjectedDate=G)}this.config.getApprovalMode()==="plan"&&I.push(Av(this.config.getSdkMode()));let B=this.config.getArenaManager();if(B)try{let z=`${B.getArenaSessionDir()}/config.json`;I.push(Uq(z))}catch{}let V=await this.tryConsumeMemoryPrefetch();V?.prompt&&I.unshift(V.prompt),T=[...I,...T]}if(a==="toolResult"){let I=await this.tryConsumeMemoryPrefetch();I?.prompt&&(T=[...T,I.prompt]),await this.microcompactHistoryBeforeSend(null,{sizeOnly:!0,pendingContent:Gs(T)})}let A=Ni(this.config.getSessionId());A&&(yield{type:"active_goal",value:A});let k=A,P=I=>{if(!yP(k,I))return k=I,{type:"active_goal",value:I??null}},U=S.run(E,T,t),$=!1;for await(let I of U){b&&!$&&(this.lastSentIdeContext=_,this.forceFullIdeContext=!1,$=!0);let B=this.config.getSkipLoopDetection(),V=!B&&this.loopDetector.addAndCheckDeterministicToolCallLoop(I),G=!V&&!B&&this.loopDetector.addAndCheckHeuristicLoops(I);if(V||G){let z=this.loopDetector.getLastLoopType();if(I.type==="tool_call_request"&&z==="consecutive_identical_tool_calls"){let q=this.loopDetector.getConsecutiveToolCallCount(),W=Math.max(0,S.pendingToolCalls.length-q);S.pendingToolCalls.splice(W)}return yield{type:"loop_detected",...z&&{value:{loopType:z}}},v&&await v.reportError("Loop detected"),this.lastApiCompletionTimestamp=Date.now(),u&&rn("error",{errorMessage:"loop detected"}),this.cancelPendingMemoryPrefetch(),S}if(v&&I.type==="finished"&&await v.updateStatus(),I.type==="chat_compressed"){this.forceFullIdeContext=!0;try{await this.restoreStartupContextAfterCompaction()}catch(z){this.config.getDebugLogger().warn(`Failed to restore startup context after compaction: ${z}`)}this.fireSessionStartHook("compact").then(z=>{!z||!this.chat||(this.lastSessionStartContext=z,this.lastSessionStartSource="compact",this.chat.applySessionStartContext(z,"compact"))}).catch(z=>{this.config.getDebugLogger().warn(`SessionStart hook failed: ${z}`)})}if(yield I,I.type==="error"){if(this.forceFullIdeContext=!0,v){let z=I.value instanceof Error?I.value.message:"Unknown error";await v.reportError(z)}if(this.lastApiCompletionTimestamp=Date.now(),u){let z=I.value instanceof Error?"[API error]":"unknown error";rn("error",{errorMessage:z})}return this.cancelPendingMemoryPrefetch(),S}}if(this.lastApiCompletionTimestamp=Date.now(),l&&c&&!S.pendingToolCalls.length&&t&&!t.aborted&&this.config.hasHooksForEvent("Stop")){let I=this.getLastModelMessageText()||"[no response text]",B=await c.request({type:"hook-execution-request",eventName:"Stop",input:{stop_hook_active:!0,last_assistant_message:I},signal:t},"hook-execution-response"),V=Ni(this.config.getSessionId());if(t.aborted){let W=P(V);return W&&(yield W),u&&rn("cancelled"),S}let z=B.output?ot("Stop",B.output):void 0;if(z?.systemMessage&&(yield{type:"hook_system_message",value:z.systemMessage}),z?.isBlockingDecision()||z?.shouldStopExecution()){if(t.aborted){let ae=P(V);return ae&&(yield ae),u&&rn("cancelled"),S}let W=z.getEffectiveReason(),x=(s?.stopHookState?.iterationCount??0)+1,O=[...s?.stopHookState?.reasons??[],W],N=this.config.getStopHookBlockingCap();if(x>=N){let ae=Dc("Stop",N);TP(this.config,this.config.getSessionId(),ae);let M=Ni(this.config.getSessionId()),ne=P(M);return ne&&(yield ne),yield{type:"hook_system_message",value:ae},Ze.warn(ae),u&&rn("ok"),S}let D=P(V);D&&(yield D),yield{type:"stop_hook_loop",value:{iterationCount:x,reasons:O,stopHookCount:B.stopHookCount??1}};let j=[{text:W}],K=Ni(this.config.getSessionId())?d:d-1,Y=yield*this.sendMessageStream(j,t,n,{type:"hook",modelOverride:s?.modelOverride,stopHookState:{iterationCount:x,reasons:O}},K);return u&&rn(t.aborted?"cancelled":"ok"),h=!0,Y}let q=P(V);q&&(yield q)}if(!S.pendingToolCalls.length&&t&&!t.aborted){try{let V=this.getChat(),z=this.getHistoryTailShallow(40,!0);Uce(V.getGenerationConfig(),z,this.config.getModel())}catch{}let I=hz(this.config.getApprovalMode());if(this.config.getSkipNextSpeakerCheck()&&!I)return this.runManagedAutoMemoryBackgroundTasks(a),v&&await v.reportCompleted(),u&&rn("ok"),S;let B=await Sue(this.getChat(),this.config,t,n);if(Cj(this.config,new Hj(n,S.finishReason?.toString()||"",B?.next_speaker||"")),B?.next_speaker==="model"){let V=[{text:"Please continue."}],G=yield*this.sendMessageStream(V,t,n,{...s,type:"hook"},d-1);return u&&rn(t.aborted?"cancelled":"ok"),h=!0,G}this.runManagedAutoMemoryBackgroundTasks(a),v&&await v.reportCompleted()}return t?.aborted&&v&&await v.reportCancelled(),u&&rn(t?.aborted?"cancelled":"ok"),h=!0,S}finally{h||this.cancelPendingMemoryPrefetch(),u&&rn(t?.aborted?"cancelled":"error",{errorMessage:"unexpected exit"})}}async generateContent(e,t,n,s,o){let a=o??jE.getStore()??this.lastPromptId,l=s;try{let c=this.config.getUserMemory(),u=t.systemInstruction?mm(t.systemInstruction,c):this.getMainSessionSystemInstruction(),h={abortSignal:n,...t,systemInstruction:u},{contentGenerator:d,retryAuthType:f,retryErrorCodes:p,model:y}=await this.config.getBaseLlmClient().resolveForModel(s);return await Pc(()=>(l=y,d.generateContent({model:y,config:h,contents:e},a)),{authType:f,extraRetryErrorCodes:p,persistentMode:Rc(),signal:n,heartbeatFn:_=>{lB.stderr.write(`[matilda-code] Waiting for API capacity... attempt ${_.attempt}, retry in ${Math.ceil(_.remainingMs/1e3)}s
2174
2174
  `)},onRetry:_=>{wc(this.config,new vc({model:l,promptId:a,attemptNumber:_.attempt,error:_.error,statusCode:_.errorStatus,retryDelayMs:_.delayMs,subagentName:xo.getStore()}))}})}catch(c){throw n.aborted?c:(await vs(c,`Error generating content via API with model ${l}.`,{requestContents:e,requestConfig:t},"generateContent-api"),new Error(`Failed to generate content with model ${l}: ${Q(c)}`))}}async tryCompressChat(e,t=!1,n,s){let o=this.lastSessionStartContext,a=this.lastSessionStartSource,l=await this.getChat().tryCompress(e,this.config.getModel(),t,n,s?{customInstructions:s}:void 0);if(l.compressionStatus===1){let c=this.getChat(),u=c.getHistoryShallow?.()??c.getHistory();await this.startChat(u,"compact"),!this.lastSessionStartContext&&o&&a&&(this.lastSessionStartContext=o,this.lastSessionStartSource=a,this.getChat().applySessionStartContext(o,a)),Ze.debug("[FILE_READ_CACHE] clear after tryCompressChat"),this.config.getFileReadCache().clear(),this.getChat().setLastPromptTokenCount(l.newTokenCount),this.forceFullIdeContext=!0}return l}async disarmFileReadCacheAfterEviction(e,t){let n=this.config.getFileReadCache();if(e.unresolvedEvictedReads>0){Ze.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=>GVe.stat(a).catch(()=>{}))),o=!0;for(let a of s)(!a||!n.markReadEvictedFromHistory(a))&&(o=!1);o?Ze.debug(`[FILE_READ_CACHE] disarmed fast-path for ${e.evictedReadPaths.length} file(s) after ${t}`):(Ze.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 Ip from"node:fs/promises";import*as Eue from"node:path";var pd=F("WORKTREE_CLEANUP"),ZVe=[RL],QVe=30*24*60*60*1e3;function e8e(r){return ZVe.some(e=>e.test(r))}async function Tue(r,e={}){let t=e.cutoffMs??QVe,n=Date.now()-t,s=new ts(r),o=s.getUserWorktreesDir();try{await Ip.access(o)}catch{return 0}let a;try{a=await Ip.readdir(o,{withFileTypes:!0})}catch(c){return c.code==="ENOENT"||pd.warn(`Failed to read ${o}: ${c}`),0}let l=0;for(let c of a){if(!c.isDirectory()||!e8e(c.name))continue;let u=Eue.join(o,c.name),h;try{h=(await Ip.stat(u)).mtimeMs}catch(y){y.code!=="ENOENT"&&pd.warn(`cleanupStaleAgentWorktrees: cannot stat ${u} \u2014 skipping: ${y}`);continue}if(h>=n)continue;let[d,f]=await Promise.all([t8e(u),s.hasUnmergedWorktreeCommits(c.name)]);if(d||f)continue;let p=await s.removeUserWorktree(c.name,{deleteBranch:!0});if(!p.success){pd.warn(`Failed to remove stale agent worktree ${u}: ${p.error}`);continue}p.branchPreserved?pd.warn(`Removed stale agent worktree ${u} but kept branch ${jy(c.name)} (unmerged commits at delete time)`):pd.debug(`Removed stale agent worktree ${u}`),l+=1}return l>0&&pd.debug(`cleanupStaleAgentWorktrees: removed ${l} stale worktree(s)`),l}async function t8e(r){try{return(await Zr(r).raw(["status","--porcelain","--untracked-files=no"])).trim().length>0}catch(e){return pd.warn(`hasTrackedChanges: cannot inspect ${r} \u2014 assuming dirty: ${e}`),!0}}g();import*as Op from"node:os";import{readFileSync as n8e}from"node:fs";import{EventEmitter as s8e}from"node:events";import{getHeapStatistics as Aue}from"node:v8";g();import*as Sb from"node:fs";import*as cB from"node:path";import*as xue from"node:v8";var vb=F("MEMORY_DUMP"),kue=3,r8e=3e4,QA=class{constructor(e){this.config=e}dumpCount=0;lastDumpTime=0;resetForNewSession(){this.dumpCount=0,this.lastDumpTime=0}async dump(e,t=[]){if(this.dumpCount>=kue){vb.debug(`Skipping dump: session cap reached (${kue})`);return}let n=Date.now();if(n-this.lastDumpTime<r8e){vb.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=cB.join(o,c),h=t[t.length-1],d=h?{rss:h.rss,heapUsed:h.heapUsed,heapTotal:h.heapTotal,external:h.external,arrayBuffers:0}:process.memoryUsage(),f={trigger:e,dumpNumber:s,timestamp:new Date().toISOString(),memoryUsage:d,v8HeapStats:xue.getHeapStatistics(),recentSamples:t,session:this.collectSessionStats(),suggestion:this.getSuggestion(e),collectionComplete:!1};Sb.writeFileSync(u,JSON.stringify(f,null,2),"utf8"),vb.info(`Phase 1 diagnostics written to ${u} (trigger=${e}, dump #${s})`);let p=await Ale({sessionId:a,matildaVersion:this.config.getCliVersion()}),y={trigger:e,dumpNumber:s,...p,recentSamples:t,session:this.collectSessionStats(),suggestion:this.getSuggestion(e),collectionComplete:!0};return Sb.writeFileSync(u,JSON.stringify(y,null,2),"utf8"),vb.info(`Phase 2 diagnostics written to ${u} (trigger=${e}, dump #${s})`),{filePath:u,trigger:e}}catch(o){vb.error(`Failed to write memory diagnostics: ${Q(o)}`);return}}ensureDiagnosticsDir(){let e=this.config.storage.getProjectDir(),t=cB.join(e,"diagnostics");return Sb.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 i8e=60,md;function o8e(){if(md===void 0){try{md=Op.availableParallelism?.()??Op.cpus().length??1}catch{md=1}(!md||md<1)&&(md=1)}return md}function uB(){try{return process.cpuUsage()}catch{return{user:0,system:0}}}var dB=class{samples=[];prevCpuUsage=uB();prevSampleTime=Date.now();record(e){let t=Date.now(),n=t-this.prevSampleTime,s=uB(),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/o8e()));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>i8e&&this.samples.shift(),e}getAll(){return[...this.samples]}reset(){this.samples.length=0,this.prevCpuUsage=uB(),this.prevSampleTime=Date.now()}},eR={softPressureRatio:.5,hardPressureRatio:.65,criticalRatio:.8,cleanupCooldownMs:5e3,enableExplicitGC:!0};function fB(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 it=F("MEMORY_PRESSURE"),a8e=64*1024*1024,Tb=class extends s8e{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 dB;constructor(e,t){super(),this.coreConfig=e,this.config={...t??eR},fB(this.config),this.effectiveMemoryLimit=this.computeEffectiveMemoryLimit(),this.diagnosticsDumper=new QA(e);let n=Aue().heap_size_limit;it.info(`Effective memory limit: ${Eb(this.effectiveMemoryLimit)} MiB; V8 heap limit: ${Eb(n)} MiB`),this.effectiveMemoryLimit<=0&&it.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){it.error(`Memory pressure check failed: ${Q(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);QB()&&(pR(this.coreConfig,l.rss,{memory_type:"rss"}),pR(this.coreConfig,l.heapUsed,{memory_type:"heap_used"}),ZB(this.coreConfig,l.cpuPercent,{}))}catch(l){let c=`Runtime sampling failed: ${Q(l)}`;this.hasLoggedSamplingError?it.debug(c):(this.hasLoggedSamplingError=!0,it.error(c))}if(t==="normal")return;let n=this.recommendCleanup(t);if(n.action==="none")return;let s=Date.now(),o=Cb(n.action)>Cb(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){it.error(`Failed to read memory usage for pressure check: ${Q(e)}`);return}}getPressureLevel(e){let t=e??this.readMemoryUsage();if(!t)return"normal";let n=this.effectiveMemoryLimit>0?t.rss/this.effectiveMemoryLimit:0,s=Aue().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 hB(e)}}executeCleanup(e){if(this.cleanupInProgress){let s=Cb(e.action),o=Cb(this.activeCleanupAction),a=this.queuedCleanupRecommendation?Cb(this.queuedCleanupRecommendation.action):0;s>o&&s>a?(this.queuedCleanupRecommendation=e,it.debug(`Queued escalated cleanup "${e.action}" while "${this.activeCleanupAction}" is in progress`)):it.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){it.error(`Cleanup measurement failed: ${Q(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(it.info(`Cleanup "${n.action}" completed; RSS delta ${s} bytes (${(o*100).toFixed(1)}%)`),o<.01){if(this.consecutiveIneffectiveCleanups++,n.action==="aggressive"&&this.consecutiveIneffectiveAggressiveCleanups++,Rue(this.consecutiveIneffectiveCleanups)){let a={rss:t,freedBytes:s,freedRatio:o,consecutiveIneffectiveCleanups:this.consecutiveIneffectiveCleanups,recommendation:n};it.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=Q(t),s=0;try{s=process.memoryUsage().rss}catch(o){it.error(`Failed to read RSS after cleanup failure: ${Q(o)}`)}this.consecutiveCleanupFailures++,it.error(`Cleanup "${e.action}" failed: ${n}; consecutive failures: ${this.consecutiveCleanupFailures}`),Rue(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){it.error(`${e} handler threw: ${Q(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(),it.debug("FileReadCache cleared");break}case"evict_cold_cache":{let t=this.coreConfig.getFileReadCache().evictNotAccessedSince(30);it.debug(`FileReadCache cold eviction: ${t} entries`);break}case"evict_stale_cache":{let t=this.coreConfig.getFileReadCache().evictNotAccessedSince(60);it.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;it.debug(`global.gc() freed ${t-n} bytes`)}else it.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?.()){it.debug("[COMPACT_HISTORY] skipped: client not initialized");break}let n=t.getChat(),s=n.getHistoryShallow?.()??n.getHistory(),o=this.coreConfig.getClearContextOnIdle(),a=Nd(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;it.debug(`[COMPACT_HISTORY] cleared ${l.toolsCleared} tool result(s) + ${l.mediaCleared} media (~${l.tokensSaved} tokens), kept ${l.toolsKept} tool / ${l.mediaKept} media`)}else it.debug("[COMPACT_HISTORY] nothing to compact")}catch(t){it.error(`[COMPACT_HISTORY] failed: ${Q(t)}`)}break}default:return hB(e)}}computeEffectiveMemoryLimit(){let e=Op.totalmem(),t=this.readCgroupMemoryLimit("/sys/fs/cgroup/memory.max",e);if(t!==void 0)return it.info(`Using cgroup v2 memory limit: ${Eb(t)} MiB`),t;let n=this.readCgroupMemoryLimit("/sys/fs/cgroup/memory/memory.limit_in_bytes",e);return n!==void 0?(it.info(`Using cgroup v1 memory limit: ${Eb(n)} MiB`),n):(it.info(`Using host memory limit: ${Eb(e)} MiB`),e)}readCgroupMemoryLimit(e,t){try{let n=n8e(e,"utf-8").trim();if(n==="max")return;if(!/^-?\d+$/.test(n)){it.warn(`Ignoring non-numeric cgroup memory limit from ${e}: ${n}`);return}let s=Number(n);if(!Number.isFinite(s)||s<=0){it.warn(`Ignoring out-of-range cgroup memory limit from ${e}: ${n}`);return}if(s<a8e){it.warn(`Ignoring unrealistically small cgroup memory limit from ${e}: ${n}`);return}if(!Number.isSafeInteger(s)){it.debug(`Ignoring unlimited cgroup memory limit from ${e}: ${n}`);return}if(t>0&&s>t){it.debug(`Ignoring cgroup memory limit above host total from ${e}: ${n}`);return}return s}catch(n){it.debug(`Failed to read cgroup memory limit from ${e}: `+Q(n));return}}};function Cb(r){switch(r){case"aggressive":return 3;case"moderate":return 2;case"light":return 1;case"none":return 0;default:return hB(r)}}function Rue(r){return r===3||r===10||r>10&&r%20===0}function Eb(r){return(r/1024/1024).toFixed(0)}function hB(r){throw new Error(`Unhandled memory pressure monitor value: ${String(r)}`)}g();var l8e=F("PROMPT_REGISTRY"),tR=class{prompts=new Map;registerPrompt(e){if(this.prompts.has(e.name)){let t=`${e.serverName}_${e.name}`;l8e.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 Pue}from"node:crypto";var c8e=F("GIT_CO_AUTHOR"),u8e=F("MEMORY_PRESSURE"),Mue=.15;var Ss=(o=>(o.PLAN="plan",o.DEFAULT="default",o.AUTO_EDIT="auto-edit",o.AUTO="auto",o.BOGAN="bogan",o))(Ss||{}),EH=Object.values(Ss),mB=class extends Error{constructor(e){super(e),this.name="TrustGateError"}},P4t={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"}},rR="Written by Matilda \u{1F1E6}\u{1F1FA} made by [Maincode](https://maincode.com)";function d8e(r){if(typeof r=="boolean")return{commit:r,pr:r,prMessage:rR};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)||c8e.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:rR;return{commit:e(r?.commit,"commit"),pr:e(r?.pr,"pr"),prMessage:n}}var h8e=25e3,f8e=1e3,p8e=2e5;function M4t(r){return r==="project"||r==="workspace"}var Iue=class{constructor(e,t,n,s,o,a,l,c,u,h,d,f,p,y,w,m,_,b,v,S,E){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=h;this.description=d;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=E}};function An(r){return r.type==="sdk"}var J8=(n=>(n.DYNAMIC_DISCOVERY="dynamic_discovery",n.GOOGLE_CREDENTIALS="google_credentials",n.SERVICE_ACCOUNT_IMPERSONATION="service_account_impersonation",n))(J8||{});function m8e(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 g8e(){let r={...eR};try{r.softPressureRatio=pB("MATILDA_MEMORY_PRESSURE_SOFT",r.softPressureRatio),r.hardPressureRatio=pB("MATILDA_MEMORY_PRESSURE_HARD",r.hardPressureRatio),r.criticalRatio=pB("MATILDA_MEMORY_PRESSURE_CRITICAL",r.criticalRatio);let e=hr.env.MATILDA_MEMORY_ENABLE_GC;e&&["0","false","off","no"].includes(e.trim().toLowerCase())&&(r.enableExplicitGC=!1),fB(r)}catch(e){let t=`[MATILDA] WARNING: Invalid memory pressure config; using defaults. Error: ${Q(e)}`;return hr.stderr.write(`${t}
2175
- `),u8e.warn(t),{...eR}}return r}function pB(r,e){let t=hr.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 y8e=[R.READ_FILE,R.EDIT,R.NOTEBOOK_EDIT,R.SHELL],w8e=Object.freeze(new Set),Oue=!1,dp=class{sessionId;sessionData;pendingStartupWorktreeNotice=null;debugLogger;toolRegistry;pendingMcpBudgetCallback;promptRegistry;subagentManager;memoryPressureConfig;memoryPressureMonitor;backgroundTaskRegistry=new pA;monitorRegistry=new VE;backgroundAgentResumeService;backgroundShellRegistry=new KE;workflowRunRegistry=new YE;fileReadCache=new hy;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=Lm();accessibility;telemetrySettings;outboundCorrelationSettings;gitCoAuthor;usageStatisticsEnabled;fileReadCacheDisabled;geminiClient;baseLlmClient;cronScheduler=null;fileFiltering;fileDiscoveryService=null;sessionService=void 0;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;initialized=!1;storage;runtimeStatusWrite=Promise.resolve();fileExclusions;truncateToolOutputThreshold;truncateToolOutputLines;toolOutputBatchBudget;eventEmitter;channel;jsonFd;jsonFile;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??Pue(),!Oue&&hr.env&&(hr.env.MATILDA_CODE_SESSION_ID=this.sessionId,Oue=!0),this.sessionData=e.sessionData,dR(this),this.debugLogger=F(),this.embeddingModel=e.embeddingModel??FR,this.fileSystemService=new gE,this.sandbox=e.sandbox,this.targetDir=bn.resolve(e.targetDir),this.plansDirectoryConfigured=!!e.plansDirectory?.trim(),this.plansDir=fe.getPlansDir(this.targetDir,e.plansDirectory),this.explicitIncludeDirectories=Array.from(new Set(e.includeDirectories??[])),this.workspaceContext=new Ta(this.targetDir,this.explicitIncludeDirectories),this.debugMode=e.debugMode,this.inputFormat=e.inputFormat??"text";let t=m8e(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??NR,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={...d8e(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??hr.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??60;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.useRipgrep=e.useRipgrep??!0,this.useBuiltinRipgrep=e.useBuiltinRipgrep??!0,this.shouldUseNodePtyShell=e.shouldUseNodePtyShell??IG(),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??h8e,this.truncateToolOutputLines=e.truncateToolOutputLines??f8e,this.toolOutputBatchBudget=e.toolOutputBatchBudget??p8e,this.channel=e.channel,this.jsonFd=e.jsonFd,this.jsonFile=e.jsonFile,this.jsonSchema=e.jsonSchema,this.inputFile=e.inputFile,this.defaultFileEncoding=e.defaultFileEncoding,this.storage=new fe(this.targetDir),this.inputFormat=e.inputFormat??"text",this.fileExclusions=new YB(this),this.eventEmitter=e.eventEmitter,this.arenaAgentClient=nv.create(),this.agentsSettings=e.agents??{},this.worktreeSettings=e.worktree??{},e.contextFileName&&VB(e.contextFileName),this.modelsConfig=new zb({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&&yj(this);let o=this.getProxy();o&&(0,nR.setGlobalDispatcher)(new nR.ProxyAgent(o)),this.geminiClient=new ZA(this),this.chatRecordingService=this.chatRecordingEnabled?new Wd(this):void 0,this.extensionManager=new Kx({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=xP(e.stopHookBlockingCap),this.userHooks=e.userHooks,this.projectHooks=e.projectHooks,this.hooks=e.hooks,this.memoryManager=new bb}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 tR,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 Tp(this),await this.hookSystem.initialize(),this.debugLogger.debug("Hook system initialized"),this.messageBus=new sb,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||{},h=o.signal;switch(o.eventName){case"UserPromptSubmit":l=await a.fireUserPromptSubmitEvent(u.prompt||"",h);break;case"UserPromptExpansion":l=await a.fireUserPromptExpansionEvent(u.command_name||"",u.command_args||"",u.prompt||"",h);break;case"Stop":{let d=await a.fireStopEvent(u.stop_hook_active||!1,u.last_assistant_message||"",h);l=d.finalOutput?ot("Stop",d.finalOutput):void 0,c=d.allOutputs.length;break}case"PreToolUse":{l=await a.firePreToolUseEvent(u.tool_name||"",u.tool_input||{},u.tool_use_id||"",u.permission_mode??"default",h);break}case"PostToolUse":l=await a.firePostToolUseEvent(u.tool_name||"",u.tool_input||{},u.tool_response||{},u.tool_use_id||"",u.permission_mode||"default",h);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",h);break;case"PostToolBatch":l=await a.firePostToolBatchEvent(u.tool_calls||[],u.permission_mode||"default",h);break;case"Notification":l=await a.fireNotificationEvent(u.message||"",u.notification_type||"permission_prompt",u.title||void 0,h);break;case"PermissionRequest":l=await a.firePermissionRequestEvent(u.tool_name||"",u.tool_input||{},u.permission_mode||"default",u.permission_suggestions||void 0,h);break;case"PermissionDenied":l=await a.firePermissionDeniedEvent(u.tool_name||"",u.tool_input||{},u.tool_use_id||"",u.reason||"classifier_blocked",h);break;case"SubagentStart":l=await a.fireSubagentStartEvent(u.agent_id||"",u.agent_type||"",u.permission_mode||"default",h);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",h);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 x_(this),this.skillManager=new I_(this),this.getBareMode()?await this.skillManager.refreshCache():await this.skillManager.startWatching(),this.debugLogger.debug("Skill manager initialized"),this.memoryPressureConfig=g8e(),this.memoryPressureMonitor=new Tb(this,this.memoryPressureConfig),this.permissionManager=new Om(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=hr.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),qn("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 e2().getInstallationId(),yR(this,new AR(this)),this.debugLogger.info("Config initialization completed"),this.getBareMode()||(async()=>{try{let a=await new ts(this.targetDir).getRepoTopLevel()??this.targetDir,l=bn.join(a,".matilda","worktrees");try{await Due.access(l)}catch{this.debugLogger.debug(`Stale worktree sweep skipped: ${l} does not exist`);return}let c=await Tue(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)||LC(n)!=="connected"&&t.push(n);return t}async refreshHierarchicalMemory(e="refresh"){let{memoryContent:t,fileCount:n,conditionalRules:s,projectRoot:o}=await nce(this.getWorkingDir(),this.getMemoryDiscoveryDirectories(),this.getFileService(),this.getExtensionContextFilePaths(),this.isTrustedFolder(),this.getImportFormat(),this.contextRuleExcludes,{explicitOnly:this.getBareMode(),loadReason:e,onInstructionsLoaded:jA(()=>this.hookSystem)});if(this.getManagedAutoMemoryEnabled()){let[a,l]=await Promise.all([XW(this.getProjectRoot()),QW().catch(()=>null)]);this.setUserMemory(this.memoryManager.appendToUserMemory(t,Ar(this.getProjectRoot()),a,{memoryDir:Vs(),indexContent:l}))}else this.setUserMemory(t);this.setGeminiMdFileCount(n),this.conditionalRulesRegistry=new rb(s,o)}buildMemoryContextWarning(e){let t=this.getContentGeneratorConfig()?.contextWindowSize??this.modelsConfig.getGenerationConfig().contextWindowSize??Up(this.getModel(),"input");if(!t||t<=0||!e)return;let n=Math.ceil(e.length/Zs),s=Math.floor(t*Mue);if(!(n<=s))return`Warning: Loaded MATILDA.md/context instructions use about ${n.toLocaleString()} tokens, more than ${Math.round(Mue*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 Sm()?.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}=BR(this,e,this.modelsConfig.getGenerationConfig(),this.modelsConfig.getGenerationConfigSources(),{strictModelProvider:this.modelsConfig.isStrictModelProviderSelection()}),l=o;this.contentGenerator=await Td(l,this,s?!0:t),this.contentGeneratorConfig=l,this.contentGeneratorConfigSources=a,this.baseLlmClient=new Jp(this.contentGenerator,this);let c=this.getMessageBus();!this.getDisableAllHooks()&&c&&Cm(c,`Successfully authenticated with ${e}`,"auth_success","Authentication successful").catch(()=>{})}getBaseLlmClient(){if(!this.baseLlmClient)if(this.contentGenerator)this.baseLlmClient=new Jp(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}startNewSession(e,t){let n=this.chatRecordingService;try{n?.finalize()}catch{}n?.flush().catch(()=>{});let s=this.sessionId;if(this.sessionId=e??Pue(),hr.env&&(hr.env.MATILDA_CODE_SESSION_ID=this.sessionId),this.sessionData=t,dR(this),this.debugLogger=F(),this.chatRecordingService=this.chatRecordingEnabled?new Wd(this):void 0,this.getFileReadCache().clear(),this.toolResultBudget.bytesWritten=0,this.getMemoryPressureMonitor()?.resetForNewSession(),this.fileHistoryService=void 0,wj(this.sessionId),mj(),ei.resetInstance(),this.initialized&&yR(this,new AR(this)),this.runtimeStatusEnabled&&s!==this.sessionId){let o=this.storage.getRuntimeStatusPath(s),a=this.storage.getRuntimeStatusPath(this.sessionId),l=this.cliVersion??null,c=this.targetDir,u=this.sessionId;this.queueRuntimeStatusWrite(async()=>{await fq(o),await GP(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 GP(this.storage.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 Sm()?.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())}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=Ys(this.fastModel);return n?.authType?`${n.authType}:${e.modelId}`:e.modelId}resolveFastModelSelector(){if(this.fastModel)try{return Ys(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}=BR(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=hr.env.SEATBELT_PROFILE;return!!e&&e.command==="sandbox-exec"&&!!t&&t.startsWith("restrictive-")}getTargetDir(){return this.targetDir}getCurrentSessionArtifactMoves(e,t){let n=bn.join(e.getProjectDir(),"chats"),s=bn.join(t.getProjectDir(),"chats");return[`${this.sessionId}.jsonl`,`${this.sessionId}.runtime.json`,`${this.sessionId}.worktree.json`].map(o=>({from:bn.join(n,o),to:bn.join(s,o)}))}moveFile(e,t){try{mt.renameSync(e,t)}catch(n){if(n.code!=="EXDEV")throw n;let s=!1;try{mt.copyFileSync(e,t),s=!0,mt.unlinkSync(e)}catch(o){if(s)try{mt.unlinkSync(t)}catch{}throw o}}}moveCurrentSessionArtifacts(e,t){let n=[];for(let{from:s,to:o}of this.getCurrentSessionArtifactMoves(e,t))if(mt.existsSync(s)){mt.mkdirSync(bn.dirname(o),{recursive:!0});try{this.moveFile(s,o),n.push({from:s,to:o})}catch(a){for(let l of n.reverse())try{mt.mkdirSync(bn.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?.flush(),await this.flushRuntimeStatusWrites();try{this.moveCurrentSessionArtifacts(e,t)}catch(s){try{hr.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=mt.realpathSync(hr.cwd()),s=bn.resolve(e),o=t??mt.realpathSync(s);if(!mt.statSync(s).isDirectory())throw new Error(`Path is not a directory: ${s}`);let a=Ta.resolveRootDirectories(o,this.explicitIncludeDirectories);hr.chdir(s);let l=mt.realpathSync(hr.cwd());if(l!==o)throw hr.chdir(n),new Error(`Changed directory to ${l}, expected ${o}.`);let c=this.storage,u=new fe(o);await this.prepareSessionArtifactMigration(c,u,n),this.targetDir=o,this.cwd=o,this.storage=u,this.chatRecordingService?.resetStoragePaths(),await this.refreshCurrentRuntimeStatus(o),this.workspaceContext.applyRootDirectories(a),this.fileDiscoveryService=null,this.sessionService=void 0,this.fileHistoryService=void 0,this.getFileReadCache().clear();try{return await this.refreshHierarchicalMemory(),{}}catch(h){return{memoryRefreshError:h}}}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?.flush()}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{gj()&&await _j()}}getPromptRegistry(){return this.promptRegistry}getDebugMode(){return this.debugMode}getQuestion(){return this.question}getSystemPrompt(){return this.systemPrompt}getAppendSystemPrompt(){return this.appendSystemPrompt}getCoreTools(){return this.getBareMode()?y8e: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?.()??w8e}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 mB("Cannot enable privileged approval modes in an untrusted folder.");e==="plan"&&this.approvalMode!=="plan"?(this.prePlanMode=this.approvalMode,this.planGateState=dz(++this.planGateEntryCounter)):e!=="plan"&&this.approvalMode==="plan"&&(this.prePlanMode=void 0,this.planGateState=void 0);let t=this.approvalMode;this.permissionManager&&(e==="auto"&&t!=="auto"?this.permissionManager.stripDangerousRulesForAutoMode():t==="auto"&&e!=="auto"&&this.permissionManager.restoreDangerousRules()),t!==e&&(this.autoModeDenialState=J0()),this.approvalMode=e}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 mt.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 bn.join(this.plansDir,`${fe.sanitizePlanSessionId(this.sessionId)}.md`)}savePlan(e){this.assertPlansDirWithinTargetDir();let t=this.getPlanFilePath(),n=bn.dirname(t);mt.mkdirSync(n,{recursive:!0});let s=t+".tmp";mt.writeFileSync(s,e,"utf-8");try{mt.renameSync(s,t)}catch(o){if(o.code!=="EXDEV")throw o;mt.copyFileSync(s,t),mt.unlinkSync(s)}try{this.assertPlanFilePathWithinTargetDir(t)}catch(o){try{mt.unlinkSync(t)}catch{}throw o}}loadPlan(){this.assertPlansDirWithinTargetDir();let e=this.getPlanFilePath();this.assertPlanFilePathWithinTargetDir(e);try{return mt.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??Wj}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??NR}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 Tb(this,this.memoryPressureConfig)}return this.memoryPressureMonitor}getCronScheduler(){return this.cronScheduler||(this.cronScheduler=new VC(this.getProjectRoot())),this.cronScheduler}isCronEnabled(){return hr.env.MATILDA_CODE_DISABLE_CRON==="1"?!1:this.cronEnabled}isAgentTeamEnabled(){return hr.env.MATILDA_CODE_ENABLE_AGENT_TEAM==="1"?!0:this.agentTeamEnabled}isWorkflowsEnabled(){return hr.env.MATILDA_CODE_DISABLE_WORKFLOWS==="1"?!1:hr.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=hr.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 _v(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 ice(this.proxy)}getWorkingDir(){return this.cwd}getBugCommand(){return this.bugCommand}getFileService(){return this.fileDiscoveryService||(this.fileDiscoveryService=new wl(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()||!Zj()}getIdeMode(){return this.ideMode}getFolderTrustFeature(){return this.folderTrustFeature}getFolderTrust(){return this.folderTrust}getAllowedHttpHookUrls(){return this.getBareMode()?[]:this.allowedHttpHookUrls}isTrustedFolder(){let e=Tu.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}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 Wd(this)),this.chatRecordingService}getTranscriptPath(){if(!this.chatRecordingEnabled)return"";let e=this.storage.getProjectDir(),n=`${this.getSessionId()}.jsonl`;return bn.join(e,"chats",n)}getSessionService(){return this.sessionService||(this.sessionService=new Sv(this.targetDir)),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 gA(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 hy),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}async createToolRegistry(e,t){let n=new FC(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-NSQJLEEY.js");return new l(a)})};if(this.getBareMode())return await s(R.READ_FILE,async()=>{let{ReadFileTool:a}=await import("./read-file-MUUE7CJM.js");return new a(this)}),await s(R.EDIT,async()=>{let{EditTool:a}=await import("./edit-HKSB4XDS.js");return new a(this)}),await s(R.NOTEBOOK_EDIT,async()=>{let{NotebookEditTool:a}=await import("./notebook-edit-3JCVXLO7.js");return new a(this)}),await s(R.SHELL,async()=>{let{ShellTool:a}=await import("./shell-6WBO3IXW.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-UA3I7UV3.js");return new a(this)}),await s(R.AGENT,async()=>{let{AgentTool:a}=await import("./agent-HQXJVWNV.js");return new a(this)}),await s(R.TASK_STOP,async()=>{let{TaskStopTool:a}=await import("./task-stop-5R44O4NK.js");return new a(this)}),await s(R.SEND_MESSAGE,async()=>{let{SendMessageTool:a}=await import("./send-message-BPTEYK4Y.js");return new a(this)}),await s(R.SKILL,async()=>{let{SkillTool:a}=await import("./skill-D23JCWUG.js");return new a(this)}),await s(R.LS,async()=>{let{LSTool:a}=await import("./ls-ZSHUDEJV.js");return new a(this)}),await s(R.READ_FILE,async()=>{let{ReadFileTool:a}=await import("./read-file-MUUE7CJM.js");return new a(this)}),this.getUseRipgrep()){let a=!1,l;try{a=await m5(this.getUseBuiltinRipgrep())}catch(c){l=Q(c)}a?await s(R.GREP,async()=>{let{RipGrepTool:c}=await import("./ripGrep-6G4YGFS7.js");return new c(this)}):(vj(this,new Fj(this.getUseRipgrep(),this.getUseBuiltinRipgrep(),l||"ripgrep is not available")),await s(R.GREP,async()=>{let{GrepTool:c}=await import("./grep-MMFCVW2R.js");return new c(this)}))}else await s(R.GREP,async()=>{let{GrepTool:a}=await import("./grep-MMFCVW2R.js");return new a(this)});if(await s(R.GLOB,async()=>{let{GlobTool:a}=await import("./glob-QJNBNWZR.js");return new a(this)}),await s(R.EDIT,async()=>{let{EditTool:a}=await import("./edit-HKSB4XDS.js");return new a(this)}),await s(R.NOTEBOOK_EDIT,async()=>{let{NotebookEditTool:a}=await import("./notebook-edit-3JCVXLO7.js");return new a(this)}),await s(R.WRITE_FILE,async()=>{let{WriteFileTool:a}=await import("./write-file-3AXYXY35.js");return new a(this)}),await s(R.SHELL,async()=>{let{ShellTool:a}=await import("./shell-6WBO3IXW.js");return new a(this)}),await s(R.TODO_WRITE,async()=>{let{TodoWriteTool:a}=await import("./todoWrite-V4DQMEDR.js");return new a(this)}),await s(R.ASK_USER_QUESTION,async()=>{let{AskUserQuestionTool:a}=await import("./askUserQuestion-QPVUWJCI.js");return new a(this)}),this.sdkMode||(await s(R.EXIT_PLAN_MODE,async()=>{let{ExitPlanModeTool:a}=await import("./exitPlanMode-AUYIUGMB.js");return new a(this)}),await s(R.ENTER_PLAN_MODE,async()=>{let{EnterPlanModeTool:a}=await import("./enterPlanMode-DFXAPB2C.js");return new a(this)})),await s(R.ENTER_WORKTREE,async()=>{let{EnterWorktreeTool:a}=await import("./enter-worktree-75VMHNQL.js");return new a(this)}),await s(R.EXIT_WORKTREE,async()=>{let{ExitWorktreeTool:a}=await import("./exit-worktree-H5O6VDZ4.js");return new a(this)}),await s(R.WEB_FETCH,async()=>{let{WebFetchTool:a}=await import("./web-fetch-XRYT2EOQ.js");return new a(this)}),await s(R.WEB_SEARCH,async()=>{let{WebSearchTool:a}=await import("./web-search-3F5JHEJW.js");return new a(this)}),await s(R.SYMBOL_SEARCH,async()=>{let{SymbolSearchTool:a}=await import("./symbol-search-3E5XK5S6.js");return new a(this)}),this.isLspEnabled()&&this.getLspClient()&&await s(R.LSP,async()=>{let{LspTool:a}=await import("./lsp-DW3UNQQ6.js");return new a(this)}),await o(),this.isCronEnabled()&&(await s(R.CRON_CREATE,async()=>{let{CronCreateTool:a}=await import("./cron-create-K35JKX3K.js");return new a(this)}),await s(R.CRON_LIST,async()=>{let{CronListTool:a}=await import("./cron-list-FCX6HCY7.js");return new a(this)}),await s(R.CRON_DELETE,async()=>{let{CronDeleteTool:a}=await import("./cron-delete-7B65R7JC.js");return new a(this)})),this.isAgentTeamEnabled()&&(await s(R.TEAM_CREATE,async()=>{let{TeamCreateTool:a}=await import("./team-create-QIVBHWVZ.js");return new a(this)}),await s(R.TEAM_DELETE,async()=>{let{TeamDeleteTool:a}=await import("./team-delete-LWX4LMFZ.js");return new a(this)}),await s(R.TASK_CREATE,async()=>{let{TaskCreateTool:a}=await import("./task-create-TQI5N4YR.js");return new a(this)}),await s(R.TASK_UPDATE,async()=>{let{TaskUpdateTool:a}=await import("./task-update-PL2JDIF6.js");return new a(this)}),await s(R.TASK_LIST,async()=>{let{TaskListTool:a}=await import("./task-list-DQBF34BK.js");return new a(this)})),this.isWorkflowsEnabled()&&await s(R.WORKFLOW,async()=>{let{WorkflowTool:a}=await import("./workflow-6UA4CJQT.js");return new a(this)}),this.isComputerUseEnabled()){let{registerComputerUseTools:a}=await import("./computer-use-JEQXCG32.js");await a(s,this)}if(await s(R.MONITOR,async()=>{let{MonitorTool:a}=await import("./monitor-J5QDRKDF.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 _8e="refs/notes/ai-attribution";function Lue(r,e){let t=JSON.stringify(r);return Buffer.byteLength(t,"utf-8")>30720?null:{command:"git",args:["notes",`--ref=${_8e}`,"add","-f","-m",t,e]}}var ide=Ve(Ka(),1);g();import*as Nue from"node:fs";var gd=class extends Error{constructor(t,n){super(t);this.errorType=n}name="StructuredToolError"};async function Fue(r,e,t,n={}){let s;try{s=await Nue.promises.stat(e)}catch(h){let d=h?.code;if(d==="ENOENT"){if(n.expectExisting){let y=`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:y,displayMessage:`file disappeared after last read; re-run ${R.READ_FILE} first.`}}return{ok:!0}}let f=`Could not stat ${e} to verify prior read (${d??"unknown error"}). Re-read with the ${R.READ_FILE} tool, then retry ${t} it.`,p=t==="editing"?"editing this file":"overwriting this file";return{ok:!1,type:"prior_read_verification_failed",rawMessage:f,displayMessage:`cannot verify prior read of ${e}; re-run ${R.READ_FILE} before ${p}.`}}if(s.isDirectory()){let h=t==="editing"?"edit":"overwrite",d=`${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:d,displayMessage:`path is a directory; cannot ${h} via this tool.`}}if(!s.isFile()){let h=t==="editing"?"edit":"overwrite",d=`${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:d,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",d=`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:d,displayMessage:`non-text payload; cannot ${h} via this tool.`}}let a=t==="editing"?"edit":"overwrite",l=t==="editing"?"editing this file":"overwriting this file",c=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)",u=`File ${e} has not been read in this session. Use the ${R.READ_FILE} tool first to load the current content ${c} before ${t} it.`;return{ok:!1,type:"edit_requires_prior_read",rawMessage:u,displayMessage:`${R.READ_FILE} required before ${l}.`}}g();var Bue=Ve(Ka(),1);var $ue=new Set(["+","?","|","(",")","{","}"]),b8e=new Set(["*","+","?"]);function jue(r){let e=r.trim(),t=e.match(/^\s*sed\s+/);if(!t)return null;let n;try{n=(0,Bue.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(v8e(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||S8e(l)||c.startsWith("~")||c.includes("$"))return null;let h=R8e(l);if(h===null)return null;let d={filePath:c,...h,extendedRegex:a};return C8e(d)?d:null}function v8e(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 S8e(r){return r.includes("`")||/\$(?:[A-Za-z_][A-Za-z0-9_]*|\{|\(|\d|[#?@$!*])/u.test(r)}function C8e(r){try{let e=Wue(r);return E8e(e)||T8e(e)||(new RegExp(e),k8e(r.replacement,x8e(e)))?!1:!A8e(e)}catch{return!1}}function E8e(r){return/\[\[:[A-Za-z]+:\]\]/u.test(r)}function T8e(r){return/\\[<>dDwWsS]/u.test(r)}function k8e(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 x8e(r){let e=0;for(let t=0;t<r.length;t++){let n=r[t];if(n==="\\"){t++;continue}if(n==="["){t=zue(r,t);continue}n==="("&&r[t+1]!=="?"&&e++}return e}function A8e(r){let e=[];for(let t=0;t<r.length;t++){let n=r[t];if(n==="\\"){t++;continue}if(n==="["){t=zue(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=Hue(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=Hue(r,t);s!==null&&(e.length>0&&(e[e.length-1].hasQuantifier=!0),t=s-1)}return!1}function zue(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 Hue(r,e){let t=r[e];if(t===void 0)return null;if(b8e.has(t))return e+1;if(t!=="{")return null;let n=e+1,s=!1;for(;Uue(r[n]);)s=!0,n++;if(!s)return null;if(r[n]===",")for(n++;Uue(r[n]);)n++;return r[n]==="}"?n+1:null}function Uue(r){return r!==void 0&&r>="0"&&r<="9"}function R8e(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"||!P8e(s)||M8e(n)?null:{pattern:t,replacement:n,flags:s}}function P8e(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 M8e(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 que(r,e){if(r.length===0)return"";let t=Wue(e),n=O8e(e.flags),s=e.flags.includes("g");try{let o=new RegExp(t,"g"),a=r.split(/(\n)/);return(r.endsWith(`
2175
+ `),u8e.warn(t),{...eR}}return r}function pB(r,e){let t=hr.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 y8e=[R.READ_FILE,R.EDIT,R.NOTEBOOK_EDIT,R.SHELL],w8e=Object.freeze(new Set),Oue=!1,dp=class{sessionId;sessionData;pendingStartupWorktreeNotice=null;debugLogger;toolRegistry;pendingMcpBudgetCallback;promptRegistry;subagentManager;memoryPressureConfig;memoryPressureMonitor;backgroundTaskRegistry=new pA;monitorRegistry=new VE;backgroundAgentResumeService;backgroundShellRegistry=new KE;workflowRunRegistry=new YE;fileReadCache=new hy;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=Lm();accessibility;telemetrySettings;outboundCorrelationSettings;gitCoAuthor;usageStatisticsEnabled;fileReadCacheDisabled;geminiClient;baseLlmClient;cronScheduler=null;fileFiltering;fileDiscoveryService=null;sessionService=void 0;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;initialized=!1;storage;runtimeStatusWrite=Promise.resolve();fileExclusions;truncateToolOutputThreshold;truncateToolOutputLines;toolOutputBatchBudget;eventEmitter;channel;jsonFd;jsonFile;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??Pue(),!Oue&&hr.env&&(hr.env.MATILDA_CODE_SESSION_ID=this.sessionId,Oue=!0),this.sessionData=e.sessionData,dR(this),this.debugLogger=F(),this.embeddingModel=e.embeddingModel??FR,this.fileSystemService=new gE,this.sandbox=e.sandbox,this.targetDir=bn.resolve(e.targetDir),this.plansDirectoryConfigured=!!e.plansDirectory?.trim(),this.plansDir=fe.getPlansDir(this.targetDir,e.plansDirectory),this.explicitIncludeDirectories=Array.from(new Set(e.includeDirectories??[])),this.workspaceContext=new Ta(this.targetDir,this.explicitIncludeDirectories),this.debugMode=e.debugMode,this.inputFormat=e.inputFormat??"text";let t=m8e(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??NR,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={...d8e(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??hr.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??60;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.useRipgrep=e.useRipgrep??!0,this.useBuiltinRipgrep=e.useBuiltinRipgrep??!0,this.shouldUseNodePtyShell=e.shouldUseNodePtyShell??IG(),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??h8e,this.truncateToolOutputLines=e.truncateToolOutputLines??f8e,this.toolOutputBatchBudget=e.toolOutputBatchBudget??p8e,this.channel=e.channel,this.jsonFd=e.jsonFd,this.jsonFile=e.jsonFile,this.jsonSchema=e.jsonSchema,this.inputFile=e.inputFile,this.defaultFileEncoding=e.defaultFileEncoding,this.storage=new fe(this.targetDir),this.inputFormat=e.inputFormat??"text",this.fileExclusions=new YB(this),this.eventEmitter=e.eventEmitter,this.arenaAgentClient=nv.create(),this.agentsSettings=e.agents??{},this.worktreeSettings=e.worktree??{},e.contextFileName&&VB(e.contextFileName),this.modelsConfig=new zb({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&&yj(this);let o=this.getProxy();o&&(0,nR.setGlobalDispatcher)(new nR.ProxyAgent(o)),this.geminiClient=new ZA(this),this.chatRecordingService=this.chatRecordingEnabled?new Wd(this):void 0,this.extensionManager=new Kx({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=xP(e.stopHookBlockingCap),this.userHooks=e.userHooks,this.projectHooks=e.projectHooks,this.hooks=e.hooks,this.memoryManager=new bb}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 tR,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 Tp(this),await this.hookSystem.initialize(),this.debugLogger.debug("Hook system initialized"),this.messageBus=new sb,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||{},h=o.signal;switch(o.eventName){case"UserPromptSubmit":l=await a.fireUserPromptSubmitEvent(u.prompt||"",h);break;case"UserPromptExpansion":l=await a.fireUserPromptExpansionEvent(u.command_name||"",u.command_args||"",u.prompt||"",h);break;case"Stop":{let d=await a.fireStopEvent(u.stop_hook_active||!1,u.last_assistant_message||"",h);l=d.finalOutput?ot("Stop",d.finalOutput):void 0,c=d.allOutputs.length;break}case"PreToolUse":{l=await a.firePreToolUseEvent(u.tool_name||"",u.tool_input||{},u.tool_use_id||"",u.permission_mode??"default",h);break}case"PostToolUse":l=await a.firePostToolUseEvent(u.tool_name||"",u.tool_input||{},u.tool_response||{},u.tool_use_id||"",u.permission_mode||"default",h);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",h);break;case"PostToolBatch":l=await a.firePostToolBatchEvent(u.tool_calls||[],u.permission_mode||"default",h);break;case"Notification":l=await a.fireNotificationEvent(u.message||"",u.notification_type||"permission_prompt",u.title||void 0,h);break;case"PermissionRequest":l=await a.firePermissionRequestEvent(u.tool_name||"",u.tool_input||{},u.permission_mode||"default",u.permission_suggestions||void 0,h);break;case"PermissionDenied":l=await a.firePermissionDeniedEvent(u.tool_name||"",u.tool_input||{},u.tool_use_id||"",u.reason||"classifier_blocked",h);break;case"SubagentStart":l=await a.fireSubagentStartEvent(u.agent_id||"",u.agent_type||"",u.permission_mode||"default",h);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",h);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 x_(this),this.skillManager=new I_(this),this.getBareMode()?await this.skillManager.refreshCache():await this.skillManager.startWatching(),this.debugLogger.debug("Skill manager initialized"),this.memoryPressureConfig=g8e(),this.memoryPressureMonitor=new Tb(this,this.memoryPressureConfig),this.permissionManager=new Om(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=hr.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),qn("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 e2().getInstallationId(),yR(this,new AR(this)),this.debugLogger.info("Config initialization completed"),this.getBareMode()||(async()=>{try{let a=await new ts(this.targetDir).getRepoTopLevel()??this.targetDir,l=bn.join(a,".matilda","worktrees");try{await Due.access(l)}catch{this.debugLogger.debug(`Stale worktree sweep skipped: ${l} does not exist`);return}let c=await Tue(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)||LC(n)!=="connected"&&t.push(n);return t}async refreshHierarchicalMemory(e="refresh"){let{memoryContent:t,fileCount:n,conditionalRules:s,projectRoot:o}=await nce(this.getWorkingDir(),this.getMemoryDiscoveryDirectories(),this.getFileService(),this.getExtensionContextFilePaths(),this.isTrustedFolder(),this.getImportFormat(),this.contextRuleExcludes,{explicitOnly:this.getBareMode(),loadReason:e,onInstructionsLoaded:jA(()=>this.hookSystem)});if(this.getManagedAutoMemoryEnabled()){let[a,l]=await Promise.all([XW(this.getProjectRoot()),QW().catch(()=>null)]);this.setUserMemory(this.memoryManager.appendToUserMemory(t,Ar(this.getProjectRoot()),a,{memoryDir:Vs(),indexContent:l}))}else this.setUserMemory(t);this.setGeminiMdFileCount(n),this.conditionalRulesRegistry=new rb(s,o)}buildMemoryContextWarning(e){let t=this.getContentGeneratorConfig()?.contextWindowSize??this.modelsConfig.getGenerationConfig().contextWindowSize??Up(this.getModel(),"input");if(!t||t<=0||!e)return;let n=Math.ceil(e.length/Zs),s=Math.floor(t*Mue);if(!(n<=s))return`Warning: Loaded MATILDA.md/context instructions use about ${n.toLocaleString()} tokens, more than ${Math.round(Mue*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 Sm()?.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}=BR(this,e,this.modelsConfig.getGenerationConfig(),this.modelsConfig.getGenerationConfigSources(),{strictModelProvider:this.modelsConfig.isStrictModelProviderSelection()}),l=o;this.contentGenerator=await Td(l,this,s?!0:t),this.contentGeneratorConfig=l,this.contentGeneratorConfigSources=a,this.baseLlmClient=new Jp(this.contentGenerator,this);let c=this.getMessageBus();!this.getDisableAllHooks()&&c&&Cm(c,`Successfully authenticated with ${e}`,"auth_success","Authentication successful").catch(()=>{})}getBaseLlmClient(){if(!this.baseLlmClient)if(this.contentGenerator)this.baseLlmClient=new Jp(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}startNewSession(e,t){let n=this.chatRecordingService;try{n?.finalize()}catch{}n?.flush().catch(()=>{});let s=this.sessionId;if(this.sessionId=e??Pue(),hr.env&&(hr.env.MATILDA_CODE_SESSION_ID=this.sessionId),this.sessionData=t,dR(this),this.debugLogger=F(),this.chatRecordingService=this.chatRecordingEnabled?new Wd(this):void 0,this.getFileReadCache().clear(),this.toolResultBudget.bytesWritten=0,this.getMemoryPressureMonitor()?.resetForNewSession(),this.fileHistoryService=void 0,wj(this.sessionId),mj(),ei.resetInstance(),this.initialized&&yR(this,new AR(this)),this.runtimeStatusEnabled&&s!==this.sessionId){let o=this.storage.getRuntimeStatusPath(s),a=this.storage.getRuntimeStatusPath(this.sessionId),l=this.cliVersion??null,c=this.targetDir,u=this.sessionId;this.queueRuntimeStatusWrite(async()=>{await fq(o),await GP(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 GP(this.storage.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 Sm()?.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())}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=Ys(this.fastModel);return n?.authType?`${n.authType}:${e.modelId}`:e.modelId}resolveFastModelSelector(){if(this.fastModel)try{return Ys(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}=BR(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=hr.env.SEATBELT_PROFILE;return!!e&&e.command==="sandbox-exec"&&!!t&&t.startsWith("restrictive-")}getTargetDir(){return this.targetDir}getCurrentSessionArtifactMoves(e,t){let n=bn.join(e.getProjectDir(),"chats"),s=bn.join(t.getProjectDir(),"chats");return[`${this.sessionId}.jsonl`,`${this.sessionId}.runtime.json`,`${this.sessionId}.worktree.json`].map(o=>({from:bn.join(n,o),to:bn.join(s,o)}))}moveFile(e,t){try{mt.renameSync(e,t)}catch(n){if(n.code!=="EXDEV")throw n;let s=!1;try{mt.copyFileSync(e,t),s=!0,mt.unlinkSync(e)}catch(o){if(s)try{mt.unlinkSync(t)}catch{}throw o}}}moveCurrentSessionArtifacts(e,t){let n=[];for(let{from:s,to:o}of this.getCurrentSessionArtifactMoves(e,t))if(mt.existsSync(s)){mt.mkdirSync(bn.dirname(o),{recursive:!0});try{this.moveFile(s,o),n.push({from:s,to:o})}catch(a){for(let l of n.reverse())try{mt.mkdirSync(bn.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?.flush(),await this.flushRuntimeStatusWrites();try{this.moveCurrentSessionArtifacts(e,t)}catch(s){try{hr.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=mt.realpathSync(hr.cwd()),s=bn.resolve(e),o=t??mt.realpathSync(s);if(!mt.statSync(s).isDirectory())throw new Error(`Path is not a directory: ${s}`);let a=Ta.resolveRootDirectories(o,this.explicitIncludeDirectories);hr.chdir(s);let l=mt.realpathSync(hr.cwd());if(l!==o)throw hr.chdir(n),new Error(`Changed directory to ${l}, expected ${o}.`);let c=this.storage,u=new fe(o);await this.prepareSessionArtifactMigration(c,u,n),this.targetDir=o,this.cwd=o,this.storage=u,this.chatRecordingService?.resetStoragePaths(),await this.refreshCurrentRuntimeStatus(o),this.workspaceContext.applyRootDirectories(a),this.fileDiscoveryService=null,this.sessionService=void 0,this.fileHistoryService=void 0,this.getFileReadCache().clear();try{return await this.refreshHierarchicalMemory(),{}}catch(h){return{memoryRefreshError:h}}}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?.flush()}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{gj()&&await _j()}}getPromptRegistry(){return this.promptRegistry}getDebugMode(){return this.debugMode}getQuestion(){return this.question}getSystemPrompt(){return this.systemPrompt}getAppendSystemPrompt(){return this.appendSystemPrompt}getCoreTools(){return this.getBareMode()?y8e: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?.()??w8e}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 mB("Cannot enable privileged approval modes in an untrusted folder.");e==="plan"&&this.approvalMode!=="plan"?(this.prePlanMode=this.approvalMode,this.planGateState=dz(++this.planGateEntryCounter)):e!=="plan"&&this.approvalMode==="plan"&&(this.prePlanMode=void 0,this.planGateState=void 0);let t=this.approvalMode;this.permissionManager&&(e==="auto"&&t!=="auto"?this.permissionManager.stripDangerousRulesForAutoMode():t==="auto"&&e!=="auto"&&this.permissionManager.restoreDangerousRules()),t!==e&&(this.autoModeDenialState=J0()),this.approvalMode=e}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 mt.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 bn.join(this.plansDir,`${fe.sanitizePlanSessionId(this.sessionId)}.md`)}savePlan(e){this.assertPlansDirWithinTargetDir();let t=this.getPlanFilePath(),n=bn.dirname(t);mt.mkdirSync(n,{recursive:!0});let s=t+".tmp";mt.writeFileSync(s,e,"utf-8");try{mt.renameSync(s,t)}catch(o){if(o.code!=="EXDEV")throw o;mt.copyFileSync(s,t),mt.unlinkSync(s)}try{this.assertPlanFilePathWithinTargetDir(t)}catch(o){try{mt.unlinkSync(t)}catch{}throw o}}loadPlan(){this.assertPlansDirWithinTargetDir();let e=this.getPlanFilePath();this.assertPlanFilePathWithinTargetDir(e);try{return mt.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??Wj}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??NR}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 Tb(this,this.memoryPressureConfig)}return this.memoryPressureMonitor}getCronScheduler(){return this.cronScheduler||(this.cronScheduler=new VC(this.getProjectRoot())),this.cronScheduler}isCronEnabled(){return hr.env.MATILDA_CODE_DISABLE_CRON==="1"?!1:this.cronEnabled}isAgentTeamEnabled(){return hr.env.MATILDA_CODE_ENABLE_AGENT_TEAM==="1"?!0:this.agentTeamEnabled}isWorkflowsEnabled(){return hr.env.MATILDA_CODE_DISABLE_WORKFLOWS==="1"?!1:hr.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=hr.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 _v(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 ice(this.proxy)}getWorkingDir(){return this.cwd}getBugCommand(){return this.bugCommand}getFileService(){return this.fileDiscoveryService||(this.fileDiscoveryService=new wl(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()||!Zj()}getIdeMode(){return this.ideMode}getFolderTrustFeature(){return this.folderTrustFeature}getFolderTrust(){return this.folderTrust}getAllowedHttpHookUrls(){return this.getBareMode()?[]:this.allowedHttpHookUrls}isTrustedFolder(){let e=Tu.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}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 Wd(this)),this.chatRecordingService}getTranscriptPath(){if(!this.chatRecordingEnabled)return"";let e=this.storage.getProjectDir(),n=`${this.getSessionId()}.jsonl`;return bn.join(e,"chats",n)}getSessionService(){return this.sessionService||(this.sessionService=new Sv(this.targetDir)),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 gA(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 hy),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}async createToolRegistry(e,t){let n=new FC(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-NSQJLEEY.js");return new l(a)})};if(this.getBareMode())return await s(R.READ_FILE,async()=>{let{ReadFileTool:a}=await import("./read-file-MUUE7CJM.js");return new a(this)}),await s(R.EDIT,async()=>{let{EditTool:a}=await import("./edit-GKLQRHLW.js");return new a(this)}),await s(R.NOTEBOOK_EDIT,async()=>{let{NotebookEditTool:a}=await import("./notebook-edit-CY3IB63X.js");return new a(this)}),await s(R.SHELL,async()=>{let{ShellTool:a}=await import("./shell-C3FX4NO6.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-UA3I7UV3.js");return new a(this)}),await s(R.AGENT,async()=>{let{AgentTool:a}=await import("./agent-O7L36PRI.js");return new a(this)}),await s(R.TASK_STOP,async()=>{let{TaskStopTool:a}=await import("./task-stop-5R44O4NK.js");return new a(this)}),await s(R.SEND_MESSAGE,async()=>{let{SendMessageTool:a}=await import("./send-message-BPTEYK4Y.js");return new a(this)}),await s(R.SKILL,async()=>{let{SkillTool:a}=await import("./skill-D23JCWUG.js");return new a(this)}),await s(R.LS,async()=>{let{LSTool:a}=await import("./ls-ZSHUDEJV.js");return new a(this)}),await s(R.READ_FILE,async()=>{let{ReadFileTool:a}=await import("./read-file-MUUE7CJM.js");return new a(this)}),this.getUseRipgrep()){let a=!1,l;try{a=await m5(this.getUseBuiltinRipgrep())}catch(c){l=Q(c)}a?await s(R.GREP,async()=>{let{RipGrepTool:c}=await import("./ripGrep-N4V3GUFZ.js");return new c(this)}):(vj(this,new Fj(this.getUseRipgrep(),this.getUseBuiltinRipgrep(),l||"ripgrep is not available")),await s(R.GREP,async()=>{let{GrepTool:c}=await import("./grep-6WULIUE2.js");return new c(this)}))}else await s(R.GREP,async()=>{let{GrepTool:a}=await import("./grep-6WULIUE2.js");return new a(this)});if(await s(R.GLOB,async()=>{let{GlobTool:a}=await import("./glob-P43IIJJX.js");return new a(this)}),await s(R.EDIT,async()=>{let{EditTool:a}=await import("./edit-GKLQRHLW.js");return new a(this)}),await s(R.NOTEBOOK_EDIT,async()=>{let{NotebookEditTool:a}=await import("./notebook-edit-CY3IB63X.js");return new a(this)}),await s(R.WRITE_FILE,async()=>{let{WriteFileTool:a}=await import("./write-file-SXD2ZXSI.js");return new a(this)}),await s(R.SHELL,async()=>{let{ShellTool:a}=await import("./shell-C3FX4NO6.js");return new a(this)}),await s(R.TODO_WRITE,async()=>{let{TodoWriteTool:a}=await import("./todoWrite-V4DQMEDR.js");return new a(this)}),await s(R.ASK_USER_QUESTION,async()=>{let{AskUserQuestionTool:a}=await import("./askUserQuestion-QPVUWJCI.js");return new a(this)}),this.sdkMode||(await s(R.EXIT_PLAN_MODE,async()=>{let{ExitPlanModeTool:a}=await import("./exitPlanMode-U3QEDGBI.js");return new a(this)}),await s(R.ENTER_PLAN_MODE,async()=>{let{EnterPlanModeTool:a}=await import("./enterPlanMode-PHENGP6O.js");return new a(this)})),await s(R.ENTER_WORKTREE,async()=>{let{EnterWorktreeTool:a}=await import("./enter-worktree-2NIHUGOI.js");return new a(this)}),await s(R.EXIT_WORKTREE,async()=>{let{ExitWorktreeTool:a}=await import("./exit-worktree-LDVCXGEZ.js");return new a(this)}),await s(R.WEB_FETCH,async()=>{let{WebFetchTool:a}=await import("./web-fetch-XRYT2EOQ.js");return new a(this)}),await s(R.WEB_SEARCH,async()=>{let{WebSearchTool:a}=await import("./web-search-5PWKXHF6.js");return new a(this)}),await s(R.SYMBOL_SEARCH,async()=>{let{SymbolSearchTool:a}=await import("./symbol-search-3E5XK5S6.js");return new a(this)}),this.isLspEnabled()&&this.getLspClient()&&await s(R.LSP,async()=>{let{LspTool:a}=await import("./lsp-DW3UNQQ6.js");return new a(this)}),await o(),this.isCronEnabled()&&(await s(R.CRON_CREATE,async()=>{let{CronCreateTool:a}=await import("./cron-create-K35JKX3K.js");return new a(this)}),await s(R.CRON_LIST,async()=>{let{CronListTool:a}=await import("./cron-list-FCX6HCY7.js");return new a(this)}),await s(R.CRON_DELETE,async()=>{let{CronDeleteTool:a}=await import("./cron-delete-7B65R7JC.js");return new a(this)})),this.isAgentTeamEnabled()&&(await s(R.TEAM_CREATE,async()=>{let{TeamCreateTool:a}=await import("./team-create-LB3Q5Z6M.js");return new a(this)}),await s(R.TEAM_DELETE,async()=>{let{TeamDeleteTool:a}=await import("./team-delete-LWX4LMFZ.js");return new a(this)}),await s(R.TASK_CREATE,async()=>{let{TaskCreateTool:a}=await import("./task-create-TQI5N4YR.js");return new a(this)}),await s(R.TASK_UPDATE,async()=>{let{TaskUpdateTool:a}=await import("./task-update-PL2JDIF6.js");return new a(this)}),await s(R.TASK_LIST,async()=>{let{TaskListTool:a}=await import("./task-list-DQBF34BK.js");return new a(this)})),this.isWorkflowsEnabled()&&await s(R.WORKFLOW,async()=>{let{WorkflowTool:a}=await import("./workflow-EUTO2UEN.js");return new a(this)}),this.isComputerUseEnabled()){let{registerComputerUseTools:a}=await import("./computer-use-5HO7HQCB.js");await a(s,this)}if(await s(R.MONITOR,async()=>{let{MonitorTool:a}=await import("./monitor-4N4X3QGD.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 _8e="refs/notes/ai-attribution";function Lue(r,e){let t=JSON.stringify(r);return Buffer.byteLength(t,"utf-8")>30720?null:{command:"git",args:["notes",`--ref=${_8e}`,"add","-f","-m",t,e]}}var ide=Ve(Ka(),1);g();import*as Nue from"node:fs";var gd=class extends Error{constructor(t,n){super(t);this.errorType=n}name="StructuredToolError"};async function Fue(r,e,t,n={}){let s;try{s=await Nue.promises.stat(e)}catch(h){let d=h?.code;if(d==="ENOENT"){if(n.expectExisting){let y=`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:y,displayMessage:`file disappeared after last read; re-run ${R.READ_FILE} first.`}}return{ok:!0}}let f=`Could not stat ${e} to verify prior read (${d??"unknown error"}). Re-read with the ${R.READ_FILE} tool, then retry ${t} it.`,p=t==="editing"?"editing this file":"overwriting this file";return{ok:!1,type:"prior_read_verification_failed",rawMessage:f,displayMessage:`cannot verify prior read of ${e}; re-run ${R.READ_FILE} before ${p}.`}}if(s.isDirectory()){let h=t==="editing"?"edit":"overwrite",d=`${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:d,displayMessage:`path is a directory; cannot ${h} via this tool.`}}if(!s.isFile()){let h=t==="editing"?"edit":"overwrite",d=`${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:d,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",d=`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:d,displayMessage:`non-text payload; cannot ${h} via this tool.`}}let a=t==="editing"?"edit":"overwrite",l=t==="editing"?"editing this file":"overwriting this file",c=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)",u=`File ${e} has not been read in this session. Use the ${R.READ_FILE} tool first to load the current content ${c} before ${t} it.`;return{ok:!1,type:"edit_requires_prior_read",rawMessage:u,displayMessage:`${R.READ_FILE} required before ${l}.`}}g();var Bue=Ve(Ka(),1);var $ue=new Set(["+","?","|","(",")","{","}"]),b8e=new Set(["*","+","?"]);function jue(r){let e=r.trim(),t=e.match(/^\s*sed\s+/);if(!t)return null;let n;try{n=(0,Bue.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(v8e(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||S8e(l)||c.startsWith("~")||c.includes("$"))return null;let h=R8e(l);if(h===null)return null;let d={filePath:c,...h,extendedRegex:a};return C8e(d)?d:null}function v8e(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 S8e(r){return r.includes("`")||/\$(?:[A-Za-z_][A-Za-z0-9_]*|\{|\(|\d|[#?@$!*])/u.test(r)}function C8e(r){try{let e=Wue(r);return E8e(e)||T8e(e)||(new RegExp(e),k8e(r.replacement,x8e(e)))?!1:!A8e(e)}catch{return!1}}function E8e(r){return/\[\[:[A-Za-z]+:\]\]/u.test(r)}function T8e(r){return/\\[<>dDwWsS]/u.test(r)}function k8e(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 x8e(r){let e=0;for(let t=0;t<r.length;t++){let n=r[t];if(n==="\\"){t++;continue}if(n==="["){t=zue(r,t);continue}n==="("&&r[t+1]!=="?"&&e++}return e}function A8e(r){let e=[];for(let t=0;t<r.length;t++){let n=r[t];if(n==="\\"){t++;continue}if(n==="["){t=zue(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=Hue(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=Hue(r,t);s!==null&&(e.length>0&&(e[e.length-1].hasQuantifier=!0),t=s-1)}return!1}function zue(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 Hue(r,e){let t=r[e];if(t===void 0)return null;if(b8e.has(t))return e+1;if(t!=="{")return null;let n=e+1,s=!1;for(;Uue(r[n]);)s=!0,n++;if(!s)return null;if(r[n]===",")for(n++;Uue(r[n]);)n++;return r[n]==="}"?n+1:null}function Uue(r){return r!==void 0&&r>="0"&&r<="9"}function R8e(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"||!P8e(s)||M8e(n)?null:{pattern:t,replacement:n,flags:s}}function P8e(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 M8e(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 que(r,e){if(r.length===0)return"";let t=Wue(e),n=O8e(e.flags),s=e.flags.includes("g");try{let o=new RegExp(t,"g"),a=r.split(/(\n)/);return(r.endsWith(`
2176
2176
  `)?a.slice(0,-1):a).map((c,u)=>u%2===1?c:D8e(c,o,e.replacement,{occurrence:n,replaceAll:s})).join("")}catch(o){throw new Error(`sed pattern simulation failed: ${Q(o)}`)}}function Wue(r){let e=I8e(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];$ue.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+=$ue.has(o)?`\\${o}`:o}return t}function I8e(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 O8e(r){let e=r.match(/[1-9][0-9]*/);return e?Number(e[0]):null}function D8e(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 d=l.slice(1,-2).map(f=>f===void 0?"":String(f));return L8e(c,d,t)})}function L8e(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}var _e=F("SHELL");function N8e(r){let e=r.trimEnd();return!e.endsWith("&")||e.endsWith("&&")||e.endsWith("\\&")?r:e.slice(0,-1).trimEnd()}function Vue(r){return r.replace(/[\\"$`]/g,"\\$&")}function Kue(r){return r.replace(/'/g,"'\\''")}function sR(r){let e=null;for(let t of r)e=t;return e}function Yue(r){let e=!1,t=!1,n=0;for(;n<r.length;){let s=r[n];if(s==="\\"&&!e&&n+1<r.length){n+=2;continue}if(s==="'"&&!t){e=!e,n++;continue}if(s==='"'&&!e){t=!t,n++;continue}if(s==="#"&&!e&&!t){let o=n===0?"":r[n-1];if(o===""||/\s/.test(o))return n}n++}return-1}function Jue(r){return r?{start:r.index??0,end:(r.index??0)+r[0].length}:null}function Xue(r,e){let t=Jue(r),n=Jue(e);return!!(t&&n&&t.start>=n.start&&t.end<=n.end)}function Zue(r,e){return r&&e?Xue(e,r)?{match:r,isDouble:!0}:Xue(r,e)?{match:e,isDouble:!1}:(r.index??0)>(e.index??0)?{match:r,isDouble:!0}:{match:e,isDouble:!1}:r?{match:r,isDouble:!0}:{match:e,isDouble:!1}}function oR(r){let e;try{e=(0,ide.parse)(r,n=>"$"+n).filter(n=>typeof n=="string")}catch(n){return _e.warn(`tokeniseSegment: parse failed for "${r.slice(0,80)}": ${n instanceof Error?n.message:String(n)}`),null}let t=0;for(;t<e.length;){let n=ede(e[t]);if(n===null)break;if(Que.has(n))return null;t++}if(e[t]==="sudo"||e[t]==="command"||e[t]==="env"){let n=e[t];for(t++;t<e.length&&e[t].startsWith("-");){let s=e[t];t++;let o=n==="env"?H8e:n==="sudo"?U8e:null;if(o&&B8e(s,o))return null;(n==="sudo"&&F8e.has(s)||n==="env"&&$8e.has(s))&&t<e.length&&t++}if(n==="env")for(;t<e.length;){let s=ede(e[t]);if(s===null)break;if(Que.has(s))return null;t++}}return e.slice(t)}var F8e=new Set(["-u","-g","-h","-D","-r","-t","-C","--user","--group","--host","--chdir","--role","--type"]),$8e=new Set(["-u","--unset","-S","--split-string"]),H8e=new Set(["-C","--chdir"]),U8e=new Set(["-D","--chdir"]);function B8e(r,e){if(e.has(r))return!0;for(let t of e)if(t.startsWith("--")&&r.startsWith(t+"=")||t.length===2&&t.startsWith("-")&&r.startsWith(t)&&r.length>2)return!0;return!1}var Que=new Set(["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"]);function ede(r){let e=/^([A-Za-z_][A-Za-z0-9_]*)=/.exec(r);return e?e[1]:null}var j8e=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--exec-path","--config-env","--super-prefix","--list-cmds"]),z8e=new Set(["-C","--git-dir","--work-tree"]);function tde(r){let e=r.trim();return e==="."||e==="./"}function _B(r){let e=1,t=!1;for(;e<r.length;){let n=r[e];if(j8e.has(n)){let s=r[e+1]??"";n==="-C"?tde(s)||(t=!0):z8e.has(n)&&(t=!0),e+=2;continue}if(n.startsWith("--git-dir=")||n.startsWith("--work-tree=")){t=!0,e++;continue}if(n.length>2&&n.startsWith("-C")){let s=n.slice(2);tde(s)||(t=!0),e++;continue}if(n.startsWith("-")){e++;continue}return{subcommand:n,changesCwd:t}}return{subcommand:void 0,changesCwd:t}}function rde(r){let e=!1,t=!1,n=!1;for(let s of $i(r)){let o=oR(s);if(!o||o.length===0)continue;let a=o[0];if(a==="cd"||a==="pushd"){!e&&bB(o)&&(n=!0);continue}if(a==="popd"){e||(n=!0);continue}if(a==="git"){let{subcommand:l,changesCwd:c}=_B(o);l==="commit"?(e=!0,!n&&!c&&(t=!0)):c&&!e&&(n=!0)}}return{hasCommit:e,attributableInCwd:t}}var q8e=new Set(["--repo","-R","--hostname"]);function W8e(r){let e=1;for(;e<r.length;){let t=r[e];if(q8e.has(t)){e+=2;continue}if(t.startsWith("--repo=")||t.startsWith("--hostname=")||t.startsWith("-R=")){e++;continue}if(t.startsWith("-")){e++;continue}return r.slice(e)}return[]}function bB(r){let e=1;for(;e<r.length&&r[e].startsWith("-");)e++;let t=r[e];return!!(t===void 0||t.startsWith("/")||t.startsWith("~")||t.includes("$")||t===".."||t.startsWith("../")||t.startsWith("..\\")||t.includes("/..")||t.includes("\\..")||t==="-")}function G8e(r){let e=!1;for(let t of $i(r)){let n=oR(t);if(!n||n.length===0)continue;let s=n[0];if(s==="cd"||s==="pushd"){!e&&bB(n)&&(e=!0);continue}if(s==="popd"){e=!0;continue}if(s!=="git")continue;let{subcommand:o,changesCwd:a}=_B(n);if(o==="commit"&&!e&&!a)return n.includes("--amend")||n.some(l=>l.startsWith("--amend="));a&&!e&&(e=!0)}return!1}function V8e(r){let e=0,t=!1;for(let n of $i(r)){let s=r.indexOf(n,e);if(s<0){_e.warn(`findAttributableCommitSegment: cannot map segment "${n.slice(0,60)}" back to the original command (likely line-continuation / whitespace mismatch).`);continue}let o=s+n.length;e=o;let a=oR(n);if(!a||a.length===0)continue;let l=a[0];if(l==="cd"||l==="pushd"){!t&&bB(a)&&(t=!0);continue}if(l==="popd"){t=!0;continue}if(l==="git"){let{subcommand:c,changesCwd:u}=_B(a);if(c==="commit"&&!t&&!u)return{start:s,end:o};u&&!t&&(t=!0)}}return null}function K8e(r){let e=0;for(let t of $i(r)){let n=r.indexOf(t,e);if(n<0){_e.warn(`findGhPrCreateSegment: cannot map segment "${t.slice(0,60)}" back to the original command (likely line-continuation / whitespace mismatch).`);continue}let s=n+t.length;e=s;let o=oR(t);if(!o||o[0]!=="gh")continue;let a=W8e(o);if(a[0]==="pr"&&(a[1]==="create"||a[1]==="new"))return{start:n,end:s}}return null}var Y8e=40,J8e=1024;function X8e(r){let e=new Map,t=r.split(`
2177
2177
  `).filter(Boolean),n=s=>{let o=s.trim();if(o=o.replace(/\{[^}]*?=>\s*([^}]*)\}/g,"$1"),o.includes("=>")){let a=o.match(/^(.*?)\s=>\s(.*)$/);a&&(o=a[2].trim())}return o};for(let s of t){let o=s.match(/^([\d-]+)\t([\d-]+)\t(.+)$/);if(!o)continue;let a=n(o[3]);if(o[1]==="-"&&o[2]==="-"){e.set(a,J8e);continue}let l=parseInt(o[1],10),c=parseInt(o[2],10);Number.isNaN(l)||Number.isNaN(c)||e.set(a,(l+c)*Y8e)}return e}var gB=1e3,Z8e=12e4,Q8e=200,nde=1e4,e5e=1e3;function t5e(r){return Math.max(e5e,Math.floor(r/2))}function r5e(r){return`Note: this foreground command ran for ${Math.round(r/1e3)}s. Next time you run a similar long-running process (build watchers, dev servers, soak tests, polling loops), pass \`is_background: true\` so the agent isn't blocked while the command runs. (This is forward-looking guidance for FUTURE invocations \u2014 do NOT re-run the command that just completed; for stateful operations like deploys, migrations, or git push, that would cause double side effects.) The output of background runs stays inspectable via /tasks (text, any mode) or the on-disk output file; in interactive mode the Background tasks dialog also has a per-entry detail view + live updates.`}function f6t(r){return ode(r)?.description??null}function ode(r){let{command:e,comment:t}=lde(r),n=e.trim();if(!n.startsWith("sleep"))return null;let s=n.slice(5);if(!s||!/\s/.test(s[0]))return null;let o=0;for(;o<s.length&&/\s/.test(s[o]);)o++;let a=o;for(;o<s.length&&!/\s/.test(s[o])&&![";","&","|",`
2178
2178
  `].includes(s[o]);)o++;let l=s.slice(a,o),c=o5e(l);if(c===null||c<2)return null;let u=s.slice(o),h=a5e(u);if(h===null)return null;let d=h.rest.trim(),f=!d,p=d?`sleep ${l} followed by: ${d}`:`standalone sleep ${l}`,y=t?.trim();if(f&&y?.startsWith(ade)){let w=i5e(y);return w===null?{description:p,isStandalone:f,intentionalSleepRejection:"The intentional-sleep comment was recognized, but the reason is too short; explain why the delay is needed after `intentional-sleep:`."}:c>n5e?{description:p,isStandalone:f,intentionalSleepRejection:"The intentional-sleep comment was recognized, but foreground sleeps over 10 minutes are not allowed; use is_background: true or Monitor for longer waits."}:(_e.debug("intentional sleep allowed",{durationSeconds:c,reason:w}),null)}return{description:p,isStandalone:f}}var ade="intentional-sleep:",n5e=10*60,s5e=8;function i5e(r){let e=r.slice(ade.length).trim();return e.length>=s5e?e:null}function o5e(r){if(!r)return null;let e=0,t=!1,n=!1;for(;e<r.length;){let a=r[e];if(a>="0"&&a<="9"){t=!0,e++;continue}if(a==="."&&!n){n=!0,e++;continue}break}if(!t)return null;let s=Number.parseFloat(r.slice(0,e));if(!Number.isFinite(s))return null;switch(r.slice(e).toLowerCase()||"s"){case"ms":return s/1e3;case"s":return s;case"m":return s*60;case"h":return s*60*60;case"d":return s*60*60*24;default:return null}}function a5e(r){let e=0;for(;e<r.length&&r[e]!==`