@maincode-ai/matilda-code 0.19.7 → 0.19.8

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 (34) hide show
  1. package/chunks/{agent-JAZ2R5P5.js → agent-2NBSL6Q2.js} +1 -1
  2. package/chunks/{agent-headless-HUDZQCLT.js → agent-headless-AXEWDJRM.js} +1 -1
  3. package/chunks/{chunk-DF4ZZ3BH.js → chunk-HDVKP4RM.js} +1 -1
  4. package/chunks/{chunk-UOF5DCHP.js → chunk-HUPUKBVY.js} +4 -4
  5. package/chunks/{chunk-4ROBKRWY.js → chunk-ILO32IXN.js} +2 -2
  6. package/chunks/{chunk-MHGRKMUG.js → chunk-OJTERV74.js} +1 -1
  7. package/chunks/{chunk-4EZRS6DY.js → chunk-WIDV26MB.js} +1 -1
  8. package/chunks/{chunk-YCINFF22.js → chunk-WN7W7S2V.js} +1 -1
  9. package/chunks/{computer-use-BCNVOJO6.js → computer-use-7PIVVKPK.js} +1 -1
  10. package/chunks/{contextCommand-7XW5T2FM.js → contextCommand-SO4X2MS6.js} +1 -1
  11. package/chunks/{edit-O5534MIA.js → edit-B5KZGY7B.js} +1 -1
  12. package/chunks/{enter-worktree-NWECAVR5.js → enter-worktree-RRN3GMRW.js} +1 -1
  13. package/chunks/{enterPlanMode-Z5CC6RK4.js → enterPlanMode-ZPXWNPYM.js} +1 -1
  14. package/chunks/{exit-worktree-5QTROW2K.js → exit-worktree-HND5ZVDQ.js} +1 -1
  15. package/chunks/{exitPlanMode-VT42OYWF.js → exitPlanMode-K7HACJ6K.js} +1 -1
  16. package/chunks/{geminiContentGenerator-DROE6XUC.js → geminiContentGenerator-ZE6UPRAE.js} +1 -1
  17. package/chunks/{glob-FWADRNRL.js → glob-PXQT4CHI.js} +1 -1
  18. package/chunks/{grep-OFTEAZOC.js → grep-B2OXQK7Q.js} +1 -1
  19. package/chunks/{matildaAgentContentGenerator-J3PXQMRW.js → matildaAgentContentGenerator-Q43QK5GQ.js} +1 -1
  20. package/chunks/{matildaContentGenerator-6WVY252A.js → matildaContentGenerator-MTZC3PAG.js} +1 -1
  21. package/chunks/{monitor-W2IPT7L4.js → monitor-6AWWXDIL.js} +1 -1
  22. package/chunks/{notebook-edit-E2RFMINC.js → notebook-edit-7BJPP7ZB.js} +1 -1
  23. package/chunks/{openaiContentGenerator-PGCPCIUM.js → openaiContentGenerator-JX2JAR3V.js} +1 -1
  24. package/chunks/{ripGrep-CKRSCA2H.js → ripGrep-G3IY6ZWZ.js} +1 -1
  25. package/chunks/{scheduler-AQ72BFMX.js → scheduler-FFE43QWC.js} +1 -1
  26. package/chunks/{serve-VAU7AZ4D.js → serve-RXBWGIMV.js} +1 -1
  27. package/chunks/{shell-LMX4PBFS.js → shell-4HTE526K.js} +1 -1
  28. package/chunks/{src-3ZEKD73Z.js → src-F4LDZDLP.js} +1 -1
  29. package/chunks/{team-create-YCCOH5ZI.js → team-create-VWJKHFTR.js} +1 -1
  30. package/chunks/{web-search-LUARHW3X.js → web-search-FEZM3B3R.js} +1 -1
  31. package/chunks/{workflow-7JKMNIOX.js → workflow-GNYDTGHJ.js} +2 -2
  32. package/chunks/{write-file-QR6KKYVC.js → write-file-2PLDMI5M.js} +1 -1
  33. package/cli.js +6 -6
  34. package/package.json +2 -2
@@ -1,6 +1,6 @@
1
1
  // Force strict mode and setup for ESM
2
2
  "use strict";
3
- import{a as ke,b as s2,c as NR,d as i2,e as H,f as o2,g as Ye,h as vt,i as a2,j as l2,k as Zt,l as se,m as oe,n as fr,o as Lt,p as FR,q as $R,r as Et,s as zn,t as ue,u as Vt,v as c2,w as HR,x as u2,y as d2}from"./chunk-TZIDSCTF.js";import{d as m2,e as g2,g as S2,h as C2,i as E2,j as UR,m as T2}from"./chunk-FUNLOUYI.js";import{d as k2,k as BR,n as x2,p as A2}from"./chunk-R3H6IWFK.js";import{g as y2,h as w2,i as _2,m as Bp,n as b2,p as v2}from"./chunk-OMZ5SGMK.js";import{a as Bt}from"./chunk-KP6BLFQS.js";import{a as Ub,b as f2,d as WR,e as zb}from"./chunk-RBG4ERTN.js";import{a as R2,b as P2,c as jp}from"./chunk-TXMXCR7D.js";import{a as jR}from"./chunk-YULUB745.js";import{a as M2,b as I2,c as O2,d as zR,e as D2,f as qR}from"./chunk-LQWORCPO.js";import{a as r2,b as Hb,c as n2}from"./chunk-TISQNFB5.js";import{a as Di,b as DR,c as Td,s as LR}from"./chunk-XXZH7C44.js";import{a as jb,b as zp}from"./chunk-QEI3OETI.js";import{b as h2,g as Bb,j as Up,k as p2,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 Ro,d as Gj,f as Vj,i as ot,j as Kj,k as Yj,l as Jj,m as Xj,n as Zj,o as Qj,p as e2,q as t2}from"./chunk-4R2OFVPK.js";import{b as xd}from"./chunk-RNKDFE2S.js";import{a as Wj}from"./chunk-EMWHQSMS.js";import{c as IR}from"./chunk-GTR4V2PV.js";import{a as cB}from"./chunk-S4K76QPI.js";import{A as nn,B as OR,E as Ed,g as Nj,j as vc,k as Hp,l as PR,n as MR,q as $b}from"./chunk-4EZRS6DY.js";import{a as xo,c as RR}from"./chunk-4F4DA5UI.js";import{D as AR,E as Ij}from"./chunk-2XZIKUB6.js";import{h as Sd,k as Dj,m as Lj,q as $p}from"./chunk-XYA3SFGC.js";import{a as AB,b as Ia,c as Ws,d as RB,f as PB}from"./chunk-4J6DC24J.js";import{f as Fj,g as $j,j as Cd,k as Hj,l as Uj}from"./chunk-CLUEFPSU.js";import{a as Oj}from"./chunk-7VGUNT5L.js";import{$a as Ab,$b as dj,$c as vR,Ab as rj,Ac as wR,B as NB,Bb as nj,Bc as _R,Cb as sj,Cc as ko,Db as ij,Eb as oj,Ec as bR,F as _d,G as FB,Gb as cR,Ha as UB,Ic as Sj,Jb as aj,Mc as Cj,Ob as lj,Oc as Ej,Qc as vd,Rc as Tj,Sb as bd,Sc as kj,Tb as cj,Ub as uj,Va as BB,Vc as Db,Yb as Pb,Za as jB,_a as La,_b as uR,aa as $B,ab as zB,ac as yc,ad as bc,bb as qB,bc as dR,bd as xj,cb as rn,cd as Lb,d as vB,da as Da,dc as hj,ec as hR,ed as SR,f as To,fc as fj,fd as CR,g as xB,ga as Dp,gb as aR,gc as fR,gd as ER,h as jn,ha as xb,hb as WB,hc as pR,i as Oa,ib as GB,ic as mR,id as TR,jb as VB,k as MB,kb as lR,kd as Aj,l as IB,lb as KB,m as OB,mb as YB,mc as pj,nb as JB,nc as mj,ob as XB,oc as gj,od as Rj,p as mc,pb as ZB,pd as Pj,q as Op,qb as QB,qd as Mj,r as DB,rb as ej,rc as gR,rd as kR,s as LB,sb as tj,sc as Mb,t as gc,tc as Ib,uc as wj,ud as xR,vb as Rb,vc as _j,vd as Nb,wd as Fb,xc as yR,ya as oR,yc as Fp,za as HB,zc as bj}from"./chunk-CFBZKYFB.js";import{b as Oi,h as Ar,k as yj,l as wc,m as Rr,n as _c,o as Lp,s as Gs,t as Np,w as Ob}from"./chunk-UY2R3ZQ4.js";import{a as vj}from"./chunk-NDR7ZFUA.js";import{b as SB,c as Xue,d as Zue,e as CB,f as EB,g as zs,i as qs,j as TB,k as sR,o as kB,p as R,q as vn,r as Tb,s as kb}from"./chunk-5U3A6KMU.js";import{b as zj,c as qj}from"./chunk-LLQVLTPB.js";import{a as Bj,b as Ao,c as jj}from"./chunk-ESSYHTAZ.js";import{b as Ke,c as _s,e as Eb}from"./chunk-IOCF4XSR.js";import{A as fB,C as js,D as wd,F as pc,G as pB,J as tR,K as rR,L as fe,Q as wB,R as _B,T as bB,W as nR,Y as F,a as Rt,b as Sb,c as Q,d as Eo,p as uB,r as dB,s as tn,w as yd,z as hB}from"./chunk-QWBNNEV2.js";import{a as iR}from"./chunk-G7R2XEEF.js";import{g as Cb,h as mB,l as gB,n as yB}from"./chunk-FWDMPRKU.js";import{a as __matilda_dirname,b as g}from"./chunk-GZPNIYVZ.js";import{a as be,c as Yue,d as D,e as Jue,f as Ve}from"./chunk-OWGSC52X.js";var HW=D((vJe,$W)=>{"use strict";g();$W.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 GW=D((CJe,WW)=>{"use strict";g();var qW="(?:"+["\\|\\|","\\&\\&",";;","\\|\\&","\\<\\(","\\<\\<\\<",">>",">\\&","<\\&","[&;()|<>]"].join("|")+")",UW=new RegExp("^"+qW+"$"),BW="|&;()<> \\t",qme='"((\\\\"|[^"])*?)"',Wme="'((\\\\'|[^'])*?)'",Gme=/^#$/,jW="'",zW='"',u0="$",$c="",Vme=4294967296;for(d0=0;d0<4;d0++)$c+=(Vme*Math.random()).toString(16);var d0,Kme=new RegExp("^"+$c);function Yme(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 Jme(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+$c+JSON.stringify(n)+$c:e+n}function Xme(r,e,t){t||(t={});var n=t.escape||"\\",s="(\\"+n+`['"`+BW+`]|[^\\s'"`+BW+"])+",o=new RegExp(["("+qW+")","("+s+"|"+qme+"|"+Wme+")+"].join("|"),"g"),a=Yme(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(UW.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 Jme(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==jW?f+=m:m===n?(y+=1,m=u.charAt(y),m===zW||m===n||m===u0?f+=m:f+=n+m):m===u0?f+=w():f+=m;else if(m===zW||m===jW)h=m;else{if(UW.test(m))return{op:u};if(Gme.test(m)){l=!0;var _={comment:r.slice(c.index+y+1)};return f.length?[f,_]:[_]}else m===n?d=!0:m===u0?f+=w():f+=m}}return p?{op:"glob",pattern:f}:f}).reduce(function(c,u){return typeof u>"u"?c:c.concat(u)},[])}WW.exports=function(e,t,n){var s=Xme(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("("+$c+".*?"+$c+")","g"));return l.length===1?o.concat(l[0]):o.concat(l.filter(Boolean).map(function(c){return Kme.test(c)?JSON.parse(c.split($c)[1]):c}))},[])}});var Va=D(h0=>{"use strict";g();h0.quote=HW();h0.parse=GW()});var CG=D((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 U=0,K=1;;){var q=r[e++];if(U+=(q&127)*K,K*=128,!(q&128))break}return U}function o(){var U=s();return e+=U,UTF8ArrayToString(r,e-U,U)}function a(U,K){if(U)throw new Error(K)}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 B=o(),$=s();$&S&&f.tlsExports.add(B)}else if(A===v)for(var P=s();P--;){var O=o(),B=o(),$=s();($&E)==T&&f.weakImports.add(B)}else e+=k}}return f};function getValue(r,e="i8"){switch(e.endsWith("*")&&(e="*"),e){case"i1":return HEAP8[r];case"i8":return HEAP8[r];case"i16":return LE_HEAP_LOAD_I16((r>>1)*2);case"i32":return LE_HEAP_LOAD_I32((r>>2)*4);case"i64":abort("to do getValue(i64) use WASM_BIGINT");case"float":return LE_HEAP_LOAD_F32((r>>2)*4);case"double":return LE_HEAP_LOAD_F64((r>>3)*8);case"*":return LE_HEAP_LOAD_U32((r>>2)*4);default:abort(`invalid type for getValue: ${e}`)}}var newDSO=(r,e,t)=>{var n={refcount:1/0,name:r,exports:t,global:!0};return LDSO.loadedLibsByName[r]=n,e!=null&&(LDSO.loadedLibsByHandle[e]=n),n},LDSO={loadedLibsByName:{},loadedLibsByHandle:{},init(){newDSO("__main__",0,wasmImports)}},___heap_base=78112,zeroMemory=(r,e)=>(HEAPU8.fill(0,r,r+e),r),alignMemory=(r,e)=>Math.ceil(r/e)*e,getMemory=r=>{if(runtimeInitialized)return zeroMemory(_malloc(r),r);var e=___heap_base,t=e+alignMemory(r,16);return ___heap_base=t,GOT.__heap_base.value=t,e},isInternalSym=r=>["__cpp_exception","__c_longjmp","__wasm_apply_data_relocs","__dso_handle","__tls_size","__tls_align","__set_stack_limits","_emscripten_tls_init","__wasm_init_tls","__wasm_call_ctors","__start_em_asm","__stop_em_asm","__start_em_js","__stop_em_js"].includes(r)||r.startsWith("__em_js__"),uleb128Encode=(r,e)=>{r<128?e.push(r):e.push(r%128|128,r>>7)},sigToWasmTypes=r=>{for(var e={i:"i32",j:"i64",f:"f32",d:"f64",e:"externref",p:"i32"},t={parameters:[],results:r[0]=="v"?[]:[e[r[0]]]},n=1;n<r.length;++n)t.parameters.push(e[r[n]]);return t},generateFuncType=(r,e)=>{var t=r.slice(0,1),n=r.slice(1),s={i:127,p:127,j:126,f:125,d:124,e:111};e.push(96),uleb128Encode(n.length,e);for(var o=0;o<n.length;++o)e.push(s[n[o]]);t=="v"?e.push(0):e.push(1,s[t])},convertJsFunctionToWasm=(r,e)=>{if(typeof WebAssembly.Function=="function")return new WebAssembly.Function(sigToWasmTypes(e),r);var t=[1];generateFuncType(e,t);var n=[0,97,115,109,1,0,0,0,1];uleb128Encode(t.length,n),n.push(...t),n.push(2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0);var s=new WebAssembly.Module(new Uint8Array(n)),o=new WebAssembly.Instance(s,{e:{f:r}}),a=o.exports.f;return a},wasmTableMirror=[],wasmTable=new WebAssembly.Table({initial:28,element:"anyfunc"}),getWasmTableEntry=r=>{var e=wasmTableMirror[r];return e||(r>=wasmTableMirror.length&&(wasmTableMirror.length=r+1),wasmTableMirror[r]=e=wasmTable.get(r)),e},updateTableMap=(r,e)=>{if(functionsInTableMap)for(var t=r;t<r+e;t++){var n=getWasmTableEntry(t);n&&functionsInTableMap.set(n,t)}},functionsInTableMap,getFunctionAddress=r=>(functionsInTableMap||(functionsInTableMap=new WeakMap,updateTableMap(0,wasmTable.length)),functionsInTableMap.get(r)||0),freeTableIndexes=[],getEmptyTableSlot=()=>{if(freeTableIndexes.length)return freeTableIndexes.pop();try{wasmTable.grow(1)}catch(r){throw r instanceof RangeError?"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.":r}return wasmTable.length-1},setWasmTableEntry=(r,e)=>{wasmTable.set(r,e),wasmTableMirror[r]=wasmTable.get(r)},addFunction=(r,e)=>{var t=getFunctionAddress(r);if(t)return t;var n=getEmptyTableSlot();try{setWasmTableEntry(n,r)}catch(o){if(!(o instanceof TypeError))throw o;var s=convertJsFunctionToWasm(r,e);setWasmTableEntry(n,s)}return functionsInTableMap.set(r,n),n},updateGOT=(r,e)=>{for(var t in r)if(!isInternalSym(t)){var n=r[t];t.startsWith("orig$")&&(t=t.split("$")[1],e=!0),GOT[t]||=new WebAssembly.Global({value:"i32",mutable:!0}),(e||GOT[t].value==0)&&(typeof n=="function"?GOT[t].value=addFunction(n):typeof n=="number"?GOT[t].value=n:err(`unhandled export type for '${t}': ${typeof n}`))}},relocateExports=(r,e,t)=>{var n={};for(var s in r){var o=r[s];typeof o=="object"&&(o=o.value),typeof o=="number"&&(o+=e),n[s]=o}return updateGOT(n,t),n},isSymbolDefined=r=>{var e=wasmImports[r];return!(!e||e.stub)},dynCallLegacy=(r,e,t)=>{r=r.replace(/p/g,"i");var n=Module["dynCall_"+r];return n(e,...t)},dynCall=(r,e,t=[])=>{if(r.includes("j"))return dynCallLegacy(r,e,t);var n=getWasmTableEntry(e)(...t);return n},stackSave=()=>_emscripten_stack_get_current(),stackRestore=r=>__emscripten_stack_restore(r),createInvokeFunction=r=>(e,...t)=>{var n=stackSave();try{return dynCall(r,e,t)}catch(s){if(stackRestore(n),s!==s+0)throw s;_setThrew(1,0)}},resolveGlobalSymbol=(r,e=!1)=>{var t;return e&&"orig$"+r in wasmImports&&(r="orig$"+r),isSymbolDefined(r)?t=wasmImports[r]:r.startsWith("invoke_")&&(t=wasmImports[r]=createInvokeFunction(r.split("_")[1])),{sym:t,name:r}},UTF8ToString=(r,e)=>r?UTF8ArrayToString(HEAPU8,r,e):"",loadWebAssemblyModule=(binary,flags,libName,localScope,handle)=>{var metadata=getDylinkMetadata(binary);currentModuleWeakSymbols=metadata.weakImports;function loadModule(){var firstLoad=!handle||!HEAP8[handle+8];if(firstLoad){var memAlign=Math.pow(2,metadata.memoryAlign),memoryBase=metadata.memorySize?alignMemory(getMemory(metadata.memorySize+memAlign),memAlign):0,tableBase=metadata.tableSize?wasmTable.length:0;handle&&(HEAP8[handle+8]=1,LE_HEAP_STORE_U32((handle+12>>2)*4,memoryBase),LE_HEAP_STORE_I32((handle+16>>2)*4,metadata.memorySize),LE_HEAP_STORE_U32((handle+20>>2)*4,tableBase),LE_HEAP_STORE_I32((handle+24>>2)*4,metadata.tableSize))}else memoryBase=LE_HEAP_LOAD_U32((handle+12>>2)*4),tableBase=LE_HEAP_LOAD_U32((handle+20>>2)*4);var tableGrowthNeeded=tableBase+metadata.tableSize-wasmTable.length;tableGrowthNeeded>0&&wasmTable.grow(tableGrowthNeeded);var moduleExports;function resolveSymbol(r){var e=resolveGlobalSymbol(r).sym;return!e&&localScope&&(e=localScope[r]),e||(e=moduleExports[r]),e}var proxyHandler={get(r,e){switch(e){case"__memory_base":return memoryBase;case"__table_base":return tableBase}if(e in wasmImports&&!wasmImports[e].stub)return wasmImports[e];if(!(e in r)){var t;r[e]=(...n)=>(t||=resolveSymbol(e),t(...n))}return r[e]}},proxy=new Proxy({},proxyHandler),info={"GOT.mem":new Proxy({},GOTHandler),"GOT.func":new Proxy({},GOTHandler),env:proxy,wasi_snapshot_preview1:proxy};function postInstantiation(module,instance){updateTableMap(tableBase,metadata.tableSize),moduleExports=relocateExports(instance.exports,memoryBase),flags.allowUndefined||reportUndefinedSymbols();function addEmAsm(addr,body){for(var args=[],arity=0;arity<16&&body.indexOf("$"+arity)!=-1;arity++)args.push("$"+arity);args=args.join(",");var func=`(${args}) => { ${body} };`;ASM_CONSTS[start]=eval(func)}if("__start_em_asm"in moduleExports)for(var start=moduleExports.__start_em_asm,stop=moduleExports.__stop_em_asm;start<stop;){var jsString=UTF8ToString(start);addEmAsm(start,jsString),start=HEAPU8.indexOf(0,start)+1}function addEmJs(name,cSig,body){var jsArgs=[];if(cSig=cSig.slice(1,-1),cSig!="void"){cSig=cSig.split(",");for(var i in cSig){var jsArg=cSig[i].split(" ").pop();jsArgs.push(jsArg.replace("*",""))}}var func=`(${jsArgs}) => ${body};`;moduleExports[name]=eval(func)}for(var name in moduleExports)if(name.startsWith("__em_js__")){var start=moduleExports[name],jsString=UTF8ToString(start),parts=jsString.split("<::>");addEmJs(name.replace("__em_js__",""),parts[0],parts[1]),delete moduleExports[name]}var applyRelocs=moduleExports.__wasm_apply_data_relocs;applyRelocs&&(runtimeInitialized?applyRelocs():__RELOC_FUNCS__.push(applyRelocs));var init=moduleExports.__wasm_call_ctors;return init&&(runtimeInitialized?init():__ATINIT__.push(init)),moduleExports}if(flags.loadAsync){if(binary instanceof WebAssembly.Module){var instance=new WebAssembly.Instance(binary,info);return Promise.resolve(postInstantiation(binary,instance))}return WebAssembly.instantiate(binary,info).then(r=>postInstantiation(r.module,r.instance))}var module=binary instanceof WebAssembly.Module?binary:new WebAssembly.Module(binary),instance=new WebAssembly.Instance(module,info);return postInstantiation(module,instance)}return flags.loadAsync?metadata.neededDynlibs.reduce((r,e)=>r.then(()=>loadDynamicLibrary(e,flags,localScope)),Promise.resolve()).then(loadModule):(metadata.neededDynlibs.forEach(r=>loadDynamicLibrary(r,flags,localScope)),loadModule())},mergeLibSymbols=(r,e)=>{for(var[t,n]of Object.entries(r)){let s=a=>{isSymbolDefined(a)||(wasmImports[a]=n)};s(t);let o="__main_argc_argv";t=="main"&&s(o),t==o&&s("main"),t.startsWith("dynCall_")&&!Module.hasOwnProperty(t)&&(Module[t]=n)}},asyncLoad=(r,e,t,n)=>{var s=n?"":`al ${r}`;readAsync(r).then(o=>{e(new Uint8Array(o)),s&&removeRunDependency(s)},o=>{if(t)t();else throw`Loading data file "${r}" failed.`}),s&&addRunDependency(s)};function loadDynamicLibrary(r,e={global:!0,nodelete:!0},t,n){var s=LDSO.loadedLibsByName[r];if(s)return e.global?s.global||(s.global=!0,mergeLibSymbols(s.exports,r)):t&&Object.assign(t,s.exports),e.nodelete&&s.refcount!==1/0&&(s.refcount=1/0),s.refcount++,n&&(LDSO.loadedLibsByHandle[n]=s),e.loadAsync?Promise.resolve(!0):!0;s=newDSO(r,n,"loading"),s.refcount=e.nodelete?1/0:1,s.global=e.global;function o(){if(n){var c=LE_HEAP_LOAD_U32((n+28>>2)*4),u=LE_HEAP_LOAD_U32((n+32>>2)*4);if(c&&u){var 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 s2,c as NR,d as i2,e as H,f as o2,g as Ye,h as vt,i as a2,j as l2,k as Zt,l as se,m as oe,n as fr,o as Lt,p as FR,q as $R,r as Et,s as zn,t as ue,u as Vt,v as c2,w as HR,x as u2,y as d2}from"./chunk-TZIDSCTF.js";import{d as m2,e as g2,g as S2,h as C2,i as E2,j as UR,m as T2}from"./chunk-FUNLOUYI.js";import{d as k2,k as BR,n as x2,p as A2}from"./chunk-R3H6IWFK.js";import{g as y2,h as w2,i as _2,m as Bp,n as b2,p as v2}from"./chunk-OMZ5SGMK.js";import{a as Bt}from"./chunk-KP6BLFQS.js";import{a as Ub,b as f2,d as WR,e as zb}from"./chunk-RBG4ERTN.js";import{a as R2,b as P2,c as jp}from"./chunk-TXMXCR7D.js";import{a as jR}from"./chunk-YULUB745.js";import{a as M2,b as I2,c as O2,d as zR,e as D2,f as qR}from"./chunk-LQWORCPO.js";import{a as r2,b as Hb,c as n2}from"./chunk-TISQNFB5.js";import{a as Di,b as DR,c as Td,s as LR}from"./chunk-XXZH7C44.js";import{a as jb,b as zp}from"./chunk-QEI3OETI.js";import{b as h2,g as Bb,j as Up,k as p2,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 Ro,d as Gj,f as Vj,i as ot,j as Kj,k as Yj,l as Jj,m as Xj,n as Zj,o as Qj,p as e2,q as t2}from"./chunk-4R2OFVPK.js";import{b as xd}from"./chunk-RNKDFE2S.js";import{a as Wj}from"./chunk-EMWHQSMS.js";import{c as IR}from"./chunk-GTR4V2PV.js";import{a as cB}from"./chunk-S4K76QPI.js";import{A as nn,B as OR,E as Ed,g as Nj,j as vc,k as Hp,l as PR,n as MR,q as $b}from"./chunk-WIDV26MB.js";import{a as xo,c as RR}from"./chunk-4F4DA5UI.js";import{D as AR,E as Ij}from"./chunk-2XZIKUB6.js";import{h as Sd,k as Dj,m as Lj,q as $p}from"./chunk-XYA3SFGC.js";import{a as AB,b as Ia,c as Ws,d as RB,f as PB}from"./chunk-4J6DC24J.js";import{f as Fj,g as $j,j as Cd,k as Hj,l as Uj}from"./chunk-CLUEFPSU.js";import{a as Oj}from"./chunk-7VGUNT5L.js";import{$a as Ab,$b as dj,$c as vR,Ab as rj,Ac as wR,B as NB,Bb as nj,Bc as _R,Cb as sj,Cc as ko,Db as ij,Eb as oj,Ec as bR,F as _d,G as FB,Gb as cR,Ha as UB,Ic as Sj,Jb as aj,Mc as Cj,Ob as lj,Oc as Ej,Qc as vd,Rc as Tj,Sb as bd,Sc as kj,Tb as cj,Ub as uj,Va as BB,Vc as Db,Yb as Pb,Za as jB,_a as La,_b as uR,aa as $B,ab as zB,ac as yc,ad as bc,bb as qB,bc as dR,bd as xj,cb as rn,cd as Lb,d as vB,da as Da,dc as hj,ec as hR,ed as SR,f as To,fc as fj,fd as CR,g as xB,ga as Dp,gb as aR,gc as fR,gd as ER,h as jn,ha as xb,hb as WB,hc as pR,i as Oa,ib as GB,ic as mR,id as TR,jb as VB,k as MB,kb as lR,kd as Aj,l as IB,lb as KB,m as OB,mb as YB,mc as pj,nb as JB,nc as mj,ob as XB,oc as gj,od as Rj,p as mc,pb as ZB,pd as Pj,q as Op,qb as QB,qd as Mj,r as DB,rb as ej,rc as gR,rd as kR,s as LB,sb as tj,sc as Mb,t as gc,tc as Ib,uc as wj,ud as xR,vb as Rb,vc as _j,vd as Nb,wd as Fb,xc as yR,ya as oR,yc as Fp,za as HB,zc as bj}from"./chunk-CFBZKYFB.js";import{b as Oi,h as Ar,k as yj,l as wc,m as Rr,n as _c,o as Lp,s as Gs,t as Np,w as Ob}from"./chunk-UY2R3ZQ4.js";import{a as vj}from"./chunk-NDR7ZFUA.js";import{b as SB,c as Xue,d as Zue,e as CB,f as EB,g as zs,i as qs,j as TB,k as sR,o as kB,p as R,q as vn,r as Tb,s as kb}from"./chunk-5U3A6KMU.js";import{b as zj,c as qj}from"./chunk-LLQVLTPB.js";import{a as Bj,b as Ao,c as jj}from"./chunk-ESSYHTAZ.js";import{b as Ke,c as _s,e as Eb}from"./chunk-IOCF4XSR.js";import{A as fB,C as js,D as wd,F as pc,G as pB,J as tR,K as rR,L as fe,Q as wB,R as _B,T as bB,W as nR,Y as F,a as Rt,b as Sb,c as Q,d as Eo,p as uB,r as dB,s as tn,w as yd,z as hB}from"./chunk-QWBNNEV2.js";import{a as iR}from"./chunk-G7R2XEEF.js";import{g as Cb,h as mB,l as gB,n as yB}from"./chunk-FWDMPRKU.js";import{a as __matilda_dirname,b as g}from"./chunk-GZPNIYVZ.js";import{a as be,c as Yue,d as D,e as Jue,f as Ve}from"./chunk-OWGSC52X.js";var HW=D((vJe,$W)=>{"use strict";g();$W.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 GW=D((CJe,WW)=>{"use strict";g();var qW="(?:"+["\\|\\|","\\&\\&",";;","\\|\\&","\\<\\(","\\<\\<\\<",">>",">\\&","<\\&","[&;()|<>]"].join("|")+")",UW=new RegExp("^"+qW+"$"),BW="|&;()<> \\t",qme='"((\\\\"|[^"])*?)"',Wme="'((\\\\'|[^'])*?)'",Gme=/^#$/,jW="'",zW='"',u0="$",$c="",Vme=4294967296;for(d0=0;d0<4;d0++)$c+=(Vme*Math.random()).toString(16);var d0,Kme=new RegExp("^"+$c);function Yme(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 Jme(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+$c+JSON.stringify(n)+$c:e+n}function Xme(r,e,t){t||(t={});var n=t.escape||"\\",s="(\\"+n+`['"`+BW+`]|[^\\s'"`+BW+"])+",o=new RegExp(["("+qW+")","("+s+"|"+qme+"|"+Wme+")+"].join("|"),"g"),a=Yme(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(UW.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 Jme(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==jW?f+=m:m===n?(y+=1,m=u.charAt(y),m===zW||m===n||m===u0?f+=m:f+=n+m):m===u0?f+=w():f+=m;else if(m===zW||m===jW)h=m;else{if(UW.test(m))return{op:u};if(Gme.test(m)){l=!0;var _={comment:r.slice(c.index+y+1)};return f.length?[f,_]:[_]}else m===n?d=!0:m===u0?f+=w():f+=m}}return p?{op:"glob",pattern:f}:f}).reduce(function(c,u){return typeof u>"u"?c:c.concat(u)},[])}WW.exports=function(e,t,n){var s=Xme(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("("+$c+".*?"+$c+")","g"));return l.length===1?o.concat(l[0]):o.concat(l.filter(Boolean).map(function(c){return Kme.test(c)?JSON.parse(c.split($c)[1]):c}))},[])}});var Va=D(h0=>{"use strict";g();h0.quote=HW();h0.parse=GW()});var CG=D((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 U=0,K=1;;){var q=r[e++];if(U+=(q&127)*K,K*=128,!(q&128))break}return U}function o(){var U=s();return e+=U,UTF8ArrayToString(r,e-U,U)}function a(U,K){if(U)throw new Error(K)}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 B=o(),$=s();$&S&&f.tlsExports.add(B)}else if(A===v)for(var P=s();P--;){var O=o(),B=o(),$=s();($&E)==T&&f.weakImports.add(B)}else e+=k}}return f};function getValue(r,e="i8"){switch(e.endsWith("*")&&(e="*"),e){case"i1":return HEAP8[r];case"i8":return HEAP8[r];case"i16":return LE_HEAP_LOAD_I16((r>>1)*2);case"i32":return LE_HEAP_LOAD_I32((r>>2)*4);case"i64":abort("to do getValue(i64) use WASM_BIGINT");case"float":return LE_HEAP_LOAD_F32((r>>2)*4);case"double":return LE_HEAP_LOAD_F64((r>>3)*8);case"*":return LE_HEAP_LOAD_U32((r>>2)*4);default:abort(`invalid type for getValue: ${e}`)}}var newDSO=(r,e,t)=>{var n={refcount:1/0,name:r,exports:t,global:!0};return LDSO.loadedLibsByName[r]=n,e!=null&&(LDSO.loadedLibsByHandle[e]=n),n},LDSO={loadedLibsByName:{},loadedLibsByHandle:{},init(){newDSO("__main__",0,wasmImports)}},___heap_base=78112,zeroMemory=(r,e)=>(HEAPU8.fill(0,r,r+e),r),alignMemory=(r,e)=>Math.ceil(r/e)*e,getMemory=r=>{if(runtimeInitialized)return zeroMemory(_malloc(r),r);var e=___heap_base,t=e+alignMemory(r,16);return ___heap_base=t,GOT.__heap_base.value=t,e},isInternalSym=r=>["__cpp_exception","__c_longjmp","__wasm_apply_data_relocs","__dso_handle","__tls_size","__tls_align","__set_stack_limits","_emscripten_tls_init","__wasm_init_tls","__wasm_call_ctors","__start_em_asm","__stop_em_asm","__start_em_js","__stop_em_js"].includes(r)||r.startsWith("__em_js__"),uleb128Encode=(r,e)=>{r<128?e.push(r):e.push(r%128|128,r>>7)},sigToWasmTypes=r=>{for(var e={i:"i32",j:"i64",f:"f32",d:"f64",e:"externref",p:"i32"},t={parameters:[],results:r[0]=="v"?[]:[e[r[0]]]},n=1;n<r.length;++n)t.parameters.push(e[r[n]]);return t},generateFuncType=(r,e)=>{var t=r.slice(0,1),n=r.slice(1),s={i:127,p:127,j:126,f:125,d:124,e:111};e.push(96),uleb128Encode(n.length,e);for(var o=0;o<n.length;++o)e.push(s[n[o]]);t=="v"?e.push(0):e.push(1,s[t])},convertJsFunctionToWasm=(r,e)=>{if(typeof WebAssembly.Function=="function")return new WebAssembly.Function(sigToWasmTypes(e),r);var t=[1];generateFuncType(e,t);var n=[0,97,115,109,1,0,0,0,1];uleb128Encode(t.length,n),n.push(...t),n.push(2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0);var s=new WebAssembly.Module(new Uint8Array(n)),o=new WebAssembly.Instance(s,{e:{f:r}}),a=o.exports.f;return a},wasmTableMirror=[],wasmTable=new WebAssembly.Table({initial:28,element:"anyfunc"}),getWasmTableEntry=r=>{var e=wasmTableMirror[r];return e||(r>=wasmTableMirror.length&&(wasmTableMirror.length=r+1),wasmTableMirror[r]=e=wasmTable.get(r)),e},updateTableMap=(r,e)=>{if(functionsInTableMap)for(var t=r;t<r+e;t++){var n=getWasmTableEntry(t);n&&functionsInTableMap.set(n,t)}},functionsInTableMap,getFunctionAddress=r=>(functionsInTableMap||(functionsInTableMap=new WeakMap,updateTableMap(0,wasmTable.length)),functionsInTableMap.get(r)||0),freeTableIndexes=[],getEmptyTableSlot=()=>{if(freeTableIndexes.length)return freeTableIndexes.pop();try{wasmTable.grow(1)}catch(r){throw r instanceof RangeError?"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.":r}return wasmTable.length-1},setWasmTableEntry=(r,e)=>{wasmTable.set(r,e),wasmTableMirror[r]=wasmTable.get(r)},addFunction=(r,e)=>{var t=getFunctionAddress(r);if(t)return t;var n=getEmptyTableSlot();try{setWasmTableEntry(n,r)}catch(o){if(!(o instanceof TypeError))throw o;var s=convertJsFunctionToWasm(r,e);setWasmTableEntry(n,s)}return functionsInTableMap.set(r,n),n},updateGOT=(r,e)=>{for(var t in r)if(!isInternalSym(t)){var n=r[t];t.startsWith("orig$")&&(t=t.split("$")[1],e=!0),GOT[t]||=new WebAssembly.Global({value:"i32",mutable:!0}),(e||GOT[t].value==0)&&(typeof n=="function"?GOT[t].value=addFunction(n):typeof n=="number"?GOT[t].value=n:err(`unhandled export type for '${t}': ${typeof n}`))}},relocateExports=(r,e,t)=>{var n={};for(var s in r){var o=r[s];typeof o=="object"&&(o=o.value),typeof o=="number"&&(o+=e),n[s]=o}return updateGOT(n,t),n},isSymbolDefined=r=>{var e=wasmImports[r];return!(!e||e.stub)},dynCallLegacy=(r,e,t)=>{r=r.replace(/p/g,"i");var n=Module["dynCall_"+r];return n(e,...t)},dynCall=(r,e,t=[])=>{if(r.includes("j"))return dynCallLegacy(r,e,t);var n=getWasmTableEntry(e)(...t);return n},stackSave=()=>_emscripten_stack_get_current(),stackRestore=r=>__emscripten_stack_restore(r),createInvokeFunction=r=>(e,...t)=>{var n=stackSave();try{return dynCall(r,e,t)}catch(s){if(stackRestore(n),s!==s+0)throw s;_setThrew(1,0)}},resolveGlobalSymbol=(r,e=!1)=>{var t;return e&&"orig$"+r in wasmImports&&(r="orig$"+r),isSymbolDefined(r)?t=wasmImports[r]:r.startsWith("invoke_")&&(t=wasmImports[r]=createInvokeFunction(r.split("_")[1])),{sym:t,name:r}},UTF8ToString=(r,e)=>r?UTF8ArrayToString(HEAPU8,r,e):"",loadWebAssemblyModule=(binary,flags,libName,localScope,handle)=>{var metadata=getDylinkMetadata(binary);currentModuleWeakSymbols=metadata.weakImports;function loadModule(){var firstLoad=!handle||!HEAP8[handle+8];if(firstLoad){var memAlign=Math.pow(2,metadata.memoryAlign),memoryBase=metadata.memorySize?alignMemory(getMemory(metadata.memorySize+memAlign),memAlign):0,tableBase=metadata.tableSize?wasmTable.length:0;handle&&(HEAP8[handle+8]=1,LE_HEAP_STORE_U32((handle+12>>2)*4,memoryBase),LE_HEAP_STORE_I32((handle+16>>2)*4,metadata.memorySize),LE_HEAP_STORE_U32((handle+20>>2)*4,tableBase),LE_HEAP_STORE_I32((handle+24>>2)*4,metadata.tableSize))}else memoryBase=LE_HEAP_LOAD_U32((handle+12>>2)*4),tableBase=LE_HEAP_LOAD_U32((handle+20>>2)*4);var tableGrowthNeeded=tableBase+metadata.tableSize-wasmTable.length;tableGrowthNeeded>0&&wasmTable.grow(tableGrowthNeeded);var moduleExports;function resolveSymbol(r){var e=resolveGlobalSymbol(r).sym;return!e&&localScope&&(e=localScope[r]),e||(e=moduleExports[r]),e}var proxyHandler={get(r,e){switch(e){case"__memory_base":return memoryBase;case"__table_base":return tableBase}if(e in wasmImports&&!wasmImports[e].stub)return wasmImports[e];if(!(e in r)){var t;r[e]=(...n)=>(t||=resolveSymbol(e),t(...n))}return r[e]}},proxy=new Proxy({},proxyHandler),info={"GOT.mem":new Proxy({},GOTHandler),"GOT.func":new Proxy({},GOTHandler),env:proxy,wasi_snapshot_preview1:proxy};function postInstantiation(module,instance){updateTableMap(tableBase,metadata.tableSize),moduleExports=relocateExports(instance.exports,memoryBase),flags.allowUndefined||reportUndefinedSymbols();function addEmAsm(addr,body){for(var args=[],arity=0;arity<16&&body.indexOf("$"+arity)!=-1;arity++)args.push("$"+arity);args=args.join(",");var func=`(${args}) => { ${body} };`;ASM_CONSTS[start]=eval(func)}if("__start_em_asm"in moduleExports)for(var start=moduleExports.__start_em_asm,stop=moduleExports.__stop_em_asm;start<stop;){var jsString=UTF8ToString(start);addEmAsm(start,jsString),start=HEAPU8.indexOf(0,start)+1}function addEmJs(name,cSig,body){var jsArgs=[];if(cSig=cSig.slice(1,-1),cSig!="void"){cSig=cSig.split(",");for(var i in cSig){var jsArg=cSig[i].split(" ").pop();jsArgs.push(jsArg.replace("*",""))}}var func=`(${jsArgs}) => ${body};`;moduleExports[name]=eval(func)}for(var name in moduleExports)if(name.startsWith("__em_js__")){var start=moduleExports[name],jsString=UTF8ToString(start),parts=jsString.split("<::>");addEmJs(name.replace("__em_js__",""),parts[0],parts[1]),delete moduleExports[name]}var applyRelocs=moduleExports.__wasm_apply_data_relocs;applyRelocs&&(runtimeInitialized?applyRelocs():__RELOC_FUNCS__.push(applyRelocs));var init=moduleExports.__wasm_call_ctors;return init&&(runtimeInitialized?init():__ATINIT__.push(init)),moduleExports}if(flags.loadAsync){if(binary instanceof WebAssembly.Module){var instance=new WebAssembly.Instance(binary,info);return Promise.resolve(postInstantiation(binary,instance))}return WebAssembly.instantiate(binary,info).then(r=>postInstantiation(r.module,r.instance))}var module=binary instanceof WebAssembly.Module?binary:new WebAssembly.Module(binary),instance=new WebAssembly.Instance(module,info);return postInstantiation(module,instance)}return flags.loadAsync?metadata.neededDynlibs.reduce((r,e)=>r.then(()=>loadDynamicLibrary(e,flags,localScope)),Promise.resolve()).then(loadModule):(metadata.neededDynlibs.forEach(r=>loadDynamicLibrary(r,flags,localScope)),loadModule())},mergeLibSymbols=(r,e)=>{for(var[t,n]of Object.entries(r)){let s=a=>{isSymbolDefined(a)||(wasmImports[a]=n)};s(t);let o="__main_argc_argv";t=="main"&&s(o),t==o&&s("main"),t.startsWith("dynCall_")&&!Module.hasOwnProperty(t)&&(Module[t]=n)}},asyncLoad=(r,e,t,n)=>{var s=n?"":`al ${r}`;readAsync(r).then(o=>{e(new Uint8Array(o)),s&&removeRunDependency(s)},o=>{if(t)t();else throw`Loading data file "${r}" failed.`}),s&&addRunDependency(s)};function loadDynamicLibrary(r,e={global:!0,nodelete:!0},t,n){var s=LDSO.loadedLibsByName[r];if(s)return e.global?s.global||(s.global=!0,mergeLibSymbols(s.exports,r)):t&&Object.assign(t,s.exports),e.nodelete&&s.refcount!==1/0&&(s.refcount=1/0),s.refcount++,n&&(LDSO.loadedLibsByHandle[n]=s),e.loadAsync?Promise.resolve(!0):!0;s=newDSO(r,n,"loading"),s.refcount=e.nodelete?1/0:1,s.global=e.global;function o(){if(n){var c=LE_HEAP_LOAD_U32((n+28>>2)*4),u=LE_HEAP_LOAD_U32((n+32>>2)*4);if(c&&u){var 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,B;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 K=b[1].name,q=b[2].name;y[w].push(W=>{let z=[],G=[];for(let I of W)I.name===K&&z.push(I.node),I.name===q&&G.push(I.node);let x=(I,L,N)=>N?I.text===L.text:I.text!==L.text;return P?z.every(I=>G.some(L=>x(I,L,k))):z.some(I=>G.some(L=>x(I,L,k)))})}else{B=b[1].name;let K=b[2].value,q=z=>z.text===K,W=z=>z.text!==K;y[w].push(z=>{let G=[];for(let I of z)I.name===B&&G.push(I.node);let x=k?q:W;return P?G.every(x):G.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}.`);B=b[1].name;let $=new RegExp(b[2].value);P=!A.startsWith("any-"),y[w].push(K=>{let q=[];for(let z of K)z.name===B&&q.push(z.node.text);let W=(z,G)=>G?$.test(z):!$.test(z);return q.length===0?!k:P?q.every(z=>W(z,k)):q.some(z=>W(z,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(K=>K.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(K=>K.type!=="string"))throw new Error(`Arguments to \`#${A}\` predicate must be a strings.".`);let O=A==="is?"?d:f;O[w]||(O[w]={}),O[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 K=2;K<b.length;K++)if(b[K].type!=="string")throw new Error(`Arguments to \`#${A}\` predicate must be a strings.".`);B=b[1].name;let U=b.slice(2).map(K=>K.value);y[w].push(K=>{let q=[];for(let W of K)W.name===B&&q.push(W.node.text);return q.length===0?!k:q.every(W=>U.includes(W))===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:
@@ -278,7 +278,7 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
278
278
  `}function dde(r,e,t,n,s,o,a){var l;if(typeof a=="function"&&(a={callback:a}),(l=a)!==null&&l!==void 0&&l.callback){var u=a,h=u.callback;Sc(r,e,t,n,s,o,Vb(Vb({},a),{},{callback:function(f){f?h(QR(f)):h()}}))}else{var c=Sc(r,e,t,n,s,o,a);return c?QR(c):void 0}}function Pd(r,e,t,n,s,o){return dde(r,r,e,t,n,s,o)}function hde(r){var e=r.endsWith(`
279
279
  `),t=r.split(`
280
280
  `).map(function(n){return n+`
281
- `});return e?t.pop():t.push(t.pop().slice(0,-1)),t}g();var YA=Ve(cB(),1);import*as mt from"node:fs";import*as mue from"node:fs/promises";import*as bn from"node:path";import hr from"node:process";g();import*as Tc from"node:fs/promises";import*as Vp from"node:path";g();var eP=5,B2=(a=>(a.INITIALIZING="initializing",a.RUNNING="running",a.IDLE="idle",a.COMPLETED="completed",a.CANCELLED="cancelled",a.FAILED="failed",a))(B2||{});function Cc(r){return r.replace(/[/\\:*?"<>|]/g,"--")}g();var Ec=(a=>(a.ERROR="ERROR",a.TIMEOUT="TIMEOUT",a.GOAL="GOAL",a.MAX_TURNS="MAX_TURNS",a.CANCELLED="CANCELLED",a.SHUTDOWN="SHUTDOWN",a))(Ec||{}),Md=(a=>(a.INITIALIZING="initializing",a.RUNNING="running",a.IDLE="idle",a.COMPLETED="completed",a.FAILED="failed",a.CANCELLED="cancelled",a))(Md||{}),jt=r=>r==="completed"||r==="failed"||r==="cancelled",Gp=r=>r==="idle"||r==="completed",Xb=r=>r==="idle"||jt(r);var j2=F("ARENA_AGENT_CLIENT"),fde="agents",pde="control",Zb=class r{constructor(e,t){this.agentId=e;let n=Cc(e);this.agentsDir=Vp.join(t,fde),this.controlDir=Vp.join(t,pde),this.statusFilePath=Vp.join(this.agentsDir,`${n}.json`),this.controlFilePath=Vp.join(this.controlDir,`${n}.json`),this.startTimeMs=Date.now()}agentsDir;controlDir;statusFilePath;controlFilePath;startTimeMs;initialized=!1;static create(){let e=process.env.ARENA_AGENT_ID,t=process.env.ARENA_SESSION_ID,n=process.env.ARENA_SESSION_DIR;return!e||!t||!n?null:new r(e,n)}async init(){await Tc.mkdir(this.agentsDir,{recursive:!0}),await Tc.mkdir(this.controlDir,{recursive:!0}),this.initialized=!0,j2.info(`ArenaAgentClient initialized for agent ${this.agentId} at ${this.agentsDir}`)}async updateStatus(e){await this.ensureInitialized();let t=this.getStatsFromTelemetry(),n={agentId:this.agentId,status:"running",updatedAt:Date.now(),rounds:t.rounds,currentActivity:e,stats:t,finalSummary:null,error:null};await _s(this.statusFilePath,n)}async checkControlSignal(){await this.ensureInitialized();try{let e=await Tc.readFile(this.controlFilePath,"utf-8"),t=JSON.parse(e);return await Tc.unlink(this.controlFilePath),t}catch(e){if(Rt(e)&&e.code==="ENOENT")return null;if(Rt(e)&&e.code==="EACCES")throw e;return j2.error("Error reading control signal:",e),null}}async reportCompleted(e){await this.ensureInitialized();let t=this.getStatsFromTelemetry(),n={agentId:this.agentId,status:"completed",updatedAt:Date.now(),rounds:t.rounds,stats:t,finalSummary:e??null,error:null};await _s(this.statusFilePath,n)}async reportError(e){await this.ensureInitialized();let t=this.getStatsFromTelemetry(),n={agentId:this.agentId,status:"failed",updatedAt:Date.now(),rounds:t.rounds,stats:t,finalSummary:null,error:e};await _s(this.statusFilePath,n)}async reportCancelled(){await this.ensureInitialized();let e=this.getStatsFromTelemetry(),t={agentId:this.agentId,status:"cancelled",updatedAt:Date.now(),rounds:e.rounds,stats:e,finalSummary:null,error:null};await _s(this.statusFilePath,t)}getStatsFromTelemetry(){let e=jn.getMetrics(),t=0,n=0,s=0,o=0;for(let a of Object.values(e.models))t+=a.api.totalRequests,n+=a.tokens.total,s+=a.tokens.prompt,o+=a.tokens.candidates;return{rounds:t,totalTokens:n,inputTokens:s,outputTokens:o,durationMs:Date.now()-this.startTimeMs,toolCalls:e.tools.totalCalls,successfulToolCalls:e.tools.totalSuccess,failedToolCalls:e.tools.totalFail}}async ensureInitialized(){this.initialized||await this.init()}};g();g();function rP(r,e,t){let n=r.getContentGeneratorConfig(),s=t.authType===n.authType,o=r.getModelsConfig(),a=e?o.getResolvedModel(t.authType,e):void 0,l={...n,model:e??n.model,authType:t.authType};if(!s)for(let c of vc)l[c]=void 0;return a?(mde(l,a,n,t),l):(l.apiKey=tP(t.apiKey,s?n.apiKey:void 0,t.authType,"apiKey"),l.baseUrl=t.baseUrl??tP(void 0,s?n.baseUrl:void 0,t.authType,"baseUrl"),l.apiKeyEnvKey=s?n.apiKeyEnvKey:void 0,l)}async function Id(r,e,t,n){let s=rP(r,t,n);return{contentGenerator:await Ed(s,e),contentGeneratorConfig:s}}function mde(r,e,t,n){let s=n.authType===t.authType;r.model=e.id,r.authType=e.authType,r.baseUrl=n.baseUrl??e.baseUrl??(s?t.baseUrl:void 0),e.envKey?(r.apiKey=n.apiKey??process.env[e.envKey]??(s?t.apiKey:void 0),r.apiKeyEnvKey=e.envKey):(r.apiKey=tP(n.apiKey,s?t.apiKey:void 0,n.authType,"apiKey"),r.apiKeyEnvKey=s?t.apiKeyEnvKey:void 0);for(let o of vc){let a=e.generationConfig[o];a!==void 0&&(r[o]=a)}}function tP(r,e,t,n){if(r)return r;if(e)return e;let s=Hp[t];if(s)for(let o of s[n]){let a=process.env[o];if(a)return a}}g();var gde=new Set(Object.values(nn));function Ks(r,e={}){return q2(z2(r),e)}function Od(r){return{currentModel:r.getModel?.(),currentAuthType:r.getContentGeneratorConfig?.()?.authType,fastModel:r.getFastModel?.(),getAvailableModels:e=>r.getAllConfiguredModels?.(e)??[]}}function z2(r){let e=r?.trim();if(!e||e==="inherit")return{kind:"inherit"};if(e==="fast")return{kind:"fast"};let t=e.indexOf(":");if(t===-1)return{kind:"model",modelId:e};let n=e.slice(0,t).trim(),s=e.slice(t+1).trim();if(!gde.has(n))return{kind:"model",modelId:e};if(!s)throw new Error("Model selector must include a model ID after the authType");return{kind:"model",authType:n,modelId:s}}function yde(r,e){return e.currentAuthType&&e.getAvailableModels&&e.getAvailableModels([e.currentAuthType]).some(s=>s.id===r)?e.currentAuthType:(e.getAvailableModels?e.getAvailableModels().find(n=>n.id===r):void 0)?.authType??e.currentAuthType}function q2(r,e){if(r.kind==="model"){let n=r.authType??yde(r.modelId,e);return{...n?{authType:n}:{},modelId:r.modelId}}if(r.kind==="inherit")return e.currentModel?{...e.currentAuthType?{authType:e.currentAuthType}:{},modelId:e.currentModel}:void 0;if(!e.fastModel)return;let t=z2(e.fastModel);if(t.kind!=="fast")return q2(t,{...e,fastModel:void 0})}g();g();function Po(r){return typeof r=="object"&&r!==null&&"error"in r&&typeof r.error=="object"&&"message"in r.error}function Dd(r){return typeof r=="object"&&r!==null&&"message"in r&&typeof r.message=="string"}function o5e(r){let e=t=>t.includes("Quota exceeded for quota metric 'Gemini")&&t.includes("Pro Requests'");if(typeof r=="string")return e(r);if(Dd(r))return e(r.message);if(Po(r))return e(r.error.message);if(r&&typeof r=="object"&&"response"in r){let t=r;if(t.response&&t.response.data){if(typeof t.response.data=="string")return e(t.response.data);if(typeof t.response.data=="object"&&t.response.data!==null&&"error"in t.response.data){let n=t.response.data;return e(n.error?.message||"")}}}return!1}function a5e(r){return typeof r=="string"?r.includes("Quota exceeded for quota metric"):Dd(r)?r.message.includes("Quota exceeded for quota metric"):Po(r)?r.error.message.includes("Quota exceeded for quota metric"):!1}function Qb(r){if(typeof r!="object"||r===null)return!1;let{status:e,code:t,message:n}=r;return e===429&&t==="insufficient_quota"&&typeof n=="string"&&n.toLowerCase().includes("free allocated quota exceeded")}g();g();function Na(r){let e=Math.max(1,r.attempt),t=Math.min(r.maxDelayMs,2147483647),n=Math.min(e-1,31),s=Math.min(r.initialDelayMs*Math.pow(2,n),t),a=(r.retryAfterMode??"ignore")==="ignore"?null:ev(r.error);if(a!==null&&a>0){let h=Math.min(r.retryAfterMaxDelayMs??r.maxDelayMs,2147483647),d=Math.min(a,h);return Math.max(s,d)}let l=r.jitterRatio??0;if(l<=0)return s;let c=r.random??Math.random,u=s*l*(c()*2-1);return Math.min(Math.max(0,s+u),t)}function ev(r){let e=W2(r,"retry-after")??wde(r,"retry-after");if(e===null)return null;let t=e.trim();if(/^\d+(\.\d+)?$/.test(t)){let o=Number(t);if(Number.isFinite(o)&&o>=0)return Math.min(o*1e3,2147483647)}let n=Date.parse(t);if(!Number.isFinite(n))return null;let s=n-Date.now();return s>0?Math.min(s,2147483647):0}function W2(r,e){if(!_de(r))return null;let{headers:t}=r;if(typeof t.get=="function"){let s=t.get(e);return typeof s=="string"?s:null}if(typeof t!="object"||t===null)return null;let n=e.toLowerCase();for(let[s,o]of Object.entries(t))if(s.toLowerCase()===n)return typeof o=="string"?o:null;return null}function wde(r,e){return bde(r)?W2(r.response,e):null}function _de(r){return typeof r=="object"&&r!==null&&"headers"in r&&r.headers!=null}function bde(r){return typeof r=="object"&&r!==null&&"response"in r&&typeof r.response=="object"&&r.response!==null&&"headers"in r.response&&r.response.headers!=null}var vde=new Set([429,503,1302,1305]);function kc(r,e){let t=Sde(r);return t===null?!1:!!(vde.has(t)||e&&e.includes(t))}function tv(r){let e=Eo(r),t=Cde(r),n=V2(r),s=n?.includes("event:error")||n?.includes("HTTP_STATUS/")?"sse":e!==void 0?"http":"unknown";return{...e!==void 0?{statusCode:e}:{},...t?.code!==void 0?{providerCode:String(t.code)}:{},...t?.message!==void 0?{providerMessage:t.message}:{},...t?.requestId!==void 0?{requestId:t.requestId}:{},transport:s}}function G2(r,e){return Na({attempt:r,initialDelayMs:e.initialDelayMs,maxDelayMs:e.maxDelayMs,retryAfterMode:"minimum",retryAfterMaxDelayMs:e.maxDelayMs,error:e.error})}function Sde(r){if(Po(r)){let t=Number(r.error.code);if(Number.isFinite(t)&&t>0)return t}let e=r instanceof Error?r.message:typeof r=="string"?r:null;if(e){let t=e.indexOf("{");if(t!==-1)try{let n=JSON.parse(e.substring(t));if(Po(n)){let s=Number(n.error.code);if(Number.isFinite(s)&&s>0)return s}}catch{}}if(Dd(r)&&typeof r.status=="number")return r.status;if(r instanceof Error&&"status"in r){let t=r.status;if(typeof t=="number")return t}return Eo(r)??null}function Cde(r){for(let e of Ede(r)){if(typeof e!="object"||e===null)continue;let t=e,n=e.error,o=(typeof n=="object"&&n!==null?n:void 0)??t,a=typeof o.code=="string"||typeof o.code=="number"?o.code:void 0,l=typeof o.message=="string"?o.message:void 0,c=typeof o.request_id=="string"?o.request_id:typeof o.requestId=="string"?o.requestId:typeof t.request_id=="string"?t.request_id:typeof t.requestId=="string"?t.requestId:void 0;if(a!==void 0||l!==void 0||c!==void 0)return{code:a,message:l,requestId:c}}return Po(r)?{code:r.error.code,message:r.error.message}:null}function Ede(r){let e=V2(r);if(!e)return[];let t=[];for(let o of e.split(/\r?\n/)){if(!o.startsWith("data:"))continue;let a=o.slice(5).trim();if(!(!a||a==="[DONE]"))try{t.push(JSON.parse(a))}catch{}}if(t.length>0)return t;let n=e.indexOf("{"),s=e.lastIndexOf("}");if(n!==-1&&s>n)try{t.push(JSON.parse(e.slice(n,s+1)))}catch{}return t}function V2(r){return r instanceof Error?r.message:typeof r=="string"?r:null}g();function rv(r,e={}){if(Tde(r))return{kind:"abort",diagnosis:"fail-fast",reason:"aborted"};let t=tv(r),n=t.statusCode,s=Rde(r),o=t.providerCode??s.providerCode,a=t.providerMessage??s.providerMessage,l=t.requestId??s.requestId,c={...n!==void 0?{statusCode:n}:{},...o!==void 0?{providerCode:o}:{},...a!==void 0?{providerMessage:a}:{},...l!==void 0?{requestId:l}:{}};if(e.authType==="matilda-oauth"&&Qb(r))return{kind:"provider-business",diagnosis:"fail-fast",reason:"matilda-oauth-free-tier-quota",...c};if(Ade(o))return{kind:"provider-business",diagnosis:"fail-fast",reason:"allocated-quota-exceeded",...c};if(kc(r,e.extraRetryErrorCodes))return{kind:t.transport==="sse"?"sse-provider":n!==void 0?"http":"provider",diagnosis:"retryable",reason:"rate-limit",...c};let u=kde(r);if(u!==void 0&&(n===void 0||n>=500))return{kind:"transport",diagnosis:"retryable",reason:"transport-error",transportCode:u,...n!==void 0?{statusCode:n}:{}};if(n!==void 0){let h=t.transport==="sse"?"sse-provider":"http";return n===529?{kind:h,diagnosis:"retryable",reason:"capacity-overload",...c}:n===401||n===403?{kind:h,diagnosis:"fail-fast",reason:"auth-error",...c}:n>=400&&n<500?{kind:h,diagnosis:"fail-fast",reason:"client-error",...c}:n>=500&&n<600?{kind:h,diagnosis:"retryable",reason:"server-error",...c}:{kind:h,diagnosis:"unknown",reason:"http-status",...c}}return{kind:"unknown",diagnosis:"unknown",reason:"unclassified",...c}}function Tde(r){return Sb(r)?!0:r instanceof Error&&r.name==="CanceledError"}function kde(r){if(typeof r!="object"||r===null)return;let e=r.code;if(typeof e=="string"&&K2(e))return e;let t=r instanceof Error?r.cause:void 0;if(typeof t=="object"&&t!==null){let n=t.code;if(typeof n=="string"&&K2(n))return n}}function K2(r){return xde.has(r)}var xde=new Set(["EAI_AGAIN","ECONNABORTED","ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETUNREACH","ENOTFOUND","EPIPE","ETIMEDOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_SOCKET"]);function Ade(r){return r==="Throttling.AllocationQuota"}function Rde(r){if(typeof r!="object"||r===null)return{};let e=r,t=typeof e.code=="string"||typeof e.code=="number"?String(e.code):void 0,n=typeof e.code=="number"&&e.code>=100&&e.code<600,s=r instanceof Error&&t?.startsWith("ERR_")||n?void 0:t,o=typeof e.request_id=="string"?e.request_id:typeof e.requestId=="string"?e.requestId:void 0,a=typeof e.message=="string"&&(!(r instanceof Error)||s!==void 0||o!==void 0)?e.message:void 0;return{...s!==void 0?{providerCode:s}:{},...a!==void 0?{providerMessage:a}:{},...o!==void 0?{requestId:o}:{}}}var xc=F("RETRY"),Pde=5*60*1e3,Mde=6*60*60*1e3,Ide=3e4,Ode={maxAttempts:7,initialDelayMs:1500,maxDelayMs:3e4,shouldRetryOnError:J2};function J2(r,e){let t=Eo(r);return kc(r,e)||t!==void 0&&t>=500&&t<600}function Y2(r){return r===429||r===503}function Dde(r){let e=Eo(r);return e===429||e===529}function Ac(){let r=process.env.MATILDA_CODE_UNATTENDED_RETRY;return r==="true"||r==="1"}function nP(r,e){return new Promise((t,n)=>{if(e?.aborted)return n(new Error("Retry aborted by signal"));let s=()=>{e?.removeEventListener("abort",o)};function o(){clearTimeout(a),s(),n(new Error("Retry aborted by signal"))}let a=setTimeout(()=>{s(),t()},r);e?.addEventListener("abort",o,{once:!0}),e?.aborted&&(clearTimeout(a),s(),n(new Error("Retry aborted by signal")))})}async function Lde(r,e){let t=r;for(;t>0;){if(e.signal?.aborted)throw new Error("Retry aborted by signal");let n=Math.max(1,Math.min(t,e.heartbeatInterval));await nP(n,e.signal),t-=n,t>0&&e.heartbeatFn&&e.heartbeatFn({attempt:e.attempt,remainingMs:t,error:e.error})}}async function Rc(r,e){if(e?.maxAttempts!==void 0&&e.maxAttempts<=0)throw new Error("maxAttempts must be a positive number.");let t=e?Object.fromEntries(Object.entries(e).filter(([K,q])=>q!=null)):{},{maxAttempts:n,initialDelayMs:s,maxDelayMs:o,authType:a,extraRetryErrorCodes:l,shouldRetryOnError:c,shouldRetryOnContent:u,persistentMode:h,persistentMaxBackoffMs:d,persistentCapMs:f,heartbeatIntervalMs:p,heartbeatFn:y,signal:w,onRetry:m}={...Ode,...t},_=typeof e?.shouldRetryOnError=="function",b=h??!1,v=d??Pde,S=f??Mde,E=p??Ide,T=0,A=0,k=s,P=Date.now(),B=0,$=0,O,U=!1;for(;T<n;){T++,B++;let K=Date.now()-P;try{let q=await Oj.run({attempt:B,retryTotalDelayMs:$,requestSetupMs:K},()=>r());if(u&&u(q)){O=q,U=!0;let W=Na({attempt:1,initialDelayMs:k,maxDelayMs:o,jitterRatio:.3});xc.warn(`Attempt ${B}: response rejected by content check. Retrying with backoff in ${Math.ceil(W/1e3)}s...`),await nP(W,w),$+=W,k=Math.min(o,k*2);continue}return q}catch(q){let W=Eo(q),z=rv(q,{authType:a,extraRetryErrorCodes:l});if(z.kind==="abort")throw q;if(a==="matilda-oauth"&&Qb(q))throw xc.error("Legacy OAuth quota exceeded, fast-failing",z,q),new Error(`This legacy OAuth route is unavailable.
281
+ `});return e?t.pop():t.push(t.pop().slice(0,-1)),t}g();var YA=Ve(cB(),1);import*as mt from"node:fs";import*as mue from"node:fs/promises";import*as bn from"node:path";import hr from"node:process";g();import*as Tc from"node:fs/promises";import*as Vp from"node:path";g();var eP=5,B2=(a=>(a.INITIALIZING="initializing",a.RUNNING="running",a.IDLE="idle",a.COMPLETED="completed",a.CANCELLED="cancelled",a.FAILED="failed",a))(B2||{});function Cc(r){return r.replace(/[/\\:*?"<>|]/g,"--")}g();var Ec=(a=>(a.ERROR="ERROR",a.TIMEOUT="TIMEOUT",a.GOAL="GOAL",a.MAX_TURNS="MAX_TURNS",a.CANCELLED="CANCELLED",a.SHUTDOWN="SHUTDOWN",a))(Ec||{}),Md=(a=>(a.INITIALIZING="initializing",a.RUNNING="running",a.IDLE="idle",a.COMPLETED="completed",a.FAILED="failed",a.CANCELLED="cancelled",a))(Md||{}),jt=r=>r==="completed"||r==="failed"||r==="cancelled",Gp=r=>r==="idle"||r==="completed",Xb=r=>r==="idle"||jt(r);var j2=F("ARENA_AGENT_CLIENT"),fde="agents",pde="control",Zb=class r{constructor(e,t){this.agentId=e;let n=Cc(e);this.agentsDir=Vp.join(t,fde),this.controlDir=Vp.join(t,pde),this.statusFilePath=Vp.join(this.agentsDir,`${n}.json`),this.controlFilePath=Vp.join(this.controlDir,`${n}.json`),this.startTimeMs=Date.now()}agentsDir;controlDir;statusFilePath;controlFilePath;startTimeMs;initialized=!1;static create(){let e=process.env.ARENA_AGENT_ID,t=process.env.ARENA_SESSION_ID,n=process.env.ARENA_SESSION_DIR;return!e||!t||!n?null:new r(e,n)}async init(){await Tc.mkdir(this.agentsDir,{recursive:!0}),await Tc.mkdir(this.controlDir,{recursive:!0}),this.initialized=!0,j2.info(`ArenaAgentClient initialized for agent ${this.agentId} at ${this.agentsDir}`)}async updateStatus(e){await this.ensureInitialized();let t=this.getStatsFromTelemetry(),n={agentId:this.agentId,status:"running",updatedAt:Date.now(),rounds:t.rounds,currentActivity:e,stats:t,finalSummary:null,error:null};await _s(this.statusFilePath,n)}async checkControlSignal(){await this.ensureInitialized();try{let e=await Tc.readFile(this.controlFilePath,"utf-8"),t=JSON.parse(e);return await Tc.unlink(this.controlFilePath),t}catch(e){if(Rt(e)&&e.code==="ENOENT")return null;if(Rt(e)&&e.code==="EACCES")throw e;return j2.error("Error reading control signal:",e),null}}async reportCompleted(e){await this.ensureInitialized();let t=this.getStatsFromTelemetry(),n={agentId:this.agentId,status:"completed",updatedAt:Date.now(),rounds:t.rounds,stats:t,finalSummary:e??null,error:null};await _s(this.statusFilePath,n)}async reportError(e){await this.ensureInitialized();let t=this.getStatsFromTelemetry(),n={agentId:this.agentId,status:"failed",updatedAt:Date.now(),rounds:t.rounds,stats:t,finalSummary:null,error:e};await _s(this.statusFilePath,n)}async reportCancelled(){await this.ensureInitialized();let e=this.getStatsFromTelemetry(),t={agentId:this.agentId,status:"cancelled",updatedAt:Date.now(),rounds:e.rounds,stats:e,finalSummary:null,error:null};await _s(this.statusFilePath,t)}getStatsFromTelemetry(){let e=jn.getMetrics(),t=0,n=0,s=0,o=0;for(let a of Object.values(e.models))t+=a.api.totalRequests,n+=a.tokens.total,s+=a.tokens.prompt,o+=a.tokens.candidates;return{rounds:t,totalTokens:n,inputTokens:s,outputTokens:o,durationMs:Date.now()-this.startTimeMs,toolCalls:e.tools.totalCalls,successfulToolCalls:e.tools.totalSuccess,failedToolCalls:e.tools.totalFail}}async ensureInitialized(){this.initialized||await this.init()}};g();g();function rP(r,e,t){let n=r.getContentGeneratorConfig(),s=t.authType===n.authType,o=r.getModelsConfig(),a=e?o.getResolvedModel(t.authType,e):void 0,l={...n,model:e??n.model,authType:t.authType};if(!s)for(let c of vc)l[c]=void 0;return a?(mde(l,a,n,t),l):(l.apiKey=tP(t.apiKey,s?n.apiKey:void 0,t.authType,"apiKey"),l.baseUrl=t.baseUrl??tP(void 0,s?n.baseUrl:void 0,t.authType,"baseUrl"),l.apiKeyEnvKey=s?n.apiKeyEnvKey:void 0,l)}async function Id(r,e,t,n){let s=rP(r,t,n);return{contentGenerator:await Ed(s,e),contentGeneratorConfig:s}}function mde(r,e,t,n){let s=n.authType===t.authType;r.model=e.id,r.authType=e.authType,r.baseUrl=n.baseUrl??e.baseUrl??(s?t.baseUrl:void 0),e.envKey?(r.apiKey=n.apiKey??process.env[e.envKey]??(s?t.apiKey:void 0),r.apiKeyEnvKey=e.envKey):(r.apiKey=tP(n.apiKey,s?t.apiKey:void 0,n.authType,"apiKey"),r.apiKeyEnvKey=s?t.apiKeyEnvKey:void 0);for(let o of vc){let a=e.generationConfig[o];a!==void 0&&(r[o]=a)}}function tP(r,e,t,n){if(r)return r;if(e)return e;let s=Hp[t];if(s)for(let o of s[n]){let a=process.env[o];if(a)return a}}g();var gde=new Set(Object.values(nn));function Ks(r,e={}){return q2(z2(r),e)}function Od(r){return{currentModel:r.getModel?.(),currentAuthType:r.getContentGeneratorConfig?.()?.authType,fastModel:r.getFastModel?.(),getAvailableModels:e=>r.getAllConfiguredModels?.(e)??[]}}function z2(r){let e=r?.trim();if(!e||e==="inherit")return{kind:"inherit"};if(e==="fast")return{kind:"fast"};let t=e.indexOf(":");if(t===-1)return{kind:"model",modelId:e};let n=e.slice(0,t).trim(),s=e.slice(t+1).trim();if(!gde.has(n))return{kind:"model",modelId:e};if(!s)throw new Error("Model selector must include a model ID after the authType");return{kind:"model",authType:n,modelId:s}}function yde(r,e){return e.currentAuthType&&e.getAvailableModels&&e.getAvailableModels([e.currentAuthType]).some(s=>s.id===r)?e.currentAuthType:(e.getAvailableModels?e.getAvailableModels().find(n=>n.id===r):void 0)?.authType??e.currentAuthType}function q2(r,e){if(r.kind==="model"){let n=r.authType??yde(r.modelId,e);return{...n?{authType:n}:{},modelId:r.modelId}}if(r.kind==="inherit")return e.currentModel?{...e.currentAuthType?{authType:e.currentAuthType}:{},modelId:e.currentModel}:void 0;if(!e.fastModel)return;let t=z2(e.fastModel);if(t.kind!=="fast")return q2(t,{...e,fastModel:void 0})}g();g();function Po(r){return typeof r=="object"&&r!==null&&"error"in r&&typeof r.error=="object"&&"message"in r.error}function Dd(r){return typeof r=="object"&&r!==null&&"message"in r&&typeof r.message=="string"}function o5e(r){let e=t=>t.includes("Quota exceeded for quota metric 'Gemini")&&t.includes("Pro Requests'");if(typeof r=="string")return e(r);if(Dd(r))return e(r.message);if(Po(r))return e(r.error.message);if(r&&typeof r=="object"&&"response"in r){let t=r;if(t.response&&t.response.data){if(typeof t.response.data=="string")return e(t.response.data);if(typeof t.response.data=="object"&&t.response.data!==null&&"error"in t.response.data){let n=t.response.data;return e(n.error?.message||"")}}}return!1}function a5e(r){return typeof r=="string"?r.includes("Quota exceeded for quota metric"):Dd(r)?r.message.includes("Quota exceeded for quota metric"):Po(r)?r.error.message.includes("Quota exceeded for quota metric"):!1}function Qb(r){if(typeof r!="object"||r===null)return!1;let{status:e,code:t,message:n}=r;return e===429&&t==="insufficient_quota"&&typeof n=="string"&&n.toLowerCase().includes("free allocated quota exceeded")}g();g();function Na(r){let e=Math.max(1,r.attempt),t=Math.min(r.maxDelayMs,2147483647),n=Math.min(e-1,31),s=Math.min(r.initialDelayMs*Math.pow(2,n),t),a=(r.retryAfterMode??"ignore")==="ignore"?null:ev(r.error);if(a!==null&&a>0){let h=Math.min(r.retryAfterMaxDelayMs??r.maxDelayMs,2147483647),d=Math.min(a,h);return Math.max(s,d)}let l=r.jitterRatio??0;if(l<=0)return s;let c=r.random??Math.random,u=s*l*(c()*2-1);return Math.min(Math.max(0,s+u),t)}function ev(r){let e=W2(r,"retry-after")??wde(r,"retry-after");if(e===null)return null;let t=e.trim();if(/^\d+(\.\d+)?$/.test(t)){let o=Number(t);if(Number.isFinite(o)&&o>=0)return Math.min(o*1e3,2147483647)}let n=Date.parse(t);if(!Number.isFinite(n))return null;let s=n-Date.now();return s>0?Math.min(s,2147483647):0}function W2(r,e){if(!_de(r))return null;let{headers:t}=r;if(typeof t.get=="function"){let s=t.get(e);return typeof s=="string"?s:null}if(typeof t!="object"||t===null)return null;let n=e.toLowerCase();for(let[s,o]of Object.entries(t))if(s.toLowerCase()===n)return typeof o=="string"?o:null;return null}function wde(r,e){return bde(r)?W2(r.response,e):null}function _de(r){return typeof r=="object"&&r!==null&&"headers"in r&&r.headers!=null}function bde(r){return typeof r=="object"&&r!==null&&"response"in r&&typeof r.response=="object"&&r.response!==null&&"headers"in r.response&&r.response.headers!=null}var vde=new Set([429,503,1302,1305]);function kc(r,e){let t=Sde(r);return t===null?!1:!!(vde.has(t)||e&&e.includes(t))}function tv(r){let e=Eo(r),t=Cde(r),n=V2(r),s=n?.includes("event:error")||n?.includes("HTTP_STATUS/")?"sse":e!==void 0?"http":"unknown";return{...e!==void 0?{statusCode:e}:{},...t?.code!==void 0?{providerCode:String(t.code)}:{},...t?.message!==void 0?{providerMessage:t.message}:{},...t?.requestId!==void 0?{requestId:t.requestId}:{},transport:s}}function G2(r,e){return Na({attempt:r,initialDelayMs:e.initialDelayMs,maxDelayMs:e.maxDelayMs,retryAfterMode:"minimum",retryAfterMaxDelayMs:e.maxDelayMs,error:e.error})}function Sde(r){if(Po(r)){let t=Number(r.error.code);if(Number.isFinite(t)&&t>0)return t}let e=r instanceof Error?r.message:typeof r=="string"?r:null;if(e){let t=e.indexOf("{");if(t!==-1)try{let n=JSON.parse(e.substring(t));if(Po(n)){let s=Number(n.error.code);if(Number.isFinite(s)&&s>0)return s}}catch{}}if(Dd(r)&&typeof r.status=="number")return r.status;if(r instanceof Error&&"status"in r){let t=r.status;if(typeof t=="number")return t}return Eo(r)??null}function Cde(r){for(let e of Ede(r)){if(typeof e!="object"||e===null)continue;let t=e,n=e.error,o=(typeof n=="object"&&n!==null?n:void 0)??t,a=typeof o.code=="string"||typeof o.code=="number"?o.code:void 0,l=typeof o.message=="string"?o.message:void 0,c=typeof o.request_id=="string"?o.request_id:typeof o.requestId=="string"?o.requestId:typeof t.request_id=="string"?t.request_id:typeof t.requestId=="string"?t.requestId:void 0;if(a!==void 0||l!==void 0||c!==void 0)return{code:a,message:l,requestId:c}}return Po(r)?{code:r.error.code,message:r.error.message}:null}function Ede(r){let e=V2(r);if(!e)return[];let t=[];for(let o of e.split(/\r?\n/)){if(!o.startsWith("data:"))continue;let a=o.slice(5).trim();if(!(!a||a==="[DONE]"))try{t.push(JSON.parse(a))}catch{}}if(t.length>0)return t;let n=e.indexOf("{"),s=e.lastIndexOf("}");if(n!==-1&&s>n)try{t.push(JSON.parse(e.slice(n,s+1)))}catch{}return t}function V2(r){return r instanceof Error?r.message:typeof r=="string"?r:null}g();function rv(r,e={}){if(Tde(r))return{kind:"abort",diagnosis:"fail-fast",reason:"aborted"};let t=tv(r),n=t.statusCode,s=Rde(r),o=t.providerCode??s.providerCode,a=t.providerMessage??s.providerMessage,l=t.requestId??s.requestId,c={...n!==void 0?{statusCode:n}:{},...o!==void 0?{providerCode:o}:{},...a!==void 0?{providerMessage:a}:{},...l!==void 0?{requestId:l}:{}};if(e.authType==="matilda-oauth"&&Qb(r))return{kind:"provider-business",diagnosis:"fail-fast",reason:"matilda-oauth-free-tier-quota",...c};if(Ade(o))return{kind:"provider-business",diagnosis:"fail-fast",reason:"allocated-quota-exceeded",...c};if(kc(r,e.extraRetryErrorCodes))return{kind:t.transport==="sse"?"sse-provider":n!==void 0?"http":"provider",diagnosis:"retryable",reason:"rate-limit",...c};let u=kde(r);if(u!==void 0&&(n===void 0||n>=500))return{kind:"transport",diagnosis:"retryable",reason:"transport-error",transportCode:u,...n!==void 0?{statusCode:n}:{}};if(n!==void 0){let h=t.transport==="sse"?"sse-provider":"http";return n===529?{kind:h,diagnosis:"retryable",reason:"capacity-overload",...c}:n===401||n===403?{kind:h,diagnosis:"fail-fast",reason:"auth-error",...c}:n>=400&&n<500?{kind:h,diagnosis:"fail-fast",reason:"client-error",...c}:n>=500&&n<600?{kind:h,diagnosis:"retryable",reason:"server-error",...c}:{kind:h,diagnosis:"unknown",reason:"http-status",...c}}return{kind:"unknown",diagnosis:"unknown",reason:"unclassified",...c}}function Tde(r){return Sb(r)?!0:r instanceof Error&&r.name==="CanceledError"}function kde(r){if(typeof r!="object"||r===null)return;let e=r.code;if(typeof e=="string"&&K2(e))return e;let t=r instanceof Error?r.cause:void 0;if(typeof t=="object"&&t!==null){let n=t.code;if(typeof n=="string"&&K2(n))return n}}function K2(r){return xde.has(r)}var xde=new Set(["EAI_AGAIN","ECONNABORTED","ECONNREFUSED","ECONNRESET","EHOSTUNREACH","ENETUNREACH","ENOTFOUND","EPIPE","ETIMEDOUT","UND_ERR_BODY_TIMEOUT","UND_ERR_CONNECT_TIMEOUT","UND_ERR_HEADERS_TIMEOUT","UND_ERR_SOCKET"]);function Ade(r){return r==="Throttling.AllocationQuota"}function Rde(r){if(typeof r!="object"||r===null)return{};let e=r,t=typeof e.code=="string"||typeof e.code=="number"?String(e.code):void 0,n=typeof e.code=="number"&&e.code>=100&&e.code<600,s=r instanceof Error&&t?.startsWith("ERR_")||n?void 0:t,o=typeof e.request_id=="string"?e.request_id:typeof e.requestId=="string"?e.requestId:void 0,a=typeof e.message=="string"&&(!(r instanceof Error)||s!==void 0||o!==void 0)?e.message:void 0;return{...s!==void 0?{providerCode:s}:{},...a!==void 0?{providerMessage:a}:{},...o!==void 0?{requestId:o}:{}}}var xc=F("RETRY"),Pde=5*60*1e3,Mde=6*60*60*1e3,Ide=3e4,Ode={maxAttempts:7,initialDelayMs:1500,maxDelayMs:3e4,shouldRetryOnError:J2};function J2(r,e){let t=Eo(r);if(kc(r,e)||t!==void 0&&t>=500&&t<600)return!0;let n=r instanceof Error?r.message:typeof r=="string"?r:String(r??"");return/EngineCore|EngineDeadError|upstream error|Bad Gateway|\b502\b|\b503\b/i.test(n)}function Y2(r){return r===429||r===503}function Dde(r){let e=Eo(r);return e===429||e===529}function Ac(){let r=process.env.MATILDA_CODE_UNATTENDED_RETRY;return r==="true"||r==="1"}function nP(r,e){return new Promise((t,n)=>{if(e?.aborted)return n(new Error("Retry aborted by signal"));let s=()=>{e?.removeEventListener("abort",o)};function o(){clearTimeout(a),s(),n(new Error("Retry aborted by signal"))}let a=setTimeout(()=>{s(),t()},r);e?.addEventListener("abort",o,{once:!0}),e?.aborted&&(clearTimeout(a),s(),n(new Error("Retry aborted by signal")))})}async function Lde(r,e){let t=r;for(;t>0;){if(e.signal?.aborted)throw new Error("Retry aborted by signal");let n=Math.max(1,Math.min(t,e.heartbeatInterval));await nP(n,e.signal),t-=n,t>0&&e.heartbeatFn&&e.heartbeatFn({attempt:e.attempt,remainingMs:t,error:e.error})}}async function Rc(r,e){if(e?.maxAttempts!==void 0&&e.maxAttempts<=0)throw new Error("maxAttempts must be a positive number.");let t=e?Object.fromEntries(Object.entries(e).filter(([K,q])=>q!=null)):{},{maxAttempts:n,initialDelayMs:s,maxDelayMs:o,authType:a,extraRetryErrorCodes:l,shouldRetryOnError:c,shouldRetryOnContent:u,persistentMode:h,persistentMaxBackoffMs:d,persistentCapMs:f,heartbeatIntervalMs:p,heartbeatFn:y,signal:w,onRetry:m}={...Ode,...t},_=typeof e?.shouldRetryOnError=="function",b=h??!1,v=d??Pde,S=f??Mde,E=p??Ide,T=0,A=0,k=s,P=Date.now(),B=0,$=0,O,U=!1;for(;T<n;){T++,B++;let K=Date.now()-P;try{let q=await Oj.run({attempt:B,retryTotalDelayMs:$,requestSetupMs:K},()=>r());if(u&&u(q)){O=q,U=!0;let W=Na({attempt:1,initialDelayMs:k,maxDelayMs:o,jitterRatio:.3});xc.warn(`Attempt ${B}: response rejected by content check. Retrying with backoff in ${Math.ceil(W/1e3)}s...`),await nP(W,w),$+=W,k=Math.min(o,k*2);continue}return q}catch(q){let W=Eo(q),z=rv(q,{authType:a,extraRetryErrorCodes:l});if(z.kind==="abort")throw q;if(a==="matilda-oauth"&&Qb(q))throw xc.error("Legacy OAuth quota exceeded, fast-failing",z,q),new Error(`This legacy OAuth route is unavailable.
282
282
 
283
283
  To continue using Matilda, try one of these alternatives:
284
284
  - OpenRouter: https://openrouter.ai/docs/quickstart
@@ -1124,7 +1124,7 @@ ${Zfe}`}function Qfe(r){let e=r[r.length-1];if(!(!e||e.role!=="model")&&e.parts?
1124
1124
  You are currently in PLAN mode. You may research, read files, and propose plans, but you may not execute modification tools (${R.WRITE_FILE}, ${R.EDIT}, ${R.SHELL}, etc.) until the user exits plan mode. The summary above may not reflect this constraint \u2014 honor plan mode regardless.
1125
1125
  </plan-mode-active>`,Tq=200,rpe=30;function npe(){return{text:tpe}}function spe(r){return r.replace(/[\r\n\t]+/g," ")}function ipe(r){if(r.length===0)return null;let e=[...r].sort((o,a)=>o.startTime-a.startTime),t=Math.max(0,e.length-rpe),s=(t>0?e.slice(t):e).map(o=>{let a=spe(o.description),l=a.length>Tq?a.slice(0,Tq)+"\u2026":a;return`- [${et(o.status)}] ${et(o.id)}: ${et(l)}`});return t>0&&s.push(`- (\u2026 and ${t} older task${t===1?"":"s"} not shown)`),{text:"<background-tasks>\nThe following background subagent tasks were active at compaction. The summary above does not include their per-task state. Use `task_stop` / `send_message` to interact; do not assume they completed.\n"+s.join(`
1126
1126
  `)+`
1127
- </background-tasks>`}}function UP(r){let e=[];if(r.planModeActive&&e.push(npe()),r.runningSubagents&&r.runningSubagents.length>0){let t=ipe(r.runningSubagents);t&&e.push(t)}return e}async function xq(r,e,t={}){let{workspaceRoot:n,signal:s,maxFiles:o=Ffe,maxImages:a=Bfe,planModeActive:l,runningSubagents:c}=t,u=qfe(r,o).filter(_=>epe(_,n)),h=await Jfe(u,s),d=Gfe(r,a),f=Xfe(d),p=[...UP({planModeActive:l,runningSubagents:c})];for(let _ of h)for(let b of _.parts??[])p.push(b);if(f)for(let _ of f.parts??[])p.push(_);let y=Qfe(r),w=[{text:"Got it. Thanks for the additional context!"}],m=[{role:"user",parts:[{text:HP(e)}]}];if(p.length>0)m.push({role:"model",parts:w}),m.push({role:"user",parts:p}),y&&m.push(y);else if(y){let _=(y.parts??[]).filter(b=>!!b.functionCall);m.push({role:"model",parts:[...w,..._]})}else m.push({role:"model",parts:w});return m}var bv=2e4,Aq=45e3,Rq=.7,ope=.1,ape=bv,lpe=13e3,Pq=2e4,Mq=3e3,Iq=48e3,Oq=16e3,cpe=256e3,upe=64e3,dpe=32e3,Gd=3,hpe=1.5,fpe=/[\u3040-\u30ff\u3400-\u9fff\uf900-\ufaff\uac00-\ud7af]/g;function ppe(r,e){let t=Cs([{role:"model",parts:[{text:r}]}],e),n=r.match(fpe)?.length??0;if(n===0)return t;let s=Math.max(0,r.length-n),o=Math.ceil(s/Xs)+Math.ceil(n*hpe);return Math.max(t,o)}var mpe=4e3;function gpe(r,e){if(r<=0)return 0;let t=Math.max(0,r-Oq);return e>=Iq+Oq?Math.min(Iq,t,r):Math.min(t,r)}function hm(r){let e=Math.max(0,r-ape),t=e-lpe,n=Math.max(Rq*r,t),s=r>=cpe;s&&(n=Math.min(n,upe));let o=n-Pq,a=Math.max((Rq-ope)*r,o);s&&(a=Math.min(a,Math.max(0,n-Pq)));let l=e-Mq,c=Math.min(r,Math.max(l,n+Mq));s&&(c=Math.min(c,n+dpe));let u=gpe(n,e);return{warn:a,prefire:u,auto:n,hard:c,effectiveWindow:e}}function Dq(r){let e=r.getBackgroundTaskRegistry?.();return e?e.getAll().filter(t=>t.kind==="agent"&&t.isBackgrounded&&(t.status==="running"||t.status==="paused")).map(t=>({id:t.id,description:t.description,status:t.status,startTime:t.startTime})):[]}function ype(r,e){let t=bq(),n=[];return r&&r.trim().length>0&&n.push(r.trim()),e.length>0&&n.push(e),n.length===0?t:`${t}
1127
+ </background-tasks>`}}function UP(r){let e=[];if(r.planModeActive&&e.push(npe()),r.runningSubagents&&r.runningSubagents.length>0){let t=ipe(r.runningSubagents);t&&e.push(t)}return e}async function xq(r,e,t={}){let{workspaceRoot:n,signal:s,maxFiles:o=Ffe,maxImages:a=Bfe,planModeActive:l,runningSubagents:c}=t,u=qfe(r,o).filter(_=>epe(_,n)),h=await Jfe(u,s),d=Gfe(r,a),f=Xfe(d),p=[...UP({planModeActive:l,runningSubagents:c})];for(let _ of h)for(let b of _.parts??[])p.push(b);if(f)for(let _ of f.parts??[])p.push(_);let y=Qfe(r),w=[{text:"Got it. Thanks for the additional context!"}],m=[{role:"user",parts:[{text:HP(e)}]}];if(p.length>0)m.push({role:"model",parts:w}),m.push({role:"user",parts:p}),y&&m.push(y);else if(y){let _=(y.parts??[]).filter(b=>!!b.functionCall);m.push({role:"model",parts:[...w,..._]})}else m.push({role:"model",parts:w});return m}var bv=2e4,Aq=12e3,Rq=.7,ope=.1,ape=bv,lpe=13e3,Pq=2e4,Mq=3e3,Iq=96e3,Oq=16e3,cpe=256e3,upe=128e3,dpe=32e3,Gd=3,hpe=1.5,fpe=/[\u3040-\u30ff\u3400-\u9fff\uf900-\ufaff\uac00-\ud7af]/g;function ppe(r,e){let t=Cs([{role:"model",parts:[{text:r}]}],e),n=r.match(fpe)?.length??0;if(n===0)return t;let s=Math.max(0,r.length-n),o=Math.ceil(s/Xs)+Math.ceil(n*hpe);return Math.max(t,o)}var mpe=4e3;function gpe(r,e){if(r<=0)return 0;let t=Math.max(0,r-Oq);return e>=Iq+Oq?Math.min(Iq,t,r):Math.min(t,r)}function hm(r){let e=Math.max(0,r-ape),t=e-lpe,n=Math.max(Rq*r,t),s=r>=cpe;s&&(n=Math.min(n,upe));let o=n-Pq,a=Math.max((Rq-ope)*r,o);s&&(a=Math.min(a,Math.max(0,n-Pq)));let l=e-Mq,c=Math.min(r,Math.max(l,n+Mq));s&&(c=Math.min(c,n+dpe));let u=gpe(n,e);return{warn:a,prefire:u,auto:n,hard:c,effectiveWindow:e}}function Dq(r){let e=r.getBackgroundTaskRegistry?.();return e?e.getAll().filter(t=>t.kind==="agent"&&t.isBackgrounded&&(t.status==="running"||t.status==="paused")).map(t=>({id:t.id,description:t.description,status:t.status,startTime:t.startTime})):[]}function ype(r,e){let t=bq(),n=[];return r&&r.trim().length>0&&n.push(r.trim()),e.length>0&&n.push(e),n.length===0?t:`${t}
1128
1128
 
1129
1129
  Additional Instructions:
1130
1130
  ${n.join(`
@@ -2159,7 +2159,7 @@ ${kd(r)}
2159
2159
  The current date is: ${q}. Note: This is the authoritative current date \u2014 it may differ from the "Today's date" mentioned earlier in the conversation startup context.
2160
2160
  </system-reminder>`),this.lastInjectedDate=q)}this.config.getApprovalMode()==="plan"&&O.push(wv(this.config.getSdkMode()));let U=this.config.getArenaManager();if(U)try{let W=`${U.getArenaSessionDir()}/config.json`;O.push(vq(W))}catch{}let K=await this.tryConsumeMemoryPrefetch();K?.prompt&&O.unshift(K.prompt),T=[...O,...T]}if(a==="toolResult"){let O=await this.tryConsumeMemoryPrefetch();O?.prompt&&(T=[...T,O.prompt]),await this.microcompactHistoryBeforeSend(null,{sizeOnly:!0,pendingContent:Ws(T)})}let A=Td(this.config.getSessionId());A&&(yield{type:"active_goal",value:A});let k=A,P=O=>{if(!DR(k,O))return k=O,{type:"active_goal",value:O??null}},B=S.run(E,T,t),$=!1;for await(let O of B){b&&!$&&(this.lastSentIdeContext=_,this.forceFullIdeContext=!1,$=!0);let U=this.config.getSkipLoopDetection(),K=!U&&this.loopDetector.addAndCheckDeterministicToolCallLoop(O),q=!K&&!U&&this.loopDetector.addAndCheckHeuristicLoops(O);if(K||q){let W=this.loopDetector.getLastLoopType();if(O.type==="tool_call_request"&&W==="consecutive_identical_tool_calls"){let z=this.loopDetector.getConsecutiveToolCallCount(),G=Math.max(0,S.pendingToolCalls.length-z);S.pendingToolCalls.splice(G)}return yield{type:"loop_detected",...W&&{value:{loopType:W}}},v&&await v.reportError("Loop detected"),this.lastApiCompletionTimestamp=Date.now(),u&&rn("error",{errorMessage:"loop detected"}),this.cancelPendingMemoryPrefetch(),S}if(v&&O.type==="finished"&&await v.updateStatus(),O.type==="chat_compressed"){this.forceFullIdeContext=!0;try{await this.restoreStartupContextAfterCompaction()}catch(W){this.config.getDebugLogger().warn(`Failed to restore startup context after compaction: ${W}`)}this.fireSessionStartHook("compact").then(W=>{!W||!this.chat||(this.lastSessionStartContext=W,this.lastSessionStartSource="compact",this.chat.applySessionStartContext(W,"compact"))}).catch(W=>{this.config.getDebugLogger().warn(`SessionStart hook failed: ${W}`)})}if(yield O,O.type==="error"){if(this.forceFullIdeContext=!0,v){let W=O.value instanceof Error?O.value.message:"Unknown error";await v.reportError(W)}if(this.lastApiCompletionTimestamp=Date.now(),u){let W=O.value instanceof Error?"[API error]":"unknown error";rn("error",{errorMessage:W})}return this.cancelPendingMemoryPrefetch(),S}}if(this.lastApiCompletionTimestamp=Date.now(),l&&c&&!S.pendingToolCalls.length&&t&&!t.aborted&&this.config.hasHooksForEvent("Stop")){let O=this.getLastModelMessageText()||"[no response text]",U=await c.request({type:"hook-execution-request",eventName:"Stop",input:{stop_hook_active:!0,last_assistant_message:O},signal:t},"hook-execution-response"),K=Td(this.config.getSessionId());if(t.aborted){let G=P(K);return G&&(yield G),u&&rn("cancelled"),S}let W=U.output?ot("Stop",U.output):void 0;if(W?.systemMessage&&(yield{type:"hook_system_message",value:W.systemMessage}),W?.isBlockingDecision()||W?.shouldStopExecution()){if(t.aborted){let ae=P(K);return ae&&(yield ae),u&&rn("cancelled"),S}let G=W.getEffectiveReason(),x=(s?.stopHookState?.iterationCount??0)+1,I=[...s?.stopHookState?.reasons??[],G],L=this.config.getStopHookBlockingCap();if(x>=L){let ae=Ic("Stop",L);LR(this.config,this.config.getSessionId(),ae);let M=Td(this.config.getSessionId()),te=P(M);return te&&(yield te),yield{type:"hook_system_message",value:ae},Ze.warn(ae),u&&rn("ok"),S}let N=P(K);N&&(yield N),yield{type:"stop_hook_loop",value:{iterationCount:x,reasons:I,stopHookCount:U.stopHookCount??1}};let j=[{text:G}],V=Td(this.config.getSessionId())?d:d-1,J=yield*this.sendMessageStream(j,t,n,{type:"hook",modelOverride:s?.modelOverride,stopHookState:{iterationCount:x,reasons:I}},V);return u&&rn(t.aborted?"cancelled":"ok"),h=!0,J}let z=P(K);z&&(yield z)}if(!S.pendingToolCalls.length&&t&&!t.aborted){try{let G=this.getChat(),I=this.getHistoryTailShallow(40,!0);Cce(G.getGenerationConfig(),I,this.config.getModel())}catch{}let O=this.config.getApprovalMode(),U=nz(O)||O==="plan",K=this.getChat().getLastHistoryEntry?.(),q=VU(K),W=zA(K)||q||!!K&&jA(K);if(this.config.getSkipNextSpeakerCheck()&&!U&&!W)return this.runManagedAutoMemoryBackgroundTasks(a),v&&await v.reportCompleted(),u&&rn("ok"),S;let z=await sue(this.getChat(),this.config,t,n);if(uj(this.config,new kj(n,S.finishReason?.toString()||"",z?.next_speaker||"")),z?.next_speaker==="model"){let G=[{text:zA(K)?"Please continue with a user-visible response. Do not only think silently \u2014 summarize results or take the next concrete action.":q?"You announced a next action but did not call a tool. Call the appropriate tool now (e.g. enter_plan_mode, or a read-only investigation tool). Do not only restate your intent.":"Please continue."}],x=yield*this.sendMessageStream(G,t,n,{...s,type:"hook"},d-1);return u&&rn(t.aborted?"cancelled":"ok"),h=!0,x}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??IE.getStore()??this.lastPromptId,l=s;try{let c=this.config.getUserMemory(),u=t.systemInstruction?um(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 Rc(()=>(l=y,d.generateContent({model:y,config:h,contents:e},a)),{authType:f,extraRetryErrorCodes:p,persistentMode:Ac(),signal:n,heartbeatFn:_=>{KU.stderr.write(`[matilda-code] Waiting for API capacity... attempt ${_.attempt}, retry in ${Math.ceil(_.remainingMs/1e3)}s
2161
2161
  `)},onRetry:_=>{yc(this.config,new bc({model:l,promptId:a,attemptNumber:_.attempt,error:_.error,statusCode:_.errorStatus,retryDelayMs:_.delayMs,subagentName:To.getStore()}))}})}catch(c){throw n.aborted?c:(await Di(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=>cVe.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 Pp from"node:fs/promises";import*as iue from"node:path";var hd=F("WORKTREE_CLEANUP"),yVe=[pL],wVe=30*24*60*60*1e3;function _Ve(r){return yVe.some(e=>e.test(r))}async function oue(r,e={}){let t=e.cutoffMs??wVe,n=Date.now()-t,s=new ts(r),o=s.getUserWorktreesDir();try{await Pp.access(o)}catch{return 0}let a;try{a=await Pp.readdir(o,{withFileTypes:!0})}catch(c){return c.code==="ENOENT"||hd.warn(`Failed to read ${o}: ${c}`),0}let l=0;for(let c of a){if(!c.isDirectory()||!_Ve(c.name))continue;let u=iue.join(o,c.name),h;try{h=(await Pp.stat(u)).mtimeMs}catch(y){y.code!=="ENOENT"&&hd.warn(`cleanupStaleAgentWorktrees: cannot stat ${u} \u2014 skipping: ${y}`);continue}if(h>=n)continue;let[d,f]=await Promise.all([bVe(u),s.hasUnmergedWorktreeCommits(c.name)]);if(d||f)continue;let p=await s.removeUserWorktree(c.name,{deleteBranch:!0});if(!p.success){hd.warn(`Failed to remove stale agent worktree ${u}: ${p.error}`);continue}p.branchPreserved?hd.warn(`Removed stale agent worktree ${u} but kept branch ${Fy(c.name)} (unmerged commits at delete time)`):hd.debug(`Removed stale agent worktree ${u}`),l+=1}return l>0&&hd.debug(`cleanupStaleAgentWorktrees: removed ${l} stale worktree(s)`),l}async function bVe(r){try{return(await Zr(r).raw(["status","--porcelain","--untracked-files=no"])).trim().length>0}catch(e){return hd.warn(`hasTrackedChanges: cannot inspect ${r} \u2014 assuming dirty: ${e}`),!0}}g();import*as Mp from"node:os";import{readFileSync as SVe}from"node:fs";import{EventEmitter as CVe}from"node:events";import{getHeapStatistics as cue}from"node:v8";g();import*as yb from"node:fs";import*as JU from"node:path";import*as lue from"node:v8";var gb=F("MEMORY_DUMP"),aue=3,vVe=3e4,WA=class{constructor(e){this.config=e}dumpCount=0;lastDumpTime=0;resetForNewSession(){this.dumpCount=0,this.lastDumpTime=0}async dump(e,t=[]){if(this.dumpCount>=aue){gb.debug(`Skipping dump: session cap reached (${aue})`);return}let n=Date.now();if(n-this.lastDumpTime<vVe){gb.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=JU.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:lue.getHeapStatistics(),recentSamples:t,session:this.collectSessionStats(),suggestion:this.getSuggestion(e),collectionComplete:!1};yb.writeFileSync(u,JSON.stringify(f,null,2),"utf8"),gb.info(`Phase 1 diagnostics written to ${u} (trigger=${e}, dump #${s})`);let p=await dle({sessionId:a,matildaVersion:this.config.getCliVersion()}),y={trigger:e,dumpNumber:s,...p,recentSamples:t,session:this.collectSessionStats(),suggestion:this.getSuggestion(e),collectionComplete:!0};return yb.writeFileSync(u,JSON.stringify(y,null,2),"utf8"),gb.info(`Phase 2 diagnostics written to ${u} (trigger=${e}, dump #${s})`),{filePath:u,trigger:e}}catch(o){gb.error(`Failed to write memory diagnostics: ${Q(o)}`);return}}ensureDiagnosticsDir(){let e=this.config.storage.getProjectDir(),t=JU.join(e,"diagnostics");return yb.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 EVe=60,fd;function TVe(){if(fd===void 0){try{fd=Mp.availableParallelism?.()??Mp.cpus().length??1}catch{fd=1}(!fd||fd<1)&&(fd=1)}return fd}function XU(){try{return process.cpuUsage()}catch{return{user:0,system:0}}}var ZU=class{samples=[];prevCpuUsage=XU();prevSampleTime=Date.now();record(e){let t=Date.now(),n=t-this.prevSampleTime,s=XU(),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/TVe()));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>EVe&&this.samples.shift(),e}getAll(){return[...this.samples]}reset(){this.samples.length=0,this.prevCpuUsage=XU(),this.prevSampleTime=Date.now()}},GA={softPressureRatio:.5,hardPressureRatio:.65,criticalRatio:.8,cleanupCooldownMs:5e3,enableExplicitGC:!0};function eB(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"),kVe=64*1024*1024,bb=class extends CVe{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 ZU;constructor(e,t){super(),this.coreConfig=e,this.config={...t??GA},eB(this.config),this.effectiveMemoryLimit=this.computeEffectiveMemoryLimit(),this.diagnosticsDumper=new WA(e);let n=cue().heap_size_limit;it.info(`Effective memory limit: ${_b(this.effectiveMemoryLimit)} MiB; V8 heap limit: ${_b(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);UB()&&(oR(this.coreConfig,l.rss,{memory_type:"rss"}),oR(this.coreConfig,l.heapUsed,{memory_type:"heap_used"}),HB(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=wb(n.action)>wb(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=cue().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 QU(e)}}executeCleanup(e){if(this.cleanupInProgress){let s=wb(e.action),o=wb(this.activeCleanupAction),a=this.queuedCleanupRecommendation?wb(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++,uue(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}`),uue(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 QU(e)}}computeEffectiveMemoryLimit(){let e=Mp.totalmem(),t=this.readCgroupMemoryLimit("/sys/fs/cgroup/memory.max",e);if(t!==void 0)return it.info(`Using cgroup v2 memory limit: ${_b(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: ${_b(n)} MiB`),n):(it.info(`Using host memory limit: ${_b(e)} MiB`),e)}readCgroupMemoryLimit(e,t){try{let n=SVe(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<kVe){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 wb(r){switch(r){case"aggressive":return 3;case"moderate":return 2;case"light":return 1;case"none":return 0;default:return QU(r)}}function uue(r){return r===3||r===10||r>10&&r%20===0}function _b(r){return(r/1024/1024).toFixed(0)}function QU(r){throw new Error(`Unhandled memory pressure monitor value: ${String(r)}`)}g();var xVe=F("PROMPT_REGISTRY"),VA=class{prompts=new Map;registerPrompt(e){if(this.prompts.has(e.name)){let t=`${e.serverName}_${e.name}`;xVe.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 due}from"node:crypto";var AVe=F("GIT_CO_AUTHOR"),RVe=F("MEMORY_PRESSURE"),hue=.15;var vs=(o=>(o.PLAN="plan",o.DEFAULT="default",o.AUTO_EDIT="auto-edit",o.AUTO="auto",o.BOGAN="bogan",o))(vs||{}),cH=Object.values(vs),rB=class extends Error{constructor(e){super(e),this.name="TrustGateError"}},a4t={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"}},KA="Written by Matilda \u{1F1E6}\u{1F1FA} made by [Maincode](https://maincode.com)";function PVe(r){if(typeof r=="boolean")return{commit:r,pr:r,prMessage:KA};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)||AVe.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:KA;return{commit:e(r?.commit,"commit"),pr:e(r?.pr,"pr"),prMessage:n}}var MVe=25e3,IVe=1e3,OVe=2e5;function l4t(r){return r==="project"||r==="workspace"}var fue=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 I8=(n=>(n.DYNAMIC_DISCOVERY="dynamic_discovery",n.GOOGLE_CREDENTIALS="google_credentials",n.SERVICE_ACCOUNT_IMPERSONATION="service_account_impersonation",n))(I8||{});function DVe(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 LVe(){let r={...GA};try{r.softPressureRatio=tB("MATILDA_MEMORY_PRESSURE_SOFT",r.softPressureRatio),r.hardPressureRatio=tB("MATILDA_MEMORY_PRESSURE_HARD",r.hardPressureRatio),r.criticalRatio=tB("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),eB(r)}catch(e){let t=`[MATILDA] WARNING: Invalid memory pressure config; using defaults. Error: ${Q(e)}`;return hr.stderr.write(`${t}
2162
- `),RVe.warn(t),{...GA}}return r}function tB(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 NVe=[R.READ_FILE,R.EDIT,R.NOTEBOOK_EDIT,R.SHELL],FVe=Object.freeze(new Set),pue=!1,cp=class{sessionId;sessionData;pendingStartupWorktreeNotice=null;debugLogger;toolRegistry;pendingMcpBudgetCallback;promptRegistry;subagentManager;memoryPressureConfig;memoryPressureMonitor;backgroundTaskRegistry=new sA;monitorRegistry=new FE;backgroundAgentResumeService;backgroundShellRegistry=new $E;workflowRunRegistry=new HE;fileReadCache=new ay;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=Pm();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??due(),!pue&&hr.env&&(hr.env.MATILDA_CODE_SESSION_ID=this.sessionId,pue=!0),this.sessionData=e.sessionData,nR(this),this.debugLogger=F(),this.embeddingModel=e.embeddingModel??RR,this.fileSystemService=new oE,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 Ea(this.targetDir,this.explicitIncludeDirectories),this.debugMode=e.debugMode,this.inputFormat=e.inputFormat??"text";let t=DVe(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??AR,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={...PVe(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??5;this.clearContextOnIdle={toolResultsThresholdMinutes:s,toolResultsNumToKeep:n?.toolResultsNumToKeep??5,toolResultsTotalCharsThreshold:n?.toolResultsTotalCharsThreshold??((n?.toolResultsThresholdMinutes??0)<0?-1:5e5)},this.sessionTokenLimit=e.sessionTokenLimit??-1,this.experimentalZedIntegration=e.experimentalZedIntegration??!1,this.cronEnabled=e.cronEnabled??!0,this.agentTeamEnabled=e.agentTeamEnabled??!1,this.workflowsEnabled=e.workflowsEnabled??!1,this.computerUseEnabled=e.computerUseEnabled??!0,this.computerUseMaxImageDimension=e.computerUseMaxImageDimension,this.emitToolUseSummaries=e.emitToolUseSummaries??!0,this.listExtensions=e.listExtensions??!1,this.overrideExtensions=e.overrideExtensions,this.noBrowser=e.noBrowser??!1,this.folderTrustFeature=e.folderTrustFeature??!1,this.folderTrust=e.folderTrust??!1,this.ideMode=e.ideMode??!1,this.modelProvidersConfig=e.modelProvidersConfig,this.cliVersion=e.cliVersion,this.chatRecordingEnabled=e.chatRecording??!0,this.loadMemoryFromIncludeDirectories=e.loadMemoryFromIncludeDirectories??!1,this.importFormat=e.importFormat??"tree",this.chatCompression=e.chatCompression,this.interactive=e.interactive??!1,this.trustedFolder=e.trustedFolder,this.skipLoopDetection=e.skipLoopDetection??!1,this.skipStartupContext=e.skipStartupContext??!1,this.bareMode=e.bareMode??!1,this.warnings=e.warnings??[],this.addLegacyPlanLocationWarning(),this.allowedHttpHookUrls=e.allowedHttpHookUrls??[],this.onPersistPermissionRuleCallback=e.onPersistPermissionRule,this.useRipgrep=e.useRipgrep??!0,this.useBuiltinRipgrep=e.useBuiltinRipgrep??!0,this.shouldUseNodePtyShell=e.shouldUseNodePtyShell??pG(),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??MVe,this.truncateToolOutputLines=e.truncateToolOutputLines??IVe,this.toolOutputBatchBudget=e.toolOutputBatchBudget??OVe,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 NB(this),this.eventEmitter=e.eventEmitter,this.arenaAgentClient=Zb.create(),this.agentsSettings=e.agents??{},this.worktreeSettings=e.worktree??{},e.contextFileName&&DB(e.contextFileName),this.modelsConfig=new $b({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&&sj(this);let o=this.getProxy();o&&(0,YA.setGlobalDispatcher)(new YA.ProxyAgent(o)),this.geminiClient=new qA(this),this.chatRecordingService=this.chatRecordingEnabled?new zd(this):void 0,this.extensionManager=new $x({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=hP(e.stopHookBlockingCap),this.userHooks=e.userHooks,this.projectHooks=e.projectHooks,this.hooks=e.hooks,this.memoryManager=new mb}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 VA,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 Cp(this),await this.hookSystem.initialize(),this.debugLogger.debug("Hook system initialized"),this.messageBus=new Q_,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 S_(this),this.skillManager=new x_(this),this.getBareMode()?await this.skillManager.refreshCache():await this.skillManager.startWatching(),this.debugLogger.debug("Skill manager initialized"),this.memoryPressureConfig=LVe(),this.memoryPressureMonitor=new bb(this,this.memoryPressureConfig),this.permissionManager=new Am(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 Wj().getInstallationId(),cR(this,new bR(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 mue.access(l)}catch{this.debugLogger.debug(`Stale worktree sweep skipped: ${l} does not exist`);return}let c=await oue(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)||TC(n)!=="connected"&&t.push(n);return t}async refreshHierarchicalMemory(e="refresh"){let{memoryContent:t,fileCount:n,conditionalRules:s,projectRoot:o}=await Ule(this.getWorkingDir(),this.getMemoryDiscoveryDirectories(),this.getFileService(),this.getExtensionContextFilePaths(),this.isTrustedFolder(),this.getImportFormat(),this.contextRuleExcludes,{explicitOnly:this.getBareMode(),loadReason:e,onInstructionsLoaded:IA(()=>this.hookSystem)});if(this.getManagedAutoMemoryEnabled()){let[a,l]=await Promise.all([OW(this.getProjectRoot()),LW().catch(()=>null)]);this.setUserMemory(this.memoryManager.appendToUserMemory(t,Ar(this.getProjectRoot()),a,{memoryDir:Gs(),indexContent:l}))}else this.setUserMemory(t);this.setGeminiMdFileCount(n),this.conditionalRulesRegistry=new X_(s,o)}buildMemoryContextWarning(e){let t=this.getContentGeneratorConfig()?.contextWindowSize??this.modelsConfig.getGenerationConfig().contextWindowSize??$p(this.getModel(),"input");if(!t||t<=0||!e)return;let n=Math.ceil(e.length/Xs),s=Math.floor(t*hue);if(!(n<=s))return`Warning: Loaded MATILDA.md/context instructions use about ${n.toLocaleString()} tokens, more than ${Math.round(hue*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 ym()?.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}=OR(this,e,this.modelsConfig.getGenerationConfig(),this.modelsConfig.getGenerationConfigSources(),{strictModelProvider:this.modelsConfig.isStrictModelProviderSelection()}),l=o;this.contentGenerator=await Ed(l,this,s?!0:t),this.contentGeneratorConfig=l,this.contentGeneratorConfigSources=a,this.baseLlmClient=new Kp(this.contentGenerator,this);let c=this.getMessageBus();!this.getDisableAllHooks()&&c&&wm(c,`Successfully authenticated with ${e}`,"auth_success","Authentication successful").catch(()=>{})}getBaseLlmClient(){if(!this.baseLlmClient)if(this.contentGenerator)this.baseLlmClient=new Kp(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??due(),hr.env&&(hr.env.MATILDA_CODE_SESSION_ID=this.sessionId),this.sessionData=t,nR(this),this.debugLogger=F(),this.chatRecordingService=this.chatRecordingEnabled?new zd(this):void 0,this.getFileReadCache().clear(),this.toolResultBudget.bytesWritten=0,this.getMemoryPressureMonitor()?.resetForNewSession(),this.fileHistoryService=void 0,ij(this.sessionId),rj(),Qs.resetInstance(),this.initialized&&cR(this,new bR(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 Kz(o),await MP(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 MP(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 ym()?.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=Ks(this.fastModel);return n?.authType?`${n.authType}:${e.modelId}`:e.modelId}resolveFastModelSelector(){if(this.fastModel)try{return Ks(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}=OR(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=Ea.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{nj()&&await oj()}}getPromptRegistry(){return this.promptRegistry}getDebugMode(){return this.debugMode}getQuestion(){return this.question}getSystemPrompt(){return this.systemPrompt}getAppendSystemPrompt(){return this.appendSystemPrompt}getCoreTools(){return this.getBareMode()?NVe: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?.()??FVe}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 rB("Cannot enable privileged approval modes in an untrusted folder.");e==="plan"&&this.approvalMode!=="plan"?(this.prePlanMode=this.approvalMode,this.planGateState=rz(++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=L0()),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??Ij}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??AR}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 bb(this,this.memoryPressureConfig)}return this.memoryPressureMonitor}getCronScheduler(){return this.cronScheduler||(this.cronScheduler=new FC(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 cv(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 jle(this.proxy)}getWorkingDir(){return this.cwd}getBugCommand(){return this.bugCommand}getFileService(){return this.fileDiscoveryService||(this.fileDiscoveryService=new yl(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=Cu.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 zd(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 hv(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 oA(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 ay),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 xC(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-LLA4WQR7.js");return new l(a)})};if(this.getBareMode())return await s(R.READ_FILE,async()=>{let{ReadFileTool:a}=await import("./read-file-HEVXSNSO.js");return new a(this)}),await s(R.EDIT,async()=>{let{EditTool:a}=await import("./edit-O5534MIA.js");return new a(this)}),await s(R.NOTEBOOK_EDIT,async()=>{let{NotebookEditTool:a}=await import("./notebook-edit-E2RFMINC.js");return new a(this)}),await s(R.SHELL,async()=>{let{ShellTool:a}=await import("./shell-LMX4PBFS.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-47TA6SG4.js");return new a(this)}),await s(R.AGENT,async()=>{let{AgentTool:a}=await import("./agent-JAZ2R5P5.js");return new a(this)}),await s(R.TASK_STOP,async()=>{let{TaskStopTool:a}=await import("./task-stop-UKRXMCZV.js");return new a(this)}),await s(R.SEND_MESSAGE,async()=>{let{SendMessageTool:a}=await import("./send-message-K3T7GVHO.js");return new a(this)}),await s(R.SKILL,async()=>{let{SkillTool:a}=await import("./skill-YXHHDMLR.js");return new a(this)}),await s(R.LS,async()=>{let{LSTool:a}=await import("./ls-4QPI2E7A.js");return new a(this)}),await s(R.READ_FILE,async()=>{let{ReadFileTool:a}=await import("./read-file-HEVXSNSO.js");return new a(this)}),this.getUseRipgrep()){let a=!1,l;try{a=await X8(this.getUseBuiltinRipgrep())}catch(c){l=Q(c)}a?await s(R.GREP,async()=>{let{RipGrepTool:c}=await import("./ripGrep-CKRSCA2H.js");return new c(this)}):(lj(this,new Ej(this.getUseRipgrep(),this.getUseBuiltinRipgrep(),l||"ripgrep is not available")),await s(R.GREP,async()=>{let{GrepTool:c}=await import("./grep-OFTEAZOC.js");return new c(this)}))}else await s(R.GREP,async()=>{let{GrepTool:a}=await import("./grep-OFTEAZOC.js");return new a(this)});if(await s(R.GLOB,async()=>{let{GlobTool:a}=await import("./glob-FWADRNRL.js");return new a(this)}),await s(R.EDIT,async()=>{let{EditTool:a}=await import("./edit-O5534MIA.js");return new a(this)}),await s(R.NOTEBOOK_EDIT,async()=>{let{NotebookEditTool:a}=await import("./notebook-edit-E2RFMINC.js");return new a(this)}),await s(R.WRITE_FILE,async()=>{let{WriteFileTool:a}=await import("./write-file-QR6KKYVC.js");return new a(this)}),await s(R.SHELL,async()=>{let{ShellTool:a}=await import("./shell-LMX4PBFS.js");return new a(this)}),await s(R.TODO_WRITE,async()=>{let{TodoWriteTool:a}=await import("./todoWrite-DKJAYA4S.js");return new a(this)}),await s(R.UPDATE_GOAL,async()=>{let{UpdateGoalTool:a}=await import("./update-goal-DH2TEYYU.js");return new a(this)}),await s(R.ASK_USER_QUESTION,async()=>{let{AskUserQuestionTool:a}=await import("./askUserQuestion-V5YLTC4J.js");return new a(this)}),this.sdkMode||(await s(R.EXIT_PLAN_MODE,async()=>{let{ExitPlanModeTool:a}=await import("./exitPlanMode-VT42OYWF.js");return new a(this)}),await s(R.ENTER_PLAN_MODE,async()=>{let{EnterPlanModeTool:a}=await import("./enterPlanMode-Z5CC6RK4.js");return new a(this)})),await s(R.ENTER_WORKTREE,async()=>{let{EnterWorktreeTool:a}=await import("./enter-worktree-NWECAVR5.js");return new a(this)}),await s(R.EXIT_WORKTREE,async()=>{let{ExitWorktreeTool:a}=await import("./exit-worktree-5QTROW2K.js");return new a(this)}),await s(R.WEB_FETCH,async()=>{let{WebFetchTool:a}=await import("./web-fetch-5F7C7MXU.js");return new a(this)}),await s(R.WEB_SEARCH,async()=>{let{WebSearchTool:a}=await import("./web-search-LUARHW3X.js");return new a(this)}),await s(R.SYMBOL_SEARCH,async()=>{let{SymbolSearchTool:a}=await import("./symbol-search-WVNUJRET.js");return new a(this)}),this.isLspEnabled()&&this.getLspClient()&&await s(R.LSP,async()=>{let{LspTool:a}=await import("./lsp-P3GKBOP3.js");return new a(this)}),await o(),this.isCronEnabled()&&(await s(R.CRON_CREATE,async()=>{let{CronCreateTool:a}=await import("./cron-create-JHL5JGIM.js");return new a(this)}),await s(R.CRON_LIST,async()=>{let{CronListTool:a}=await import("./cron-list-R3YHZBHA.js");return new a(this)}),await s(R.CRON_DELETE,async()=>{let{CronDeleteTool:a}=await import("./cron-delete-K2R3KI2W.js");return new a(this)})),this.isAgentTeamEnabled()&&(await s(R.TEAM_CREATE,async()=>{let{TeamCreateTool:a}=await import("./team-create-YCCOH5ZI.js");return new a(this)}),await s(R.TEAM_DELETE,async()=>{let{TeamDeleteTool:a}=await import("./team-delete-DEPXAMUE.js");return new a(this)}),await s(R.TASK_CREATE,async()=>{let{TaskCreateTool:a}=await import("./task-create-ZZTSVXZN.js");return new a(this)}),await s(R.TASK_UPDATE,async()=>{let{TaskUpdateTool:a}=await import("./task-update-XZWORLJB.js");return new a(this)}),await s(R.TASK_LIST,async()=>{let{TaskListTool:a}=await import("./task-list-6I64SK7E.js");return new a(this)})),this.isWorkflowsEnabled()&&await s(R.WORKFLOW,async()=>{let{WorkflowTool:a}=await import("./workflow-7JKMNIOX.js");return new a(this)}),this.isComputerUseEnabled()){let{registerComputerUseTools:a}=await import("./computer-use-BCNVOJO6.js");await a(s,this)}if(await s(R.MONITOR,async()=>{let{MonitorTool:a}=await import("./monitor-W2IPT7L4.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 $Ve="refs/notes/ai-attribution";function gue(r,e){let t=JSON.stringify(r);return Buffer.byteLength(t,"utf-8")>30720?null:{command:"git",args:["notes",`--ref=${$Ve}`,"add","-f","-m",t,e]}}var Uue=Ve(Va(),1);g();import*as yue from"node:fs";var pd=class extends Error{constructor(t,n){super(t);this.errorType=n}name="StructuredToolError"};async function wue(r,e,t,n={}){let s;try{s=await yue.promises.stat(e)}catch(d){let f=d?.code;if(f==="ENOENT"){if(n.expectExisting){let w=`File ${e} disappeared after the model read it (stat now returns ENOENT). Re-read with the ${R.READ_FILE} tool \u2014 the path may have been deleted or moved \u2014 before retrying ${t} it.`;return{ok:!1,type:"file_changed_since_read",rawMessage:w,displayMessage:`file disappeared after last read; re-run ${R.READ_FILE} first.`}}return{ok:!0}}let p=`Could not stat ${e} to verify prior read (${f??"unknown error"}). Re-read with the ${R.READ_FILE} tool, then retry ${t} it.`,y=t==="editing"?"editing this file":"overwriting this file";return{ok:!1,type:"prior_read_verification_failed",rawMessage:p,displayMessage:`cannot verify prior read of ${e}; re-run ${R.READ_FILE} before ${y}.`}}if(s.isDirectory()){let d=t==="editing"?"edit":"overwrite",f=`${e} is a directory. The Edit / WriteFile tools only operate on regular files. Use a different mechanism (e.g. the shell tool) if you need to ${d} the contents of this directory.`;return{ok:!1,type:"target_is_directory",rawMessage:f,displayMessage:`path is a directory; cannot ${d} via this tool.`}}if(!s.isFile()){let d=t==="editing"?"edit":"overwrite",f=`${e} is a FIFO / socket / character or block device. The Edit / WriteFile tools only operate on regular files; the ${R.READ_FILE} tool also rejects these targets. Use a different mechanism (e.g. shell tool with the appropriate command) if you need to ${d} this path.`;return{ok:!1,type:"edit_requires_prior_read",rawMessage:f,displayMessage:`special file; cannot ${d} 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 d=`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:d,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 d=t==="editing"?"edit":"overwrite",f=`File ${e} is a binary / image / audio / video / PDF / notebook payload that the ${R.READ_FILE} tool returns as a structured value rather than as plain text. The Edit / WriteFile tools cannot mutate that payload safely \u2014 re-reading it would not change this. If this is a Jupyter notebook (.ipynb), use the ${R.NOTEBOOK_EDIT} tool for cell-level edits after reading it. For other non-text files, use a different mechanism (e.g. shell tool with an appropriate writer) if you need to ${d} it.`;return{ok:!1,type:"edit_requires_prior_read",rawMessage:f,displayMessage:`non-text payload; cannot ${d} via this tool.`}}let a=t==="editing"?"edit":"overwrite",l=t==="editing"?"editing this file":"overwriting this file";if(t==="editing"&&n.autoStampUnread!==!1)return r.recordRead(e,s,{full:!0,cacheable:!0}),{ok:!0};let u=t==="editing"?`(a partial read with offset / limit is fine \u2014 you only need to have seen the bytes you intend to ${a})`:"(read the full file \u2014 overwriting replaces every byte, so any unseen bytes would be discarded)",h=`File ${e} has not been read in this session. Use the ${R.READ_FILE} tool first to load the current content ${u} before ${t} it.`;return{ok:!1,type:"edit_requires_prior_read",rawMessage:h,displayMessage:`${R.READ_FILE} required before ${l}.`}}g();var Sue=Ve(Va(),1);var _ue=new Set(["+","?","|","(",")","{","}"]),HVe=new Set(["*","+","?"]);function Cue(r){let e=r.trim(),t=e.match(/^\s*sed\s+/);if(!t)return null;let n;try{n=(0,Sue.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(UVe(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||BVe(l)||c.startsWith("~")||c.includes("$"))return null;let h=KVe(l);if(h===null)return null;let d={filePath:c,...h,extendedRegex:a};return jVe(d)?d:null}function UVe(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 BVe(r){return r.includes("`")||/\$(?:[A-Za-z_][A-Za-z0-9_]*|\{|\(|\d|[#?@$!*])/u.test(r)}function jVe(r){try{let e=kue(r);return zVe(e)||qVe(e)||(new RegExp(e),WVe(r.replacement,GVe(e)))?!1:!VVe(e)}catch{return!1}}function zVe(r){return/\[\[:[A-Za-z]+:\]\]/u.test(r)}function qVe(r){return/\\[<>dDwWsS]/u.test(r)}function WVe(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 GVe(r){let e=0;for(let t=0;t<r.length;t++){let n=r[t];if(n==="\\"){t++;continue}if(n==="["){t=Eue(r,t);continue}n==="("&&r[t+1]!=="?"&&e++}return e}function VVe(r){let e=[];for(let t=0;t<r.length;t++){let n=r[t];if(n==="\\"){t++;continue}if(n==="["){t=Eue(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=bue(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=bue(r,t);s!==null&&(e.length>0&&(e[e.length-1].hasQuantifier=!0),t=s-1)}return!1}function Eue(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 bue(r,e){let t=r[e];if(t===void 0)return null;if(HVe.has(t))return e+1;if(t!=="{")return null;let n=e+1,s=!1;for(;vue(r[n]);)s=!0,n++;if(!s)return null;if(r[n]===",")for(n++;vue(r[n]);)n++;return r[n]==="}"?n+1:null}function vue(r){return r!==void 0&&r>="0"&&r<="9"}function KVe(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"||!YVe(s)||JVe(n)?null:{pattern:t,replacement:n,flags:s}}function YVe(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 JVe(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 Tue(r,e){if(r.length===0)return"";let t=kue(e),n=ZVe(e.flags),s=e.flags.includes("g");try{let o=new RegExp(t,"g"),a=r.split(/(\n)/);return(r.endsWith(`
2162
+ `),RVe.warn(t),{...GA}}return r}function tB(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 NVe=[R.READ_FILE,R.EDIT,R.NOTEBOOK_EDIT,R.SHELL],FVe=Object.freeze(new Set),pue=!1,cp=class{sessionId;sessionData;pendingStartupWorktreeNotice=null;debugLogger;toolRegistry;pendingMcpBudgetCallback;promptRegistry;subagentManager;memoryPressureConfig;memoryPressureMonitor;backgroundTaskRegistry=new sA;monitorRegistry=new FE;backgroundAgentResumeService;backgroundShellRegistry=new $E;workflowRunRegistry=new HE;fileReadCache=new ay;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=Pm();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??due(),!pue&&hr.env&&(hr.env.MATILDA_CODE_SESSION_ID=this.sessionId,pue=!0),this.sessionData=e.sessionData,nR(this),this.debugLogger=F(),this.embeddingModel=e.embeddingModel??RR,this.fileSystemService=new oE,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 Ea(this.targetDir,this.explicitIncludeDirectories),this.debugMode=e.debugMode,this.inputFormat=e.inputFormat??"text";let t=DVe(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??AR,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={...PVe(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??5;this.clearContextOnIdle={toolResultsThresholdMinutes:s,toolResultsNumToKeep:n?.toolResultsNumToKeep??5,toolResultsTotalCharsThreshold:n?.toolResultsTotalCharsThreshold??((n?.toolResultsThresholdMinutes??0)<0?-1:5e5)},this.sessionTokenLimit=e.sessionTokenLimit??-1,this.experimentalZedIntegration=e.experimentalZedIntegration??!1,this.cronEnabled=e.cronEnabled??!0,this.agentTeamEnabled=e.agentTeamEnabled??!1,this.workflowsEnabled=e.workflowsEnabled??!1,this.computerUseEnabled=e.computerUseEnabled??!0,this.computerUseMaxImageDimension=e.computerUseMaxImageDimension,this.emitToolUseSummaries=e.emitToolUseSummaries??!0,this.listExtensions=e.listExtensions??!1,this.overrideExtensions=e.overrideExtensions,this.noBrowser=e.noBrowser??!1,this.folderTrustFeature=e.folderTrustFeature??!1,this.folderTrust=e.folderTrust??!1,this.ideMode=e.ideMode??!1,this.modelProvidersConfig=e.modelProvidersConfig,this.cliVersion=e.cliVersion,this.chatRecordingEnabled=e.chatRecording??!0,this.loadMemoryFromIncludeDirectories=e.loadMemoryFromIncludeDirectories??!1,this.importFormat=e.importFormat??"tree",this.chatCompression=e.chatCompression,this.interactive=e.interactive??!1,this.trustedFolder=e.trustedFolder,this.skipLoopDetection=e.skipLoopDetection??!1,this.skipStartupContext=e.skipStartupContext??!1,this.bareMode=e.bareMode??!1,this.warnings=e.warnings??[],this.addLegacyPlanLocationWarning(),this.allowedHttpHookUrls=e.allowedHttpHookUrls??[],this.onPersistPermissionRuleCallback=e.onPersistPermissionRule,this.useRipgrep=e.useRipgrep??!0,this.useBuiltinRipgrep=e.useBuiltinRipgrep??!0,this.shouldUseNodePtyShell=e.shouldUseNodePtyShell??pG(),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??MVe,this.truncateToolOutputLines=e.truncateToolOutputLines??IVe,this.toolOutputBatchBudget=e.toolOutputBatchBudget??OVe,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 NB(this),this.eventEmitter=e.eventEmitter,this.arenaAgentClient=Zb.create(),this.agentsSettings=e.agents??{},this.worktreeSettings=e.worktree??{},e.contextFileName&&DB(e.contextFileName),this.modelsConfig=new $b({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&&sj(this);let o=this.getProxy();o&&(0,YA.setGlobalDispatcher)(new YA.ProxyAgent(o)),this.geminiClient=new qA(this),this.chatRecordingService=this.chatRecordingEnabled?new zd(this):void 0,this.extensionManager=new $x({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=hP(e.stopHookBlockingCap),this.userHooks=e.userHooks,this.projectHooks=e.projectHooks,this.hooks=e.hooks,this.memoryManager=new mb}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 VA,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 Cp(this),await this.hookSystem.initialize(),this.debugLogger.debug("Hook system initialized"),this.messageBus=new Q_,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 S_(this),this.skillManager=new x_(this),this.getBareMode()?await this.skillManager.refreshCache():await this.skillManager.startWatching(),this.debugLogger.debug("Skill manager initialized"),this.memoryPressureConfig=LVe(),this.memoryPressureMonitor=new bb(this,this.memoryPressureConfig),this.permissionManager=new Am(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 Wj().getInstallationId(),cR(this,new bR(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 mue.access(l)}catch{this.debugLogger.debug(`Stale worktree sweep skipped: ${l} does not exist`);return}let c=await oue(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)||TC(n)!=="connected"&&t.push(n);return t}async refreshHierarchicalMemory(e="refresh"){let{memoryContent:t,fileCount:n,conditionalRules:s,projectRoot:o}=await Ule(this.getWorkingDir(),this.getMemoryDiscoveryDirectories(),this.getFileService(),this.getExtensionContextFilePaths(),this.isTrustedFolder(),this.getImportFormat(),this.contextRuleExcludes,{explicitOnly:this.getBareMode(),loadReason:e,onInstructionsLoaded:IA(()=>this.hookSystem)});if(this.getManagedAutoMemoryEnabled()){let[a,l]=await Promise.all([OW(this.getProjectRoot()),LW().catch(()=>null)]);this.setUserMemory(this.memoryManager.appendToUserMemory(t,Ar(this.getProjectRoot()),a,{memoryDir:Gs(),indexContent:l}))}else this.setUserMemory(t);this.setGeminiMdFileCount(n),this.conditionalRulesRegistry=new X_(s,o)}buildMemoryContextWarning(e){let t=this.getContentGeneratorConfig()?.contextWindowSize??this.modelsConfig.getGenerationConfig().contextWindowSize??$p(this.getModel(),"input");if(!t||t<=0||!e)return;let n=Math.ceil(e.length/Xs),s=Math.floor(t*hue);if(!(n<=s))return`Warning: Loaded MATILDA.md/context instructions use about ${n.toLocaleString()} tokens, more than ${Math.round(hue*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 ym()?.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}=OR(this,e,this.modelsConfig.getGenerationConfig(),this.modelsConfig.getGenerationConfigSources(),{strictModelProvider:this.modelsConfig.isStrictModelProviderSelection()}),l=o;this.contentGenerator=await Ed(l,this,s?!0:t),this.contentGeneratorConfig=l,this.contentGeneratorConfigSources=a,this.baseLlmClient=new Kp(this.contentGenerator,this);let c=this.getMessageBus();!this.getDisableAllHooks()&&c&&wm(c,`Successfully authenticated with ${e}`,"auth_success","Authentication successful").catch(()=>{})}getBaseLlmClient(){if(!this.baseLlmClient)if(this.contentGenerator)this.baseLlmClient=new Kp(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??due(),hr.env&&(hr.env.MATILDA_CODE_SESSION_ID=this.sessionId),this.sessionData=t,nR(this),this.debugLogger=F(),this.chatRecordingService=this.chatRecordingEnabled?new zd(this):void 0,this.getFileReadCache().clear(),this.toolResultBudget.bytesWritten=0,this.getMemoryPressureMonitor()?.resetForNewSession(),this.fileHistoryService=void 0,ij(this.sessionId),rj(),Qs.resetInstance(),this.initialized&&cR(this,new bR(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 Kz(o),await MP(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 MP(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 ym()?.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=Ks(this.fastModel);return n?.authType?`${n.authType}:${e.modelId}`:e.modelId}resolveFastModelSelector(){if(this.fastModel)try{return Ks(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}=OR(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=Ea.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{nj()&&await oj()}}getPromptRegistry(){return this.promptRegistry}getDebugMode(){return this.debugMode}getQuestion(){return this.question}getSystemPrompt(){return this.systemPrompt}getAppendSystemPrompt(){return this.appendSystemPrompt}getCoreTools(){return this.getBareMode()?NVe: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?.()??FVe}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 rB("Cannot enable privileged approval modes in an untrusted folder.");e==="plan"&&this.approvalMode!=="plan"?(this.prePlanMode=this.approvalMode,this.planGateState=rz(++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=L0()),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??Ij}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??AR}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 bb(this,this.memoryPressureConfig)}return this.memoryPressureMonitor}getCronScheduler(){return this.cronScheduler||(this.cronScheduler=new FC(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 cv(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 jle(this.proxy)}getWorkingDir(){return this.cwd}getBugCommand(){return this.bugCommand}getFileService(){return this.fileDiscoveryService||(this.fileDiscoveryService=new yl(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=Cu.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 zd(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 hv(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 oA(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 ay),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 xC(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-LLA4WQR7.js");return new l(a)})};if(this.getBareMode())return await s(R.READ_FILE,async()=>{let{ReadFileTool:a}=await import("./read-file-HEVXSNSO.js");return new a(this)}),await s(R.EDIT,async()=>{let{EditTool:a}=await import("./edit-B5KZGY7B.js");return new a(this)}),await s(R.NOTEBOOK_EDIT,async()=>{let{NotebookEditTool:a}=await import("./notebook-edit-7BJPP7ZB.js");return new a(this)}),await s(R.SHELL,async()=>{let{ShellTool:a}=await import("./shell-4HTE526K.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-47TA6SG4.js");return new a(this)}),await s(R.AGENT,async()=>{let{AgentTool:a}=await import("./agent-2NBSL6Q2.js");return new a(this)}),await s(R.TASK_STOP,async()=>{let{TaskStopTool:a}=await import("./task-stop-UKRXMCZV.js");return new a(this)}),await s(R.SEND_MESSAGE,async()=>{let{SendMessageTool:a}=await import("./send-message-K3T7GVHO.js");return new a(this)}),await s(R.SKILL,async()=>{let{SkillTool:a}=await import("./skill-YXHHDMLR.js");return new a(this)}),await s(R.LS,async()=>{let{LSTool:a}=await import("./ls-4QPI2E7A.js");return new a(this)}),await s(R.READ_FILE,async()=>{let{ReadFileTool:a}=await import("./read-file-HEVXSNSO.js");return new a(this)}),this.getUseRipgrep()){let a=!1,l;try{a=await X8(this.getUseBuiltinRipgrep())}catch(c){l=Q(c)}a?await s(R.GREP,async()=>{let{RipGrepTool:c}=await import("./ripGrep-G3IY6ZWZ.js");return new c(this)}):(lj(this,new Ej(this.getUseRipgrep(),this.getUseBuiltinRipgrep(),l||"ripgrep is not available")),await s(R.GREP,async()=>{let{GrepTool:c}=await import("./grep-B2OXQK7Q.js");return new c(this)}))}else await s(R.GREP,async()=>{let{GrepTool:a}=await import("./grep-B2OXQK7Q.js");return new a(this)});if(await s(R.GLOB,async()=>{let{GlobTool:a}=await import("./glob-PXQT4CHI.js");return new a(this)}),await s(R.EDIT,async()=>{let{EditTool:a}=await import("./edit-B5KZGY7B.js");return new a(this)}),await s(R.NOTEBOOK_EDIT,async()=>{let{NotebookEditTool:a}=await import("./notebook-edit-7BJPP7ZB.js");return new a(this)}),await s(R.WRITE_FILE,async()=>{let{WriteFileTool:a}=await import("./write-file-2PLDMI5M.js");return new a(this)}),await s(R.SHELL,async()=>{let{ShellTool:a}=await import("./shell-4HTE526K.js");return new a(this)}),await s(R.TODO_WRITE,async()=>{let{TodoWriteTool:a}=await import("./todoWrite-DKJAYA4S.js");return new a(this)}),await s(R.UPDATE_GOAL,async()=>{let{UpdateGoalTool:a}=await import("./update-goal-DH2TEYYU.js");return new a(this)}),await s(R.ASK_USER_QUESTION,async()=>{let{AskUserQuestionTool:a}=await import("./askUserQuestion-V5YLTC4J.js");return new a(this)}),this.sdkMode||(await s(R.EXIT_PLAN_MODE,async()=>{let{ExitPlanModeTool:a}=await import("./exitPlanMode-K7HACJ6K.js");return new a(this)}),await s(R.ENTER_PLAN_MODE,async()=>{let{EnterPlanModeTool:a}=await import("./enterPlanMode-ZPXWNPYM.js");return new a(this)})),await s(R.ENTER_WORKTREE,async()=>{let{EnterWorktreeTool:a}=await import("./enter-worktree-RRN3GMRW.js");return new a(this)}),await s(R.EXIT_WORKTREE,async()=>{let{ExitWorktreeTool:a}=await import("./exit-worktree-HND5ZVDQ.js");return new a(this)}),await s(R.WEB_FETCH,async()=>{let{WebFetchTool:a}=await import("./web-fetch-5F7C7MXU.js");return new a(this)}),await s(R.WEB_SEARCH,async()=>{let{WebSearchTool:a}=await import("./web-search-FEZM3B3R.js");return new a(this)}),await s(R.SYMBOL_SEARCH,async()=>{let{SymbolSearchTool:a}=await import("./symbol-search-WVNUJRET.js");return new a(this)}),this.isLspEnabled()&&this.getLspClient()&&await s(R.LSP,async()=>{let{LspTool:a}=await import("./lsp-P3GKBOP3.js");return new a(this)}),await o(),this.isCronEnabled()&&(await s(R.CRON_CREATE,async()=>{let{CronCreateTool:a}=await import("./cron-create-JHL5JGIM.js");return new a(this)}),await s(R.CRON_LIST,async()=>{let{CronListTool:a}=await import("./cron-list-R3YHZBHA.js");return new a(this)}),await s(R.CRON_DELETE,async()=>{let{CronDeleteTool:a}=await import("./cron-delete-K2R3KI2W.js");return new a(this)})),this.isAgentTeamEnabled()&&(await s(R.TEAM_CREATE,async()=>{let{TeamCreateTool:a}=await import("./team-create-VWJKHFTR.js");return new a(this)}),await s(R.TEAM_DELETE,async()=>{let{TeamDeleteTool:a}=await import("./team-delete-DEPXAMUE.js");return new a(this)}),await s(R.TASK_CREATE,async()=>{let{TaskCreateTool:a}=await import("./task-create-ZZTSVXZN.js");return new a(this)}),await s(R.TASK_UPDATE,async()=>{let{TaskUpdateTool:a}=await import("./task-update-XZWORLJB.js");return new a(this)}),await s(R.TASK_LIST,async()=>{let{TaskListTool:a}=await import("./task-list-6I64SK7E.js");return new a(this)})),this.isWorkflowsEnabled()&&await s(R.WORKFLOW,async()=>{let{WorkflowTool:a}=await import("./workflow-GNYDTGHJ.js");return new a(this)}),this.isComputerUseEnabled()){let{registerComputerUseTools:a}=await import("./computer-use-7PIVVKPK.js");await a(s,this)}if(await s(R.MONITOR,async()=>{let{MonitorTool:a}=await import("./monitor-6AWWXDIL.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 $Ve="refs/notes/ai-attribution";function gue(r,e){let t=JSON.stringify(r);return Buffer.byteLength(t,"utf-8")>30720?null:{command:"git",args:["notes",`--ref=${$Ve}`,"add","-f","-m",t,e]}}var Uue=Ve(Va(),1);g();import*as yue from"node:fs";var pd=class extends Error{constructor(t,n){super(t);this.errorType=n}name="StructuredToolError"};async function wue(r,e,t,n={}){let s;try{s=await yue.promises.stat(e)}catch(d){let f=d?.code;if(f==="ENOENT"){if(n.expectExisting){let w=`File ${e} disappeared after the model read it (stat now returns ENOENT). Re-read with the ${R.READ_FILE} tool \u2014 the path may have been deleted or moved \u2014 before retrying ${t} it.`;return{ok:!1,type:"file_changed_since_read",rawMessage:w,displayMessage:`file disappeared after last read; re-run ${R.READ_FILE} first.`}}return{ok:!0}}let p=`Could not stat ${e} to verify prior read (${f??"unknown error"}). Re-read with the ${R.READ_FILE} tool, then retry ${t} it.`,y=t==="editing"?"editing this file":"overwriting this file";return{ok:!1,type:"prior_read_verification_failed",rawMessage:p,displayMessage:`cannot verify prior read of ${e}; re-run ${R.READ_FILE} before ${y}.`}}if(s.isDirectory()){let d=t==="editing"?"edit":"overwrite",f=`${e} is a directory. The Edit / WriteFile tools only operate on regular files. Use a different mechanism (e.g. the shell tool) if you need to ${d} the contents of this directory.`;return{ok:!1,type:"target_is_directory",rawMessage:f,displayMessage:`path is a directory; cannot ${d} via this tool.`}}if(!s.isFile()){let d=t==="editing"?"edit":"overwrite",f=`${e} is a FIFO / socket / character or block device. The Edit / WriteFile tools only operate on regular files; the ${R.READ_FILE} tool also rejects these targets. Use a different mechanism (e.g. shell tool with the appropriate command) if you need to ${d} this path.`;return{ok:!1,type:"edit_requires_prior_read",rawMessage:f,displayMessage:`special file; cannot ${d} 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 d=`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:d,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 d=t==="editing"?"edit":"overwrite",f=`File ${e} is a binary / image / audio / video / PDF / notebook payload that the ${R.READ_FILE} tool returns as a structured value rather than as plain text. The Edit / WriteFile tools cannot mutate that payload safely \u2014 re-reading it would not change this. If this is a Jupyter notebook (.ipynb), use the ${R.NOTEBOOK_EDIT} tool for cell-level edits after reading it. For other non-text files, use a different mechanism (e.g. shell tool with an appropriate writer) if you need to ${d} it.`;return{ok:!1,type:"edit_requires_prior_read",rawMessage:f,displayMessage:`non-text payload; cannot ${d} via this tool.`}}let a=t==="editing"?"edit":"overwrite",l=t==="editing"?"editing this file":"overwriting this file";if(t==="editing"&&n.autoStampUnread!==!1)return r.recordRead(e,s,{full:!0,cacheable:!0}),{ok:!0};let u=t==="editing"?`(a partial read with offset / limit is fine \u2014 you only need to have seen the bytes you intend to ${a})`:"(read the full file \u2014 overwriting replaces every byte, so any unseen bytes would be discarded)",h=`File ${e} has not been read in this session. Use the ${R.READ_FILE} tool first to load the current content ${u} before ${t} it.`;return{ok:!1,type:"edit_requires_prior_read",rawMessage:h,displayMessage:`${R.READ_FILE} required before ${l}.`}}g();var Sue=Ve(Va(),1);var _ue=new Set(["+","?","|","(",")","{","}"]),HVe=new Set(["*","+","?"]);function Cue(r){let e=r.trim(),t=e.match(/^\s*sed\s+/);if(!t)return null;let n;try{n=(0,Sue.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(UVe(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||BVe(l)||c.startsWith("~")||c.includes("$"))return null;let h=KVe(l);if(h===null)return null;let d={filePath:c,...h,extendedRegex:a};return jVe(d)?d:null}function UVe(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 BVe(r){return r.includes("`")||/\$(?:[A-Za-z_][A-Za-z0-9_]*|\{|\(|\d|[#?@$!*])/u.test(r)}function jVe(r){try{let e=kue(r);return zVe(e)||qVe(e)||(new RegExp(e),WVe(r.replacement,GVe(e)))?!1:!VVe(e)}catch{return!1}}function zVe(r){return/\[\[:[A-Za-z]+:\]\]/u.test(r)}function qVe(r){return/\\[<>dDwWsS]/u.test(r)}function WVe(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 GVe(r){let e=0;for(let t=0;t<r.length;t++){let n=r[t];if(n==="\\"){t++;continue}if(n==="["){t=Eue(r,t);continue}n==="("&&r[t+1]!=="?"&&e++}return e}function VVe(r){let e=[];for(let t=0;t<r.length;t++){let n=r[t];if(n==="\\"){t++;continue}if(n==="["){t=Eue(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=bue(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=bue(r,t);s!==null&&(e.length>0&&(e[e.length-1].hasQuantifier=!0),t=s-1)}return!1}function Eue(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 bue(r,e){let t=r[e];if(t===void 0)return null;if(HVe.has(t))return e+1;if(t!=="{")return null;let n=e+1,s=!1;for(;vue(r[n]);)s=!0,n++;if(!s)return null;if(r[n]===",")for(n++;vue(r[n]);)n++;return r[n]==="}"?n+1:null}function vue(r){return r!==void 0&&r>="0"&&r<="9"}function KVe(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"||!YVe(s)||JVe(n)?null:{pattern:t,replacement:n,flags:s}}function YVe(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 JVe(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 Tue(r,e){if(r.length===0)return"";let t=kue(e),n=ZVe(e.flags),s=e.flags.includes("g");try{let o=new RegExp(t,"g"),a=r.split(/(\n)/);return(r.endsWith(`
2163
2163
  `)?a.slice(0,-1):a).map((c,u)=>u%2===1?c:QVe(c,o,e.replacement,{occurrence:n,replaceAll:s})).join("")}catch(o){throw new Error(`sed pattern simulation failed: ${Q(o)}`)}}function kue(r){let e=XVe(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 XVe(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 ZVe(r){let e=r.match(/[1-9][0-9]*/);return e?Number(e[0]):null}function QVe(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 e8e(c,d,t)})}function e8e(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 t8e(r){let e=r.trimEnd();return!e.endsWith("&")||e.endsWith("&&")||e.endsWith("\\&")?r:e.slice(0,-1).trimEnd()}function Aue(r){return r.replace(/[\\"$`]/g,"\\$&")}function Rue(r){return r.replace(/'/g,"'\\''")}function JA(r){let e=null;for(let t of r)e=t;return e}function Pue(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 Mue(r){return r?{start:r.index??0,end:(r.index??0)+r[0].length}:null}function Iue(r,e){let t=Mue(r),n=Mue(e);return!!(t&&n&&t.start>=n.start&&t.end<=n.end)}function Oue(r,e){return r&&e?Iue(e,r)?{match:r,isDouble:!0}:Iue(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 ZA(r){let e;try{e=(0,Uue.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=Lue(e[t]);if(n===null)break;if(Due.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"?s8e:n==="sudo"?i8e:null;if(o&&o8e(s,o))return null;(n==="sudo"&&r8e.has(s)||n==="env"&&n8e.has(s))&&t<e.length&&t++}if(n==="env")for(;t<e.length;){let s=Lue(e[t]);if(s===null)break;if(Due.has(s))return null;t++}}return e.slice(t)}var r8e=new Set(["-u","-g","-h","-D","-r","-t","-C","--user","--group","--host","--chdir","--role","--type"]),n8e=new Set(["-u","--unset","-S","--split-string"]),s8e=new Set(["-C","--chdir"]),i8e=new Set(["-D","--chdir"]);function o8e(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 Due=new Set(["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"]);function Lue(r){let e=/^([A-Za-z_][A-Za-z0-9_]*)=/.exec(r);return e?e[1]:null}var a8e=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--exec-path","--config-env","--super-prefix","--list-cmds"]),l8e=new Set(["-C","--git-dir","--work-tree"]);function Nue(r){let e=r.trim();return e==="."||e==="./"}function oB(r){let e=1,t=!1;for(;e<r.length;){let n=r[e];if(a8e.has(n)){let s=r[e+1]??"";n==="-C"?Nue(s)||(t=!0):l8e.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);Nue(s)||(t=!0),e++;continue}if(n.startsWith("-")){e++;continue}return{subcommand:n,changesCwd:t}}return{subcommand:void 0,changesCwd:t}}function Fue(r){let e=!1,t=!1,n=!1;for(let s of Ni(r)){let o=ZA(s);if(!o||o.length===0)continue;let a=o[0];if(a==="cd"||a==="pushd"){!e&&aB(o)&&(n=!0);continue}if(a==="popd"){e||(n=!0);continue}if(a==="git"){let{subcommand:l,changesCwd:c}=oB(o);l==="commit"?(e=!0,!n&&!c&&(t=!0)):c&&!e&&(n=!0)}}return{hasCommit:e,attributableInCwd:t}}var c8e=new Set(["--repo","-R","--hostname"]);function u8e(r){let e=1;for(;e<r.length;){let t=r[e];if(c8e.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 aB(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 d8e(r){let e=!1;for(let t of Ni(r)){let n=ZA(t);if(!n||n.length===0)continue;let s=n[0];if(s==="cd"||s==="pushd"){!e&&aB(n)&&(e=!0);continue}if(s==="popd"){e=!0;continue}if(s!=="git")continue;let{subcommand:o,changesCwd:a}=oB(n);if(o==="commit"&&!e&&!a)return n.includes("--amend")||n.some(l=>l.startsWith("--amend="));a&&!e&&(e=!0)}return!1}function h8e(r){let e=0,t=!1;for(let n of Ni(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=ZA(n);if(!a||a.length===0)continue;let l=a[0];if(l==="cd"||l==="pushd"){!t&&aB(a)&&(t=!0);continue}if(l==="popd"){t=!0;continue}if(l==="git"){let{subcommand:c,changesCwd:u}=oB(a);if(c==="commit"&&!t&&!u)return{start:s,end:o};u&&!t&&(t=!0)}}return null}function f8e(r){let e=0;for(let t of Ni(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=ZA(t);if(!o||o[0]!=="gh")continue;let a=u8e(o);if(a[0]==="pr"&&(a[1]==="create"||a[1]==="new"))return{start:n,end:s}}return null}var p8e=40,m8e=1024;function g8e(r){let e=new Map,t=r.split(`
2164
2164
  `).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,m8e);continue}let l=parseInt(o[1],10),c=parseInt(o[2],10);Number.isNaN(l)||Number.isNaN(c)||e.set(a,(l+c)*p8e)}return e}var nB=1e3,y8e=12e4,w8e=200,$ue=1e4,_8e=1e3;function b8e(r){return Math.max(_8e,Math.floor(r/2))}function v8e(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 q4t(r){return Bue(r)?.description??null}function Bue(r){let{command:e,comment:t}=zue(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])&&![";","&","|",`
2165
2165
  `].includes(s[o]);)o++;let l=s.slice(a,o),c=T8e(l);if(c===null||c<2)return null;let u=s.slice(o),h=k8e(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(jue)){let w=E8e(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>S8e?{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 jue="intentional-sleep:",S8e=10*60,C8e=8;function E8e(r){let e=r.slice(jue.length).trim();return e.length>=C8e?e:null}function T8e(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 k8e(r){let e=0;for(;e<r.length&&r[e]!==`