@maincode-ai/matilda-code 0.20.4 → 0.20.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/chunks/{agent-HKV5XQAS.js → agent-HSHZY2QX.js} +1 -1
- package/chunks/{agent-headless-QT5CMLXY.js → agent-headless-EWZCSQN6.js} +1 -1
- package/chunks/{chunk-JHODF4MD.js → chunk-DYGICU2T.js} +1 -1
- package/chunks/{chunk-PTTKY4W4.js → chunk-GGP2HLPI.js} +2 -2
- package/chunks/{chunk-MPXE4ICG.js → chunk-H4N4VFUI.js} +1 -1
- package/chunks/{chunk-NCK377X6.js → chunk-KXVDX2LL.js} +2 -2
- package/chunks/{chunk-BAFQ36AO.js → chunk-OBPA6QHH.js} +1 -1
- package/chunks/{chunk-67UAAXGB.js → chunk-RLPVQ5SY.js} +1 -1
- package/chunks/{computer-use-Z4JLQKGC.js → computer-use-E54F2OXO.js} +1 -1
- package/chunks/{contextCommand-B2LYSU5N.js → contextCommand-6MJYOUNZ.js} +1 -1
- package/chunks/{edit-C4NER5YK.js → edit-ECFAMGBL.js} +1 -1
- package/chunks/{enter-worktree-4LCYUYYU.js → enter-worktree-C3HT4E6R.js} +1 -1
- package/chunks/{enterPlanMode-L74GNCED.js → enterPlanMode-HJDOWUYD.js} +1 -1
- package/chunks/{exit-worktree-GASDDIUP.js → exit-worktree-GYSJXOUF.js} +1 -1
- package/chunks/{exitPlanMode-D5SNMRGJ.js → exitPlanMode-OCEXPM5C.js} +1 -1
- package/chunks/{geminiContentGenerator-JRTWRQNL.js → geminiContentGenerator-EY3QPS5X.js} +1 -1
- package/chunks/{glob-MDLZ74XZ.js → glob-42PS64FP.js} +1 -1
- package/chunks/{grep-QMU4OMPK.js → grep-6J5W5EJ7.js} +1 -1
- package/chunks/{matildaAgentContentGenerator-ZXRXBMQP.js → matildaAgentContentGenerator-JEQ27NF6.js} +1 -1
- package/chunks/{matildaContentGenerator-TUSXZGC2.js → matildaContentGenerator-5FZK7UTU.js} +1 -1
- package/chunks/{monitor-DOIBVKS6.js → monitor-JGJ5W74B.js} +1 -1
- package/chunks/{notebook-edit-3SYYLOZB.js → notebook-edit-K3O75JIG.js} +1 -1
- package/chunks/{openaiContentGenerator-SSKBJCPU.js → openaiContentGenerator-32LD27RZ.js} +1 -1
- package/chunks/{ripGrep-FGPUVH6Z.js → ripGrep-2ZK4OFYZ.js} +1 -1
- package/chunks/{scheduler-PFW7Z4IZ.js → scheduler-WNS7XXCZ.js} +1 -1
- package/chunks/{serve-U64D74QQ.js → serve-72ANQDL6.js} +1 -1
- package/chunks/{shell-KW3VBBYV.js → shell-Z6CWCFSW.js} +1 -1
- package/chunks/{src-HES7P35D.js → src-PP2X6HOA.js} +1 -1
- package/chunks/{team-create-4JLJ6GQN.js → team-create-TV7R2OKS.js} +1 -1
- package/chunks/{workflow-ODYOFAKB.js → workflow-IV7OR3QI.js} +2 -2
- package/chunks/{write-file-S7CRH7VA.js → write-file-D7TUBP7Q.js} +1 -1
- package/cli.js +390 -390
- 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 o2,c as $R,d as a2,e as U,f as l2,g as Ye,h as vt,i as c2,j as u2,k as Zt,l as se,m as oe,n as fr,o as Lt,p as UR,q as HR,r as Et,s as zn,t as ue,u as Vt,v as d2,w as BR,x as h2,y as f2}from"./chunk-TZIDSCTF.js";import{d as y2,e as w2,g as E2,h as T2,i as k2,j as jR,m as x2}from"./chunk-FUNLOUYI.js";import{d as A2,k as zR,n as R2,p as P2}from"./chunk-R3H6IWFK.js";import{g as _2,h as b2,i as v2,m as Up,n as S2,p as C2}from"./chunk-OMZ5SGMK.js";import{a as Bt}from"./chunk-GIIMOLLN.js";import{a as Ub,b as m2,d as VR,e as jb}from"./chunk-RBG4ERTN.js";import{a as M2,b as I2,c as Hp}from"./chunk-TXMXCR7D.js";import{a as qR}from"./chunk-YULUB745.js";import{a as O2,b as D2,c as L2,d as WR,e as N2,f as GR}from"./chunk-LQWORCPO.js";import{a as s2,b as $b,c as i2}from"./chunk-TISQNFB5.js";import{a as Di,b as NR,c as Ed,s as FR}from"./chunk-SS5WUOSJ.js";import{a as Bb,b as Bp}from"./chunk-QEI3OETI.js";import{b as p2,g as Hb,j as $p,k as g2,l as vs}from"./chunk-QKYGQLWC.js";import{a as et,b as Td,d as xd,e as Ad}from"./chunk-MNGFXISD.js";import{b as Ro,d as Kj,f as Yj,i as ot,j as Jj,k as Xj,l as Zj,m as Qj,n as e2,o as t2,p as r2,q as n2}from"./chunk-4R2OFVPK.js";import{b as kd}from"./chunk-RNKDFE2S.js";import{a as Vj}from"./chunk-EMWHQSMS.js";import{a as dB}from"./chunk-S4K76QPI.js";import{B as nn,C as LR,F as Cd,g as $j,j as vc,k as Fp,l as OR,n as DR,q as Fb}from"./chunk-67UAAXGB.js";import{a as xo,c as MR}from"./chunk-4F4DA5UI.js";import{e as IR}from"./chunk-DC7LAFZZ.js";import{D as PR,E as Dj}from"./chunk-2XZIKUB6.js";import{h as vd,k as Nj,m as Fj,q as Np}from"./chunk-XYA3SFGC.js";import{a as PB,b as Ia,c as Gs,d as MB,f as IB}from"./chunk-4J6DC24J.js";import{a as Lj,g as Hj,h as Bj,k as Sd,l as jj,m as zj}from"./chunk-XJDC3ZQZ.js";import{$a as xb,$b as fj,$c as CR,Ab as sj,Ac as bR,B as $B,Bb as ij,Bc as vR,Cb as oj,Cc as ko,Db as aj,Eb as lj,Ec as SR,F as wd,G as UB,Gb as dR,Ha as jB,Ic as Ej,Jb as cj,Mc as Tj,Ob as uj,Oc as kj,Qc as bd,Rc as xj,Sb as _d,Sc as Aj,Tb as dj,Ub as hj,Va as zB,Vc as Ob,Yb as Rb,Za as qB,_a as La,_b as hR,aa as HB,ab as WB,ac as yc,ad as bc,bb as GB,bc as fR,bd as Rj,cb as rn,cd as Db,d as CB,da as Da,dc as pj,ec as pR,ed as ER,f as To,fc as mj,fd as TR,g as RB,ga as Ip,gb as cR,gc as mR,gd as kR,h as jn,ha as kb,hb as VB,hc as gR,i as Oa,ib as KB,ic as yR,id as xR,jb as YB,k as OB,kb as uR,kd as Pj,l as DB,lb as JB,m as LB,mb as XB,mc as gj,nb as ZB,nc as yj,ob as QB,oc as wj,od as Mj,p as mc,pb as ej,pd as Ij,q as Mp,qb as tj,qd as Oj,r as NB,rb as rj,rc as wR,rd as AR,s as FB,sb as nj,sc as Pb,t as gc,tc as Mb,uc as bj,ud as RR,vb as Ab,vc as vj,vd as Lb,wd as Nb,xc as _R,ya as lR,yc as Lp,za as BB,zc as Sj}from"./chunk-CFBZKYFB.js";import{b as Oi,h as Ar,k as _j,l as wc,m as Rr,n as _c,o as Op,s as Vs,t as Dp,w as Ib}from"./chunk-UY2R3ZQ4.js";import{a as Cj}from"./chunk-NDR7ZFUA.js";import{b as EB,c as nde,d as sde,e as TB,f as kB,g as qs,i as Ws,j as xB,k as oR,o as AB,p as A,q as vn,r as Eb,s as Tb}from"./chunk-5U3A6KMU.js";import{a as Gj}from"./chunk-IMYUVCF7.js";import{a as qj,b as Ao,c as Wj}from"./chunk-ESSYHTAZ.js";import{b as Uj}from"./chunk-3YLXGE6T.js";import{b as Ke,c as bs,e as Cb}from"./chunk-IOCF4XSR.js";import{A as mB,C as zs,D as yd,F as pc,G as gB,J as nR,K as sR,L as fe,Q as bB,R as vB,T as SB,W as iR,Y as F,a as Rt,b as vb,c as Q,d as Eo,p as hB,r as fB,s as tn,w as gd,z as pB}from"./chunk-QWBNNEV2.js";import{a as aR}from"./chunk-G7R2XEEF.js";import{g as Sb,h as yB,l as wB,n as _B}from"./chunk-FWDMPRKU.js";import{a as __matilda_dirname,b as g}from"./chunk-GZPNIYVZ.js";import{a as be,c as tde,d as L,e as rde,f as Ve}from"./chunk-OWGSC52X.js";var zW=L((UJe,jW)=>{"use strict";g();jW.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 JW=L((BJe,YW)=>{"use strict";g();var KW="(?:"+["\\|\\|","\\&\\&",";;","\\|\\&","\\<\\(","\\<\\<\\<",">>",">\\&","<\\&","[&;()|<>]"].join("|")+")",qW=new RegExp("^"+KW+"$"),WW="|&;()<> \\t",ege='"((\\\\"|[^"])*?)"',tge="'((\\\\'|[^'])*?)'",rge=/^#$/,GW="'",VW='"',f0="$",$c="",nge=4294967296;for(p0=0;p0<4;p0++)$c+=(nge*Math.random()).toString(16);var p0,sge=new RegExp("^"+$c);function ige(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 oge(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 age(r,e,t){t||(t={});var n=t.escape||"\\",s="(\\"+n+`['"`+WW+`]|[^\\s'"`+WW+"])+",o=new RegExp(["("+KW+")","("+s+"|"+ege+"|"+tge+")+"].join("|"),"g"),a=ige(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(qW.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 oge(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==GW?f+=m:m===n?(y+=1,m=u.charAt(y),m===VW||m===n||m===f0?f+=m:f+=n+m):m===f0?f+=w():f+=m;else if(m===VW||m===GW)h=m;else{if(qW.test(m))return{op:u};if(rge.test(m)){l=!0;var _={comment:r.slice(c.index+y+1)};return f.length?[f,_]:[_]}else m===n?d=!0:m===f0?f+=w():f+=m}}return p?{op:"glob",pattern:f}:f}).reduce(function(c,u){return typeof u>"u"?c:c.concat(u)},[])}YW.exports=function(e,t,n){var s=age(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 sge.test(c)?JSON.parse(c.split($c)[1]):c}))},[])}});var Va=L(m0=>{"use strict";g();m0.quote=zW();m0.parse=JW()});var xG=L((exports,module)=>{g();var Module=typeof Module<"u"?Module:{},ENVIRONMENT_IS_WEB=typeof window=="object",ENVIRONMENT_IS_WORKER=typeof importScripts=="function",ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",TreeSitter=function(){var initPromise,document=typeof window=="object"?{currentScript:window.document.currentScript}:null;class Parser{constructor(){this.initialize()}initialize(){throw new Error("cannot construct a Parser before calling `init()`")}static init(moduleOptions){return initPromise||(Module=Object.assign({},Module,moduleOptions),initPromise=new Promise(resolveInitPromise=>{var moduleOverrides=Object.assign({},Module),arguments_=[],thisProgram="./this.program",quit_=(r,e)=>{throw e},scriptDirectory="";function locateFile(r){return Module.locateFile?Module.locateFile(r,scriptDirectory):scriptDirectory+r}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=be("fs"),nodePath=be("path");scriptDirectory=__matilda_dirname+"/",readBinary=r=>{r=isFileURI(r)?new URL(r):nodePath.normalize(r);var e=fs.readFileSync(r);return e},readAsync=(r,e=!0)=>(r=isFileURI(r)?new URL(r):nodePath.normalize(r),new Promise((t,n)=>{fs.readFile(r,e?void 0:"utf8",(s,o)=>{s?n(s):t(e?o.buffer:o)})})),!Module.thisProgram&&process.argv.length>1&&(thisProgram=process.argv[1].replace(/\\/g,"/")),arguments_=process.argv.slice(2),typeof module<"u"&&(module.exports=Module),quit_=(r,e)=>{throw process.exitCode=r,e}}else(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)&&(ENVIRONMENT_IS_WORKER?scriptDirectory=self.location.href:typeof document<"u"&&document.currentScript&&(scriptDirectory=document.currentScript.src),scriptDirectory.startsWith("blob:")?scriptDirectory="":scriptDirectory=scriptDirectory.substr(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1),ENVIRONMENT_IS_WORKER&&(readBinary=r=>{var e=new XMLHttpRequest;return e.open("GET",r,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),readAsync=r=>isFileURI(r)?new Promise((e,t)=>{var n=new XMLHttpRequest;n.open("GET",r,!0),n.responseType="arraybuffer",n.onload=()=>{(n.status==200||n.status==0&&n.response)&&t(n.response),e(n.status)},n.onerror=e,n.send(null)}):fetch(r,{credentials:"same-origin"}).then(e=>e.ok?e.arrayBuffer():Promise.reject(new Error(e.status+" : "+e.url))));var out=Module.print||console.log.bind(console),err=Module.printErr||console.error.bind(console);Object.assign(Module,moduleOverrides),moduleOverrides=null,Module.arguments&&(arguments_=Module.arguments),Module.thisProgram&&(thisProgram=Module.thisProgram),Module.quit&&(quit_=Module.quit);var dynamicLibraries=Module.dynamicLibraries||[],wasmBinary;Module.wasmBinary&&(wasmBinary=Module.wasmBinary);var wasmMemory,ABORT=!1,EXITSTATUS,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64,HEAP_DATA_VIEW;function updateMemoryViews(){var r=wasmMemory.buffer;Module.HEAP_DATA_VIEW=HEAP_DATA_VIEW=new DataView(r),Module.HEAP8=HEAP8=new Int8Array(r),Module.HEAP16=HEAP16=new Int16Array(r),Module.HEAPU8=HEAPU8=new Uint8Array(r),Module.HEAPU16=HEAPU16=new Uint16Array(r),Module.HEAP32=HEAP32=new Int32Array(r),Module.HEAPU32=HEAPU32=new Uint32Array(r),Module.HEAPF32=HEAPF32=new Float32Array(r),Module.HEAPF64=HEAPF64=new Float64Array(r)}if(Module.wasmMemory)wasmMemory=Module.wasmMemory;else{var INITIAL_MEMORY=Module.INITIAL_MEMORY||33554432;wasmMemory=new WebAssembly.Memory({initial:INITIAL_MEMORY/65536,maximum:2147483648/65536})}updateMemoryViews();var __ATPRERUN__=[],__ATINIT__=[],__ATMAIN__=[],__ATPOSTRUN__=[],__RELOC_FUNCS__=[],runtimeInitialized=!1;function preRun(){if(Module.preRun)for(typeof Module.preRun=="function"&&(Module.preRun=[Module.preRun]);Module.preRun.length;)addOnPreRun(Module.preRun.shift());callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=!0,callRuntimeCallbacks(__RELOC_FUNCS__),callRuntimeCallbacks(__ATINIT__)}function preMain(){callRuntimeCallbacks(__ATMAIN__)}function postRun(){if(Module.postRun)for(typeof Module.postRun=="function"&&(Module.postRun=[Module.postRun]);Module.postRun.length;)addOnPostRun(Module.postRun.shift());callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(r){__ATPRERUN__.unshift(r)}function addOnInit(r){__ATINIT__.unshift(r)}function addOnPostRun(r){__ATPOSTRUN__.unshift(r)}var runDependencies=0,runDependencyWatcher=null,dependenciesFulfilled=null;function getUniqueRunDependency(r){return r}function addRunDependency(r){runDependencies++,Module.monitorRunDependencies?.(runDependencies)}function removeRunDependency(r){if(runDependencies--,Module.monitorRunDependencies?.(runDependencies),runDependencies==0&&(runDependencyWatcher!==null&&(clearInterval(runDependencyWatcher),runDependencyWatcher=null),dependenciesFulfilled)){var e=dependenciesFulfilled;dependenciesFulfilled=null,e()}}function abort(r){Module.onAbort?.(r),r="Aborted("+r+")",err(r),ABORT=!0,EXITSTATUS=1,r+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(r);throw e}var dataURIPrefix="data:application/octet-stream;base64,",isDataURI=r=>r.startsWith(dataURIPrefix),isFileURI=r=>r.startsWith("file://");function findWasmBinary(){var r="tree-sitter.wasm";return isDataURI(r)?r:locateFile(r)}var wasmBinaryFile;function getBinarySync(r){if(r==wasmBinaryFile&&wasmBinary)return new Uint8Array(wasmBinary);if(readBinary)return readBinary(r);throw"both async and sync fetching of the wasm failed"}function getBinaryPromise(r){return wasmBinary?Promise.resolve().then(()=>getBinarySync(r)):readAsync(r).then(e=>new Uint8Array(e),()=>getBinarySync(r))}function instantiateArrayBuffer(r,e,t){return getBinaryPromise(r).then(n=>WebAssembly.instantiate(n,e)).then(t,n=>{err(`failed to asynchronously prepare wasm: ${n}`),abort(n)})}function instantiateAsync(r,e,t,n){return!r&&typeof WebAssembly.instantiateStreaming=="function"&&!isDataURI(e)&&!isFileURI(e)&&!ENVIRONMENT_IS_NODE&&typeof fetch=="function"?fetch(e,{credentials:"same-origin"}).then(s=>{var o=WebAssembly.instantiateStreaming(s,t);return o.then(n,function(a){return err(`wasm streaming compile failed: ${a}`),err("falling back to ArrayBuffer instantiation"),instantiateArrayBuffer(e,t,n)})}):instantiateArrayBuffer(e,t,n)}function getWasmImports(){return{env:wasmImports,wasi_snapshot_preview1:wasmImports,"GOT.mem":new Proxy(wasmImports,GOTHandler),"GOT.func":new Proxy(wasmImports,GOTHandler)}}function createWasm(){var r=getWasmImports();function e(n,s){wasmExports=n.exports,wasmExports=relocateExports(wasmExports,1024);var o=getDylinkMetadata(s);return o.neededDynlibs&&(dynamicLibraries=o.neededDynlibs.concat(dynamicLibraries)),mergeLibSymbols(wasmExports,"main"),LDSO.init(),loadDylibs(),addOnInit(wasmExports.__wasm_call_ctors),__RELOC_FUNCS__.push(wasmExports.__wasm_apply_data_relocs),removeRunDependency("wasm-instantiate"),wasmExports}addRunDependency("wasm-instantiate");function t(n){e(n.instance,n.module)}if(Module.instantiateWasm)try{return Module.instantiateWasm(r,e)}catch(n){return err(`Module.instantiateWasm callback failed with error: ${n}`),!1}return wasmBinaryFile||(wasmBinaryFile=findWasmBinary()),instantiateAsync(wasmBinary,wasmBinaryFile,r,t),{}}var ASM_CONSTS={};function ExitStatus(r){this.name="ExitStatus",this.message=`Program terminated with exit(${r})`,this.status=r}var GOT={},currentModuleWeakSymbols=new Set([]),GOTHandler={get(r,e){var t=GOT[e];return t||(t=GOT[e]=new WebAssembly.Global({value:"i32",mutable:!0})),currentModuleWeakSymbols.has(e)||(t.required=!0),t}},LE_HEAP_LOAD_F32=r=>HEAP_DATA_VIEW.getFloat32(r,!0),LE_HEAP_LOAD_F64=r=>HEAP_DATA_VIEW.getFloat64(r,!0),LE_HEAP_LOAD_I16=r=>HEAP_DATA_VIEW.getInt16(r,!0),LE_HEAP_LOAD_I32=r=>HEAP_DATA_VIEW.getInt32(r,!0),LE_HEAP_LOAD_U32=r=>HEAP_DATA_VIEW.getUint32(r,!0),LE_HEAP_STORE_F32=(r,e)=>HEAP_DATA_VIEW.setFloat32(r,e,!0),LE_HEAP_STORE_F64=(r,e)=>HEAP_DATA_VIEW.setFloat64(r,e,!0),LE_HEAP_STORE_I16=(r,e)=>HEAP_DATA_VIEW.setInt16(r,e,!0),LE_HEAP_STORE_I32=(r,e)=>HEAP_DATA_VIEW.setInt32(r,e,!0),LE_HEAP_STORE_U32=(r,e)=>HEAP_DATA_VIEW.setUint32(r,e,!0),callRuntimeCallbacks=r=>{for(;r.length>0;)r.shift()(Module)},UTF8Decoder=typeof TextDecoder<"u"?new TextDecoder:void 0,UTF8ArrayToString=(r,e,t)=>{for(var n=e+t,s=e;r[s]&&!(s>=n);)++s;if(s-e>16&&r.buffer&&UTF8Decoder)return UTF8Decoder.decode(r.subarray(e,s));for(var o="";e<s;){var a=r[e++];if(!(a&128)){o+=String.fromCharCode(a);continue}var l=r[e++]&63;if((a&224)==192){o+=String.fromCharCode((a&31)<<6|l);continue}var c=r[e++]&63;if((a&240)==224?a=(a&15)<<12|l<<6|c:a=(a&7)<<18|l<<12|c<<6|r[e++]&63,a<65536)o+=String.fromCharCode(a);else{var u=a-65536;o+=String.fromCharCode(55296|u>>10,56320|u&1023)}}return o},getDylinkMetadata=r=>{var e=0,t=0;function n(){return r[e++]}function s(){for(var H=0,V=1;;){var W=r[e++];if(H+=(W&127)*V,V*=128,!(W&128))break}return H}function o(){var H=s();return e+=H,UTF8ArrayToString(r,e-H,H)}function a(H,V){if(H)throw new Error(V)}var l="dylink.0";if(r instanceof WebAssembly.Module){var c=WebAssembly.Module.customSections(r,l);c.length===0&&(l="dylink",c=WebAssembly.Module.customSections(r,l)),a(c.length===0,"need dylink section"),r=new Uint8Array(c[0]),t=r.length}else{var u=new Uint32Array(new Uint8Array(r.subarray(0,24)).buffer),h=u[0]==1836278016||u[0]==6386541;a(!h,"need to see wasm magic number"),a(r[8]!==0,"need the dylink section to be first"),e=9;var d=s();t=e+d,l=o()}var f={neededDynlibs:[],tlsExports:new Set,weakImports:new Set};if(l=="dylink"){f.memorySize=s(),f.memoryAlign=s(),f.tableSize=s(),f.tableAlign=s();for(var p=s(),y=0;y<p;++y){var w=o();f.neededDynlibs.push(w)}}else{a(l!=="dylink.0");for(var m=1,_=2,b=3,v=4,S=256,E=3,T=1;e<t;){var R=n(),k=s();if(R===m)f.memorySize=s(),f.memoryAlign=s(),f.tableSize=s(),f.tableAlign=s();else if(R===_)for(var p=s(),y=0;y<p;++y)w=o(),f.neededDynlibs.push(w);else if(R===b)for(var P=s();P--;){var B=o(),$=s();$&S&&f.tlsExports.add(B)}else if(R===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 o2,c as $R,d as a2,e as U,f as l2,g as Ye,h as vt,i as c2,j as u2,k as Zt,l as se,m as oe,n as fr,o as Lt,p as UR,q as HR,r as Et,s as zn,t as ue,u as Vt,v as d2,w as BR,x as h2,y as f2}from"./chunk-TZIDSCTF.js";import{d as y2,e as w2,g as E2,h as T2,i as k2,j as jR,m as x2}from"./chunk-FUNLOUYI.js";import{d as A2,k as zR,n as R2,p as P2}from"./chunk-R3H6IWFK.js";import{g as _2,h as b2,i as v2,m as Up,n as S2,p as C2}from"./chunk-OMZ5SGMK.js";import{a as Bt}from"./chunk-GIIMOLLN.js";import{a as Ub,b as m2,d as VR,e as jb}from"./chunk-RBG4ERTN.js";import{a as M2,b as I2,c as Hp}from"./chunk-TXMXCR7D.js";import{a as qR}from"./chunk-YULUB745.js";import{a as O2,b as D2,c as L2,d as WR,e as N2,f as GR}from"./chunk-LQWORCPO.js";import{a as s2,b as $b,c as i2}from"./chunk-TISQNFB5.js";import{a as Di,b as NR,c as Ed,s as FR}from"./chunk-SS5WUOSJ.js";import{a as Bb,b as Bp}from"./chunk-QEI3OETI.js";import{b as p2,g as Hb,j as $p,k as g2,l as vs}from"./chunk-QKYGQLWC.js";import{a as et,b as Td,d as xd,e as Ad}from"./chunk-MNGFXISD.js";import{b as Ro,d as Kj,f as Yj,i as ot,j as Jj,k as Xj,l as Zj,m as Qj,n as e2,o as t2,p as r2,q as n2}from"./chunk-4R2OFVPK.js";import{b as kd}from"./chunk-RNKDFE2S.js";import{a as Vj}from"./chunk-EMWHQSMS.js";import{a as dB}from"./chunk-S4K76QPI.js";import{B as nn,C as LR,F as Cd,g as $j,j as vc,k as Fp,l as OR,n as DR,q as Fb}from"./chunk-RLPVQ5SY.js";import{a as xo,c as MR}from"./chunk-4F4DA5UI.js";import{e as IR}from"./chunk-DC7LAFZZ.js";import{D as PR,E as Dj}from"./chunk-2XZIKUB6.js";import{h as vd,k as Nj,m as Fj,q as Np}from"./chunk-XYA3SFGC.js";import{a as PB,b as Ia,c as Gs,d as MB,f as IB}from"./chunk-4J6DC24J.js";import{a as Lj,g as Hj,h as Bj,k as Sd,l as jj,m as zj}from"./chunk-XJDC3ZQZ.js";import{$a as xb,$b as fj,$c as CR,Ab as sj,Ac as bR,B as $B,Bb as ij,Bc as vR,Cb as oj,Cc as ko,Db as aj,Eb as lj,Ec as SR,F as wd,G as UB,Gb as dR,Ha as jB,Ic as Ej,Jb as cj,Mc as Tj,Ob as uj,Oc as kj,Qc as bd,Rc as xj,Sb as _d,Sc as Aj,Tb as dj,Ub as hj,Va as zB,Vc as Ob,Yb as Rb,Za as qB,_a as La,_b as hR,aa as HB,ab as WB,ac as yc,ad as bc,bb as GB,bc as fR,bd as Rj,cb as rn,cd as Db,d as CB,da as Da,dc as pj,ec as pR,ed as ER,f as To,fc as mj,fd as TR,g as RB,ga as Ip,gb as cR,gc as mR,gd as kR,h as jn,ha as kb,hb as VB,hc as gR,i as Oa,ib as KB,ic as yR,id as xR,jb as YB,k as OB,kb as uR,kd as Pj,l as DB,lb as JB,m as LB,mb as XB,mc as gj,nb as ZB,nc as yj,ob as QB,oc as wj,od as Mj,p as mc,pb as ej,pd as Ij,q as Mp,qb as tj,qd as Oj,r as NB,rb as rj,rc as wR,rd as AR,s as FB,sb as nj,sc as Pb,t as gc,tc as Mb,uc as bj,ud as RR,vb as Ab,vc as vj,vd as Lb,wd as Nb,xc as _R,ya as lR,yc as Lp,za as BB,zc as Sj}from"./chunk-CFBZKYFB.js";import{b as Oi,h as Ar,k as _j,l as wc,m as Rr,n as _c,o as Op,s as Vs,t as Dp,w as Ib}from"./chunk-UY2R3ZQ4.js";import{a as Cj}from"./chunk-NDR7ZFUA.js";import{b as EB,c as nde,d as sde,e as TB,f as kB,g as qs,i as Ws,j as xB,k as oR,o as AB,p as A,q as vn,r as Eb,s as Tb}from"./chunk-5U3A6KMU.js";import{a as Gj}from"./chunk-IMYUVCF7.js";import{a as qj,b as Ao,c as Wj}from"./chunk-ESSYHTAZ.js";import{b as Uj}from"./chunk-3YLXGE6T.js";import{b as Ke,c as bs,e as Cb}from"./chunk-IOCF4XSR.js";import{A as mB,C as zs,D as yd,F as pc,G as gB,J as nR,K as sR,L as fe,Q as bB,R as vB,T as SB,W as iR,Y as F,a as Rt,b as vb,c as Q,d as Eo,p as hB,r as fB,s as tn,w as gd,z as pB}from"./chunk-QWBNNEV2.js";import{a as aR}from"./chunk-G7R2XEEF.js";import{g as Sb,h as yB,l as wB,n as _B}from"./chunk-FWDMPRKU.js";import{a as __matilda_dirname,b as g}from"./chunk-GZPNIYVZ.js";import{a as be,c as tde,d as L,e as rde,f as Ve}from"./chunk-OWGSC52X.js";var zW=L((UJe,jW)=>{"use strict";g();jW.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 JW=L((BJe,YW)=>{"use strict";g();var KW="(?:"+["\\|\\|","\\&\\&",";;","\\|\\&","\\<\\(","\\<\\<\\<",">>",">\\&","<\\&","[&;()|<>]"].join("|")+")",qW=new RegExp("^"+KW+"$"),WW="|&;()<> \\t",ege='"((\\\\"|[^"])*?)"',tge="'((\\\\'|[^'])*?)'",rge=/^#$/,GW="'",VW='"',f0="$",$c="",nge=4294967296;for(p0=0;p0<4;p0++)$c+=(nge*Math.random()).toString(16);var p0,sge=new RegExp("^"+$c);function ige(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 oge(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 age(r,e,t){t||(t={});var n=t.escape||"\\",s="(\\"+n+`['"`+WW+`]|[^\\s'"`+WW+"])+",o=new RegExp(["("+KW+")","("+s+"|"+ege+"|"+tge+")+"].join("|"),"g"),a=ige(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(qW.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 oge(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==GW?f+=m:m===n?(y+=1,m=u.charAt(y),m===VW||m===n||m===f0?f+=m:f+=n+m):m===f0?f+=w():f+=m;else if(m===VW||m===GW)h=m;else{if(qW.test(m))return{op:u};if(rge.test(m)){l=!0;var _={comment:r.slice(c.index+y+1)};return f.length?[f,_]:[_]}else m===n?d=!0:m===f0?f+=w():f+=m}}return p?{op:"glob",pattern:f}:f}).reduce(function(c,u){return typeof u>"u"?c:c.concat(u)},[])}YW.exports=function(e,t,n){var s=age(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 sge.test(c)?JSON.parse(c.split($c)[1]):c}))},[])}});var Va=L(m0=>{"use strict";g();m0.quote=zW();m0.parse=JW()});var xG=L((exports,module)=>{g();var Module=typeof Module<"u"?Module:{},ENVIRONMENT_IS_WEB=typeof window=="object",ENVIRONMENT_IS_WORKER=typeof importScripts=="function",ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",TreeSitter=function(){var initPromise,document=typeof window=="object"?{currentScript:window.document.currentScript}:null;class Parser{constructor(){this.initialize()}initialize(){throw new Error("cannot construct a Parser before calling `init()`")}static init(moduleOptions){return initPromise||(Module=Object.assign({},Module,moduleOptions),initPromise=new Promise(resolveInitPromise=>{var moduleOverrides=Object.assign({},Module),arguments_=[],thisProgram="./this.program",quit_=(r,e)=>{throw e},scriptDirectory="";function locateFile(r){return Module.locateFile?Module.locateFile(r,scriptDirectory):scriptDirectory+r}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=be("fs"),nodePath=be("path");scriptDirectory=__matilda_dirname+"/",readBinary=r=>{r=isFileURI(r)?new URL(r):nodePath.normalize(r);var e=fs.readFileSync(r);return e},readAsync=(r,e=!0)=>(r=isFileURI(r)?new URL(r):nodePath.normalize(r),new Promise((t,n)=>{fs.readFile(r,e?void 0:"utf8",(s,o)=>{s?n(s):t(e?o.buffer:o)})})),!Module.thisProgram&&process.argv.length>1&&(thisProgram=process.argv[1].replace(/\\/g,"/")),arguments_=process.argv.slice(2),typeof module<"u"&&(module.exports=Module),quit_=(r,e)=>{throw process.exitCode=r,e}}else(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)&&(ENVIRONMENT_IS_WORKER?scriptDirectory=self.location.href:typeof document<"u"&&document.currentScript&&(scriptDirectory=document.currentScript.src),scriptDirectory.startsWith("blob:")?scriptDirectory="":scriptDirectory=scriptDirectory.substr(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1),ENVIRONMENT_IS_WORKER&&(readBinary=r=>{var e=new XMLHttpRequest;return e.open("GET",r,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),readAsync=r=>isFileURI(r)?new Promise((e,t)=>{var n=new XMLHttpRequest;n.open("GET",r,!0),n.responseType="arraybuffer",n.onload=()=>{(n.status==200||n.status==0&&n.response)&&t(n.response),e(n.status)},n.onerror=e,n.send(null)}):fetch(r,{credentials:"same-origin"}).then(e=>e.ok?e.arrayBuffer():Promise.reject(new Error(e.status+" : "+e.url))));var out=Module.print||console.log.bind(console),err=Module.printErr||console.error.bind(console);Object.assign(Module,moduleOverrides),moduleOverrides=null,Module.arguments&&(arguments_=Module.arguments),Module.thisProgram&&(thisProgram=Module.thisProgram),Module.quit&&(quit_=Module.quit);var dynamicLibraries=Module.dynamicLibraries||[],wasmBinary;Module.wasmBinary&&(wasmBinary=Module.wasmBinary);var wasmMemory,ABORT=!1,EXITSTATUS,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64,HEAP_DATA_VIEW;function updateMemoryViews(){var r=wasmMemory.buffer;Module.HEAP_DATA_VIEW=HEAP_DATA_VIEW=new DataView(r),Module.HEAP8=HEAP8=new Int8Array(r),Module.HEAP16=HEAP16=new Int16Array(r),Module.HEAPU8=HEAPU8=new Uint8Array(r),Module.HEAPU16=HEAPU16=new Uint16Array(r),Module.HEAP32=HEAP32=new Int32Array(r),Module.HEAPU32=HEAPU32=new Uint32Array(r),Module.HEAPF32=HEAPF32=new Float32Array(r),Module.HEAPF64=HEAPF64=new Float64Array(r)}if(Module.wasmMemory)wasmMemory=Module.wasmMemory;else{var INITIAL_MEMORY=Module.INITIAL_MEMORY||33554432;wasmMemory=new WebAssembly.Memory({initial:INITIAL_MEMORY/65536,maximum:2147483648/65536})}updateMemoryViews();var __ATPRERUN__=[],__ATINIT__=[],__ATMAIN__=[],__ATPOSTRUN__=[],__RELOC_FUNCS__=[],runtimeInitialized=!1;function preRun(){if(Module.preRun)for(typeof Module.preRun=="function"&&(Module.preRun=[Module.preRun]);Module.preRun.length;)addOnPreRun(Module.preRun.shift());callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=!0,callRuntimeCallbacks(__RELOC_FUNCS__),callRuntimeCallbacks(__ATINIT__)}function preMain(){callRuntimeCallbacks(__ATMAIN__)}function postRun(){if(Module.postRun)for(typeof Module.postRun=="function"&&(Module.postRun=[Module.postRun]);Module.postRun.length;)addOnPostRun(Module.postRun.shift());callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(r){__ATPRERUN__.unshift(r)}function addOnInit(r){__ATINIT__.unshift(r)}function addOnPostRun(r){__ATPOSTRUN__.unshift(r)}var runDependencies=0,runDependencyWatcher=null,dependenciesFulfilled=null;function getUniqueRunDependency(r){return r}function addRunDependency(r){runDependencies++,Module.monitorRunDependencies?.(runDependencies)}function removeRunDependency(r){if(runDependencies--,Module.monitorRunDependencies?.(runDependencies),runDependencies==0&&(runDependencyWatcher!==null&&(clearInterval(runDependencyWatcher),runDependencyWatcher=null),dependenciesFulfilled)){var e=dependenciesFulfilled;dependenciesFulfilled=null,e()}}function abort(r){Module.onAbort?.(r),r="Aborted("+r+")",err(r),ABORT=!0,EXITSTATUS=1,r+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(r);throw e}var dataURIPrefix="data:application/octet-stream;base64,",isDataURI=r=>r.startsWith(dataURIPrefix),isFileURI=r=>r.startsWith("file://");function findWasmBinary(){var r="tree-sitter.wasm";return isDataURI(r)?r:locateFile(r)}var wasmBinaryFile;function getBinarySync(r){if(r==wasmBinaryFile&&wasmBinary)return new Uint8Array(wasmBinary);if(readBinary)return readBinary(r);throw"both async and sync fetching of the wasm failed"}function getBinaryPromise(r){return wasmBinary?Promise.resolve().then(()=>getBinarySync(r)):readAsync(r).then(e=>new Uint8Array(e),()=>getBinarySync(r))}function instantiateArrayBuffer(r,e,t){return getBinaryPromise(r).then(n=>WebAssembly.instantiate(n,e)).then(t,n=>{err(`failed to asynchronously prepare wasm: ${n}`),abort(n)})}function instantiateAsync(r,e,t,n){return!r&&typeof WebAssembly.instantiateStreaming=="function"&&!isDataURI(e)&&!isFileURI(e)&&!ENVIRONMENT_IS_NODE&&typeof fetch=="function"?fetch(e,{credentials:"same-origin"}).then(s=>{var o=WebAssembly.instantiateStreaming(s,t);return o.then(n,function(a){return err(`wasm streaming compile failed: ${a}`),err("falling back to ArrayBuffer instantiation"),instantiateArrayBuffer(e,t,n)})}):instantiateArrayBuffer(e,t,n)}function getWasmImports(){return{env:wasmImports,wasi_snapshot_preview1:wasmImports,"GOT.mem":new Proxy(wasmImports,GOTHandler),"GOT.func":new Proxy(wasmImports,GOTHandler)}}function createWasm(){var r=getWasmImports();function e(n,s){wasmExports=n.exports,wasmExports=relocateExports(wasmExports,1024);var o=getDylinkMetadata(s);return o.neededDynlibs&&(dynamicLibraries=o.neededDynlibs.concat(dynamicLibraries)),mergeLibSymbols(wasmExports,"main"),LDSO.init(),loadDylibs(),addOnInit(wasmExports.__wasm_call_ctors),__RELOC_FUNCS__.push(wasmExports.__wasm_apply_data_relocs),removeRunDependency("wasm-instantiate"),wasmExports}addRunDependency("wasm-instantiate");function t(n){e(n.instance,n.module)}if(Module.instantiateWasm)try{return Module.instantiateWasm(r,e)}catch(n){return err(`Module.instantiateWasm callback failed with error: ${n}`),!1}return wasmBinaryFile||(wasmBinaryFile=findWasmBinary()),instantiateAsync(wasmBinary,wasmBinaryFile,r,t),{}}var ASM_CONSTS={};function ExitStatus(r){this.name="ExitStatus",this.message=`Program terminated with exit(${r})`,this.status=r}var GOT={},currentModuleWeakSymbols=new Set([]),GOTHandler={get(r,e){var t=GOT[e];return t||(t=GOT[e]=new WebAssembly.Global({value:"i32",mutable:!0})),currentModuleWeakSymbols.has(e)||(t.required=!0),t}},LE_HEAP_LOAD_F32=r=>HEAP_DATA_VIEW.getFloat32(r,!0),LE_HEAP_LOAD_F64=r=>HEAP_DATA_VIEW.getFloat64(r,!0),LE_HEAP_LOAD_I16=r=>HEAP_DATA_VIEW.getInt16(r,!0),LE_HEAP_LOAD_I32=r=>HEAP_DATA_VIEW.getInt32(r,!0),LE_HEAP_LOAD_U32=r=>HEAP_DATA_VIEW.getUint32(r,!0),LE_HEAP_STORE_F32=(r,e)=>HEAP_DATA_VIEW.setFloat32(r,e,!0),LE_HEAP_STORE_F64=(r,e)=>HEAP_DATA_VIEW.setFloat64(r,e,!0),LE_HEAP_STORE_I16=(r,e)=>HEAP_DATA_VIEW.setInt16(r,e,!0),LE_HEAP_STORE_I32=(r,e)=>HEAP_DATA_VIEW.setInt32(r,e,!0),LE_HEAP_STORE_U32=(r,e)=>HEAP_DATA_VIEW.setUint32(r,e,!0),callRuntimeCallbacks=r=>{for(;r.length>0;)r.shift()(Module)},UTF8Decoder=typeof TextDecoder<"u"?new TextDecoder:void 0,UTF8ArrayToString=(r,e,t)=>{for(var n=e+t,s=e;r[s]&&!(s>=n);)++s;if(s-e>16&&r.buffer&&UTF8Decoder)return UTF8Decoder.decode(r.subarray(e,s));for(var o="";e<s;){var a=r[e++];if(!(a&128)){o+=String.fromCharCode(a);continue}var l=r[e++]&63;if((a&224)==192){o+=String.fromCharCode((a&31)<<6|l);continue}var c=r[e++]&63;if((a&240)==224?a=(a&15)<<12|l<<6|c:a=(a&7)<<18|l<<12|c<<6|r[e++]&63,a<65536)o+=String.fromCharCode(a);else{var u=a-65536;o+=String.fromCharCode(55296|u>>10,56320|u&1023)}}return o},getDylinkMetadata=r=>{var e=0,t=0;function n(){return r[e++]}function s(){for(var H=0,V=1;;){var W=r[e++];if(H+=(W&127)*V,V*=128,!(W&128))break}return H}function o(){var H=s();return e+=H,UTF8ArrayToString(r,e-H,H)}function a(H,V){if(H)throw new Error(V)}var l="dylink.0";if(r instanceof WebAssembly.Module){var c=WebAssembly.Module.customSections(r,l);c.length===0&&(l="dylink",c=WebAssembly.Module.customSections(r,l)),a(c.length===0,"need dylink section"),r=new Uint8Array(c[0]),t=r.length}else{var u=new Uint32Array(new Uint8Array(r.subarray(0,24)).buffer),h=u[0]==1836278016||u[0]==6386541;a(!h,"need to see wasm magic number"),a(r[8]!==0,"need the dylink section to be first"),e=9;var d=s();t=e+d,l=o()}var f={neededDynlibs:[],tlsExports:new Set,weakImports:new Set};if(l=="dylink"){f.memorySize=s(),f.memoryAlign=s(),f.tableSize=s(),f.tableAlign=s();for(var p=s(),y=0;y<p;++y){var w=o();f.neededDynlibs.push(w)}}else{a(l!=="dylink.0");for(var m=1,_=2,b=3,v=4,S=256,E=3,T=1;e<t;){var R=n(),k=s();if(R===m)f.memorySize=s(),f.memoryAlign=s(),f.tableSize=s(),f.tableAlign=s();else if(R===_)for(var p=s(),y=0;y<p;++y)w=o(),f.neededDynlibs.push(w);else if(R===b)for(var P=s();P--;){var B=o(),$=s();$&S&&f.tlsExports.add(B)}else if(R===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 R=b[0].value,k=!0,P=!0,B;switch(R){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 \`#${R}\` predicate. Expected 2, got ${b.length-1}`);if(b[1].type!=="capture")throw new Error(`First argument of \`#${R}\` predicate must be a capture. Got "${b[1].value}"`);if(P=!R.startsWith("any-"),b[2].type==="capture"){let V=b[1].name,W=b[2].name;y[w].push(G=>{let z=[],q=[];for(let I of G)I.name===V&&z.push(I.node),I.name===W&&q.push(I.node);let x=(I,D,N)=>N?I.text===D.text:I.text!==D.text;return P?z.every(I=>q.some(D=>x(I,D,k))):z.some(I=>q.some(D=>x(I,D,k)))})}else{B=b[1].name;let V=b[2].value,W=z=>z.text===V,G=z=>z.text!==V;y[w].push(z=>{let q=[];for(let I of z)I.name===B&&q.push(I.node);let x=k?W:G;return P?q.every(x):q.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 \`#${R}\` predicate. Expected 2, got ${b.length-1}.`);if(b[1].type!=="capture")throw new Error(`First argument of \`#${R}\` predicate must be a capture. Got "${b[1].value}".`);if(b[2].type!=="string")throw new Error(`Second argument of \`#${R}\` predicate must be a string. Got @${b[2].value}.`);B=b[1].name;let $=new RegExp(b[2].value);P=!R.startsWith("any-"),y[w].push(V=>{let W=[];for(let z of V)z.name===B&&W.push(z.node.text);let G=(z,q)=>q?$.test(z):!$.test(z);return W.length===0?!k:P?W.every(z=>G(z,k)):W.some(z=>G(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(V=>V.type!=="string"))throw new Error('Arguments to `#set!` predicate must be a strings.".');h[w]||(h[w]={}),h[w][b[1].value]=b[2]?b[2].value:null;break;case"is?":case"is-not?":if(b.length<2||b.length>3)throw new Error(`Wrong number of arguments to \`#${R}\` predicate. Expected 1 or 2. Got ${b.length-1}.`);if(b.some(V=>V.type!=="string"))throw new Error(`Arguments to \`#${R}\` predicate must be a strings.".`);let O=R==="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 \`#${R}\` predicate. Expected at least 1. Got ${b.length-1}.`);if(b[1].type!=="capture")throw new Error(`First argument of \`#${R}\` predicate must be a capture. Got "${b[1].value}".`);for(let V=2;V<b.length;V++)if(b[V].type!=="string")throw new Error(`Arguments to \`#${R}\` predicate must be a strings.".`);B=b[1].name;let H=b.slice(2).map(V=>V.value);y[w].push(V=>{let W=[];for(let G of V)G.name===B&&W.push(G.node.text);return W.length===0?!k:W.every(G=>H.includes(G))===k});break;default:p[w].push({operator:R,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:
|
|
@@ -2184,7 +2184,7 @@ ${Td(r)}
|
|
|
2184
2184
|
The current date is: ${W}. Note: This is the authoritative current date \u2014 it may differ from the "Today's date" mentioned earlier in the conversation startup context.
|
|
2185
2185
|
</system-reminder>`),this.lastInjectedDate=W)}this.config.getApprovalMode()==="plan"&&O.push(_v(this.config.getSdkMode()));let H=this.config.getArenaManager();if(H)try{let G=`${H.getArenaSessionDir()}/config.json`;O.push(kq(G))}catch{}let V=await this.tryConsumeMemoryPrefetch();V?.prompt&&O.unshift(V.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:Gs(T)})}let R=Ed(this.config.getSessionId());R&&(yield{type:"active_goal",value:R});let k=R,P=O=>{if(!NR(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 H=this.config.getSkipLoopDetection(),V=!H&&this.loopDetector.addAndCheckDeterministicToolCallLoop(O),W=!V&&!H&&this.loopDetector.addAndCheckHeuristicLoops(O);if(V||W){let G=this.loopDetector.getLastLoopType();if(O.type==="tool_call_request"&&G==="consecutive_identical_tool_calls"){let z=this.loopDetector.getConsecutiveToolCallCount(),q=Math.max(0,S.pendingToolCalls.length-z);S.pendingToolCalls.splice(q)}return yield{type:"loop_detected",...G&&{value:{loopType:G}}},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(G){this.config.getDebugLogger().warn(`Failed to restore startup context after compaction: ${G}`)}this.fireSessionStartHook("compact").then(G=>{!G||!this.chat||(this.lastSessionStartContext=G,this.lastSessionStartSource="compact",this.chat.applySessionStartContext(G,"compact"))}).catch(G=>{this.config.getDebugLogger().warn(`SessionStart hook failed: ${G}`)})}if(yield O,O.type==="error"){if(this.forceFullIdeContext=!0,v){let G=O.value instanceof Error?O.value.message:"Unknown error";await v.reportError(G)}if(this.lastApiCompletionTimestamp=Date.now(),u){let G=O.value instanceof Error?"[API error]":"unknown error";rn("error",{errorMessage:G})}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]",H=await c.request({type:"hook-execution-request",eventName:"Stop",input:{stop_hook_active:!0,last_assistant_message:O},signal:t},"hook-execution-response"),V=Ed(this.config.getSessionId());if(t.aborted){let q=P(V);return q&&(yield q),u&&rn("cancelled"),S}let G=H.output?ot("Stop",H.output):void 0;if(G?.systemMessage&&(yield{type:"hook_system_message",value:G.systemMessage}),G?.isBlockingDecision()||G?.shouldStopExecution()){if(t.aborted){let ae=P(V);return ae&&(yield ae),u&&rn("cancelled"),S}let q=G.getEffectiveReason(),x=(s?.stopHookState?.iterationCount??0)+1,I=[...s?.stopHookState?.reasons??[],q],D=this.config.getStopHookBlockingCap();if(x>=D){let ae=Ic("Stop",D);FR(this.config,this.config.getSessionId(),ae);let M=Ed(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(V);N&&(yield N),yield{type:"stop_hook_loop",value:{iterationCount:x,reasons:I,stopHookCount:H.stopHookCount??1}};let j=[{text:q}],K=Ed(this.config.getSessionId())?d:d-1,J=yield*this.sendMessageStream(j,t,n,{type:"hook",modelOverride:s?.modelOverride,stopHookState:{iterationCount:x,reasons:I}},K);return u&&rn(t.aborted?"cancelled":"ok"),h=!0,J}let z=P(V);z&&(yield z)}if(!S.pendingToolCalls.length&&t&&!t.aborted){try{let q=this.getChat(),I=this.getHistoryTailShallow(40,!0);Rce(q.getGenerationConfig(),I,this.config.getModel())}catch{}let O=this.config.getApprovalMode(),H=iz(O)||O==="plan",V=this.getChat().getLastHistoryEntry?.(),W=YH(V),G=qA(V)||W||!!V&&zA(V);if(this.config.getSkipNextSpeakerCheck()&&!H&&!G)return this.runManagedAutoMemoryBackgroundTasks(a),v&&await v.reportCompleted(),u&&rn("ok"),S;let z=await uue(this.getChat(),this.config,t,n);if(hj(this.config,new Aj(n,S.finishReason?.toString()||"",z?.next_speaker||"")),z?.next_speaker==="model"){let q=[{text:qA(V)?"Please continue with a user-visible response. Do not only think silently \u2014 summarize results or take the next concrete action.":W?"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(q,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??OE.getStore()??this.lastPromptId,l=s;try{let c=this.config.getUserMemory(),u=t.systemInstruction?lm(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:_=>{JH.stderr.write(`[matilda-code] Waiting for API capacity... attempt ${_.attempt}, retry in ${Math.ceil(_.remainingMs/1e3)}s
|
|
2186
2186
|
`)},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=>_Ve.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 Ap from"node:fs/promises";import*as due from"node:path";var hd=F("WORKTREE_CLEANUP"),xVe=[gL],AVe=30*24*60*60*1e3;function RVe(r){return xVe.some(e=>e.test(r))}async function hue(r,e={}){let t=e.cutoffMs??AVe,n=Date.now()-t,s=new rs(r),o=s.getUserWorktreesDir();try{await Ap.access(o)}catch{return 0}let a;try{a=await Ap.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()||!RVe(c.name))continue;let u=due.join(o,c.name),h;try{h=(await Ap.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([PVe(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 ${Ly(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 PVe(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 Rp from"node:os";import{readFileSync as IVe}from"node:fs";import{EventEmitter as OVe}from"node:events";import{getHeapStatistics as mue}from"node:v8";g();import*as mb from"node:fs";import*as ZH from"node:path";import*as pue from"node:v8";var pb=F("MEMORY_DUMP"),fue=3,MVe=3e4,GA=class{constructor(e){this.config=e}dumpCount=0;lastDumpTime=0;resetForNewSession(){this.dumpCount=0,this.lastDumpTime=0}async dump(e,t=[]){if(this.dumpCount>=fue){pb.debug(`Skipping dump: session cap reached (${fue})`);return}let n=Date.now();if(n-this.lastDumpTime<MVe){pb.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=ZH.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:pue.getHeapStatistics(),recentSamples:t,session:this.collectSessionStats(),suggestion:this.getSuggestion(e),collectionComplete:!1};mb.writeFileSync(u,JSON.stringify(f,null,2),"utf8"),pb.info(`Phase 1 diagnostics written to ${u} (trigger=${e}, dump #${s})`);let p=await yle({sessionId:a,matildaVersion:this.config.getCliVersion()}),y={trigger:e,dumpNumber:s,...p,recentSamples:t,session:this.collectSessionStats(),suggestion:this.getSuggestion(e),collectionComplete:!0};return mb.writeFileSync(u,JSON.stringify(y,null,2),"utf8"),pb.info(`Phase 2 diagnostics written to ${u} (trigger=${e}, dump #${s})`),{filePath:u,trigger:e}}catch(o){pb.error(`Failed to write memory diagnostics: ${Q(o)}`);return}}ensureDiagnosticsDir(){let e=this.config.storage.getProjectDir(),t=ZH.join(e,"diagnostics");return mb.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 DVe=60,fd;function LVe(){if(fd===void 0){try{fd=Rp.availableParallelism?.()??Rp.cpus().length??1}catch{fd=1}(!fd||fd<1)&&(fd=1)}return fd}function QH(){try{return process.cpuUsage()}catch{return{user:0,system:0}}}var eB=class{samples=[];prevCpuUsage=QH();prevSampleTime=Date.now();record(e){let t=Date.now(),n=t-this.prevSampleTime,s=QH(),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/LVe()));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>DVe&&this.samples.shift(),e}getAll(){return[...this.samples]}reset(){this.samples.length=0,this.prevCpuUsage=QH(),this.prevSampleTime=Date.now()}},VA={softPressureRatio:.5,hardPressureRatio:.65,criticalRatio:.8,cleanupCooldownMs:5e3,enableExplicitGC:!0};function rB(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"),NVe=64*1024*1024,wb=class extends OVe{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 eB;constructor(e,t){super(),this.coreConfig=e,this.config={...t??VA},rB(this.config),this.effectiveMemoryLimit=this.computeEffectiveMemoryLimit(),this.diagnosticsDumper=new GA(e);let n=mue().heap_size_limit;it.info(`Effective memory limit: ${yb(this.effectiveMemoryLimit)} MiB; V8 heap limit: ${yb(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);jB()&&(lR(this.coreConfig,l.rss,{memory_type:"rss"}),lR(this.coreConfig,l.heapUsed,{memory_type:"heap_used"}),BB(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=gb(n.action)>gb(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=mue().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 tB(e)}}executeCleanup(e){if(this.cleanupInProgress){let s=gb(e.action),o=gb(this.activeCleanupAction),a=this.queuedCleanupRecommendation?gb(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++,gue(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}`),gue(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=Ld(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 tB(e)}}computeEffectiveMemoryLimit(){let e=Rp.totalmem(),t=this.readCgroupMemoryLimit("/sys/fs/cgroup/memory.max",e);if(t!==void 0)return it.info(`Using cgroup v2 memory limit: ${yb(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: ${yb(n)} MiB`),n):(it.info(`Using host memory limit: ${yb(e)} MiB`),e)}readCgroupMemoryLimit(e,t){try{let n=IVe(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<NVe){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 gb(r){switch(r){case"aggressive":return 3;case"moderate":return 2;case"light":return 1;case"none":return 0;default:return tB(r)}}function gue(r){return r===3||r===10||r>10&&r%20===0}function yb(r){return(r/1024/1024).toFixed(0)}function tB(r){throw new Error(`Unhandled memory pressure monitor value: ${String(r)}`)}g();var FVe=F("PROMPT_REGISTRY"),KA=class{prompts=new Map;registerPrompt(e){if(this.prompts.has(e.name)){let t=`${e.serverName}_${e.name}`;FVe.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 yue}from"node:crypto";var $Ve=F("GIT_CO_AUTHOR"),UVe=F("MEMORY_PRESSURE"),wue=.15;var Ss=(o=>(o.PLAN="plan",o.DEFAULT="default",o.AUTO_EDIT="auto-edit",o.AUTO="auto",o.BOGAN="bogan",o))(Ss||{}),dU=Object.values(Ss).filter(r=>r!=="auto"),sB=class extends Error{constructor(e){super(e),this.name="TrustGateError"}},k4t={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"}},YA="Written by Matilda \u{1F1E6}\u{1F1FA} made by [Maincode](https://maincode.com)";function HVe(r){if(typeof r=="boolean")return{commit:r,pr:r,prMessage:YA};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)||$Ve.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:YA;return{commit:e(r?.commit,"commit"),pr:e(r?.pr,"pr"),prMessage:n}}var BVe=25e3,jVe=1e3,zVe=2e5;function x4t(r){return r==="project"||r==="workspace"}var _ue=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 $8=(n=>(n.DYNAMIC_DISCOVERY="dynamic_discovery",n.GOOGLE_CREDENTIALS="google_credentials",n.SERVICE_ACCOUNT_IMPERSONATION="service_account_impersonation",n))($8||{});function qVe(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 WVe(){let r={...VA};try{r.softPressureRatio=nB("MATILDA_MEMORY_PRESSURE_SOFT",r.softPressureRatio),r.hardPressureRatio=nB("MATILDA_MEMORY_PRESSURE_HARD",r.hardPressureRatio),r.criticalRatio=nB("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),rB(r)}catch(e){let t=`[MATILDA] WARNING: Invalid memory pressure config; using defaults. Error: ${Q(e)}`;return hr.stderr.write(`${t}
|
|
2187
|
-
`),UVe.warn(t),{...VA}}return r}function nB(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 GVe=[A.READ_FILE,A.EDIT,A.NOTEBOOK_EDIT,A.SHELL],VVe=Object.freeze(new Set),bue=!1,ap=class{sessionId;sessionData;pendingStartupWorktreeNotice=null;debugLogger;toolRegistry;pendingMcpBudgetCallback;promptRegistry;subagentManager;memoryPressureConfig;memoryPressureMonitor;backgroundTaskRegistry=new iA;monitorRegistry=new $E;backgroundAgentResumeService;backgroundShellRegistry=new UE;workflowRunRegistry=new HE;fileReadCache=new iy;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=Rm();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??yue(),!bue&&hr.env&&(hr.env.MATILDA_CODE_SESSION_ID=this.sessionId,bue=!0),this.sessionData=e.sessionData,iR(this),this.debugLogger=F(),this.embeddingModel=e.embeddingModel??MR,this.fileSystemService=new aE,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=qVe(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??PR,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={...HVe(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??wG(),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??BVe,this.truncateToolOutputLines=e.truncateToolOutputLines??jVe,this.toolOutputBatchBudget=e.toolOutputBatchBudget??zVe,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 $B(this),this.eventEmitter=e.eventEmitter,this.arenaAgentClient=Xb.create(),this.agentsSettings=e.agents??{},this.worktreeSettings=e.worktree??{},e.contextFileName&&NB(e.contextFileName),this.modelsConfig=new Fb({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&&oj(this);let o=this.getProxy();o&&(0,JA.setGlobalDispatcher)(new JA.ProxyAgent(o)),this.geminiClient=new WA(this),this.chatRecordingService=this.chatRecordingEnabled?new jd(this):void 0,this.extensionManager=new Ux({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=pP(e.stopHookBlockingCap),this.userHooks=e.userHooks,this.projectHooks=e.projectHooks,this.hooks=e.hooks,this.memoryManager=new fb}async initialize(e){if(this.initialized)throw Error("Config was already initialized");this.initialized=!0,this.debugLogger.info("Config initialization started"),this.getFileService(),this.promptRegistry=new KA,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 vp(this),await this.hookSystem.initialize(),this.debugLogger.debug("Hook system initialized"),this.messageBus=new X_,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 b_(this),this.skillManager=new T_(this),this.getBareMode()?await this.skillManager.refreshCache():await this.skillManager.startWatching(),this.debugLogger.debug("Skill manager initialized"),this.memoryPressureConfig=WVe(),this.memoryPressureMonitor=new wb(this,this.memoryPressureConfig),this.permissionManager=new xm(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 Vj().getInstallationId(),dR(this,new SR(this)),this.debugLogger.info("Config initialization completed"),this.getBareMode()||(async()=>{try{let a=await new rs(this.targetDir).getRepoTopLevel()??this.targetDir,l=bn.join(a,".matilda","worktrees");try{await vue.access(l)}catch{this.debugLogger.debug(`Stale worktree sweep skipped: ${l} does not exist`);return}let c=await hue(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)||kC(n)!=="connected"&&t.push(n);return t}async refreshHierarchicalMemory(e="refresh"){let{memoryContent:t,fileCount:n,conditionalRules:s,projectRoot:o}=await Gle(this.getWorkingDir(),this.getMemoryDiscoveryDirectories(),this.getFileService(),this.getExtensionContextFilePaths(),this.isTrustedFolder(),this.getImportFormat(),this.contextRuleExcludes,{explicitOnly:this.getBareMode(),loadReason:e,onInstructionsLoaded:OA(()=>this.hookSystem)});if(this.getManagedAutoMemoryEnabled()){let[a,l]=await Promise.all([FW(this.getProjectRoot()),UW().catch(()=>null)]);this.setUserMemory(this.memoryManager.appendToUserMemory(t,Ar(this.getProjectRoot()),a,{memoryDir:Vs(),indexContent:l}))}else this.setUserMemory(t);this.setGeminiMdFileCount(n),this.conditionalRulesRegistry=new Y_(s,o)}buildMemoryContextWarning(e){let t=this.getContentGeneratorConfig()?.contextWindowSize??this.modelsConfig.getGenerationConfig().contextWindowSize??Np(this.getModel(),"input");if(!t||t<=0||!e)return;let n=Math.ceil(e.length/Es),s=Math.floor(t*wue);if(!(n<=s))return`Warning: Loaded MATILDA.md/context instructions use about ${n.toLocaleString()} tokens, more than ${Math.round(wue*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 gm()?.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}=LR(this,e,this.modelsConfig.getGenerationConfig(),this.modelsConfig.getGenerationConfigSources(),{strictModelProvider:this.modelsConfig.isStrictModelProviderSelection()}),l=o;this.contentGenerator=await Cd(l,this,s?!0:t),this.contentGeneratorConfig=l,this.contentGeneratorConfigSources=a,this.baseLlmClient=new Gp(this.contentGenerator,this);let c=this.getMessageBus();!this.getDisableAllHooks()&&c&&ym(c,`Successfully authenticated with ${e}`,"auth_success","Authentication successful").catch(()=>{})}getBaseLlmClient(){if(!this.baseLlmClient)if(this.contentGenerator)this.baseLlmClient=new Gp(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??yue(),hr.env&&(hr.env.MATILDA_CODE_SESSION_ID=this.sessionId),this.sessionData=t,iR(this),this.debugLogger=F(),this.chatRecordingService=this.chatRecordingEnabled?new jd(this):void 0,this.getFileReadCache().clear(),this.toolResultBudget.bytesWritten=0,this.getMemoryPressureMonitor()?.resetForNewSession(),this.fileHistoryService=void 0,aj(this.sessionId),sj(),Qs.resetInstance(),this.initialized&&dR(this,new SR(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 Jz(o),await OP(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 OP(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 gm()?.contentGeneratorConfig??this.contentGeneratorConfig}getContentGeneratorConfigSources(){return Object.keys(this.contentGeneratorConfigSources).length===0&&this.modelsConfig?this.modelsConfig.getGenerationConfigSources():this.contentGeneratorConfigSources}getModel(){return this.getContentGeneratorConfig()?.model||this.modelsConfig.getModel()}getModelDisplayName(){return this.modelDisplayName||this.modelsConfig.getModelDisplayName(this.getModel())}getPublicModelId(e){return this.modelsConfig.getPublicModelId(e)}isManagedMatildaModel(e){return this.modelsConfig.isManagedMatildaModel(e)}onModelChange(e){return this.modelChangeListeners.add(e),()=>{this.modelChangeListeners.delete(e)}}notifyModelChangeListeners(){let e=this.getModel();for(let t of this.modelChangeListeners)t(e)}getFastModel(){let e=this.resolveFastModelSelector();if(!e||!(e.authType?this.getAllConfiguredModels([e.authType]):this.getAllConfiguredModels()).some(s=>s.id===e.modelId))return;let n=Ys(this.fastModel);return n?.authType?`${n.authType}:${e.modelId}`:e.modelId}resolveFastModelSelector(){if(this.fastModel)try{return Ys(this.fastModel,{currentAuthType:this.getContentGeneratorConfig()?.authType,getAvailableModels:e=>this.getAllConfiguredModels(e)})}catch{return}}setFastModel(e){this.fastModel=e||void 0}async setModel(e,t){await this.modelsConfig.setModel(e,t),this.contentGeneratorConfig&&(this.contentGeneratorConfig.model=e),this.notifyModelChangeListeners()}async handleModelChange(e,t){if(this.contentGeneratorConfig){if(e==="matilda-oauth"&&!t){let{config:n,sources:s}=LR(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{ij()&&await lj()}}getPromptRegistry(){return this.promptRegistry}getDebugMode(){return this.debugMode}getQuestion(){return this.question}getSystemPrompt(){return this.systemPrompt}getAppendSystemPrompt(){return this.appendSystemPrompt}getCoreTools(){return this.getBareMode()?GVe: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?.()??VVe}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 sB("Cannot enable privileged approval modes in an untrusted folder.");e==="plan"&&this.approvalMode!=="plan"?(this.prePlanMode=this.approvalMode,this.planGateState=sz(++this.planGateEntryCounter)):e!=="plan"&&this.approvalMode==="plan"&&(this.prePlanMode=void 0,this.planGateState=void 0);let t=e==="auto"?"default":e,n=this.approvalMode;this.permissionManager&&n==="auto"&&this.permissionManager.restoreDangerousRules(),n!==t&&(this.autoModeDenialState=$0()),this.approvalMode=t}getPlansDir(){return this.plansDir}assertPlansDirWithinTargetDir(){this.plansDirectoryConfigured&&fe.assertPathWithinDirectory(this.plansDir,this.targetDir,"plansDirectory must resolve within the project root.")}assertPlanFilePathWithinTargetDir(e){this.plansDirectoryConfigured&&fe.assertPathWithinDirectory(e,this.targetDir,"plansDirectory must resolve within the project root.")}addLegacyPlanLocationWarning(){try{if(!this.plansDirectoryConfigured)return;let e=fe.getPlansDir(),t=this.getPlanFileNames(e);if(t.length===0)return;let n=new Set(this.getPlanFileNames(this.plansDir));if(t.filter(o=>!n.has(o)).length===0)return;this.warnings.push(`Warning: Saved plan files exist at ${e}, but plansDirectory is configured to use ${this.plansDir}. Move existing plan files to ${this.plansDir} if you want to keep using them.`)}catch(e){let t=`Failed to check legacy plan directory migration warning: ${e instanceof Error?e.message:String(e)}`;this.warnings.push(t),this.debugLogger.warn(t,e)}}getPlanFileNames(e){try{return 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??Dj}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??PR}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 wb(this,this.memoryPressureConfig)}return this.memoryPressureMonitor}getCronScheduler(){return this.cronScheduler||(this.cronScheduler=new $C(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 lv(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 Kle(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()||!Uj()}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 jd(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 dv(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 aA(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 iy),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 AC(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(A.STRUCTURED_OUTPUT,async()=>{let{SyntheticOutputTool:l}=await import("./syntheticOutput-LLA4WQR7.js");return new l(a)})};if(this.getBareMode())return await s(A.READ_FILE,async()=>{let{ReadFileTool:a}=await import("./read-file-HEVXSNSO.js");return new a(this)}),await s(A.EDIT,async()=>{let{EditTool:a}=await import("./edit-C4NER5YK.js");return new a(this)}),await s(A.NOTEBOOK_EDIT,async()=>{let{NotebookEditTool:a}=await import("./notebook-edit-3SYYLOZB.js");return new a(this)}),await s(A.SHELL,async()=>{let{ShellTool:a}=await import("./shell-KW3VBBYV.js");return new a(this)}),await o(),this.debugLogger.debug(`ToolRegistry created: ${JSON.stringify(n.getAllToolNames())} (${n.getAllToolNames().length} tools)`),n;if(await s(A.TOOL_SEARCH,async()=>{let{ToolSearchTool:a}=await import("./tool-search-47TA6SG4.js");return new a(this)}),await s(A.AGENT,async()=>{let{AgentTool:a}=await import("./agent-HKV5XQAS.js");return new a(this)}),await s(A.TASK_STOP,async()=>{let{TaskStopTool:a}=await import("./task-stop-UKRXMCZV.js");return new a(this)}),await s(A.SEND_MESSAGE,async()=>{let{SendMessageTool:a}=await import("./send-message-K3T7GVHO.js");return new a(this)}),await s(A.SKILL,async()=>{let{SkillTool:a}=await import("./skill-YXHHDMLR.js");return new a(this)}),await s(A.LS,async()=>{let{LSTool:a}=await import("./ls-4QPI2E7A.js");return new a(this)}),await s(A.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 n5(this.getUseBuiltinRipgrep())}catch(c){l=Q(c)}a?await s(A.GREP,async()=>{let{RipGrepTool:c}=await import("./ripGrep-FGPUVH6Z.js");return new c(this)}):(uj(this,new kj(this.getUseRipgrep(),this.getUseBuiltinRipgrep(),l||"ripgrep is not available")),await s(A.GREP,async()=>{let{GrepTool:c}=await import("./grep-QMU4OMPK.js");return new c(this)}))}else await s(A.GREP,async()=>{let{GrepTool:a}=await import("./grep-QMU4OMPK.js");return new a(this)});if(await s(A.GLOB,async()=>{let{GlobTool:a}=await import("./glob-MDLZ74XZ.js");return new a(this)}),await s(A.EDIT,async()=>{let{EditTool:a}=await import("./edit-C4NER5YK.js");return new a(this)}),await s(A.NOTEBOOK_EDIT,async()=>{let{NotebookEditTool:a}=await import("./notebook-edit-3SYYLOZB.js");return new a(this)}),await s(A.WRITE_FILE,async()=>{let{WriteFileTool:a}=await import("./write-file-S7CRH7VA.js");return new a(this)}),await s(A.SHELL,async()=>{let{ShellTool:a}=await import("./shell-KW3VBBYV.js");return new a(this)}),await s(A.TODO_WRITE,async()=>{let{TodoWriteTool:a}=await import("./todoWrite-DKJAYA4S.js");return new a(this)}),await s(A.UPDATE_GOAL,async()=>{let{UpdateGoalTool:a}=await import("./update-goal-6WDBMJ2I.js");return new a(this)}),await s(A.ASK_USER_QUESTION,async()=>{let{AskUserQuestionTool:a}=await import("./askUserQuestion-MFLZ7MGJ.js");return new a(this)}),this.sdkMode||(await s(A.EXIT_PLAN_MODE,async()=>{let{ExitPlanModeTool:a}=await import("./exitPlanMode-D5SNMRGJ.js");return new a(this)}),await s(A.ENTER_PLAN_MODE,async()=>{let{EnterPlanModeTool:a}=await import("./enterPlanMode-L74GNCED.js");return new a(this)})),await s(A.ENTER_WORKTREE,async()=>{let{EnterWorktreeTool:a}=await import("./enter-worktree-4LCYUYYU.js");return new a(this)}),await s(A.EXIT_WORKTREE,async()=>{let{ExitWorktreeTool:a}=await import("./exit-worktree-GASDDIUP.js");return new a(this)}),await s(A.WEB_FETCH,async()=>{let{WebFetchTool:a}=await import("./web-fetch-QP42GV23.js");return new a(this)}),await s(A.WEB_SEARCH,async()=>{let{WebSearchTool:a}=await import("./web-search-FURCBRRK.js");return new a(this)}),await s(A.SYMBOL_SEARCH,async()=>{let{SymbolSearchTool:a}=await import("./symbol-search-WVNUJRET.js");return new a(this)}),this.isLspEnabled()&&this.getLspClient()&&await s(A.LSP,async()=>{let{LspTool:a}=await import("./lsp-P3GKBOP3.js");return new a(this)}),await o(),this.isCronEnabled()&&(await s(A.CRON_CREATE,async()=>{let{CronCreateTool:a}=await import("./cron-create-JHL5JGIM.js");return new a(this)}),await s(A.CRON_LIST,async()=>{let{CronListTool:a}=await import("./cron-list-R3YHZBHA.js");return new a(this)}),await s(A.CRON_DELETE,async()=>{let{CronDeleteTool:a}=await import("./cron-delete-K2R3KI2W.js");return new a(this)})),this.isAgentTeamEnabled()&&(await s(A.TEAM_CREATE,async()=>{let{TeamCreateTool:a}=await import("./team-create-4JLJ6GQN.js");return new a(this)}),await s(A.TEAM_DELETE,async()=>{let{TeamDeleteTool:a}=await import("./team-delete-DEPXAMUE.js");return new a(this)}),await s(A.TASK_CREATE,async()=>{let{TaskCreateTool:a}=await import("./task-create-ZZTSVXZN.js");return new a(this)}),await s(A.TASK_UPDATE,async()=>{let{TaskUpdateTool:a}=await import("./task-update-XZWORLJB.js");return new a(this)}),await s(A.TASK_LIST,async()=>{let{TaskListTool:a}=await import("./task-list-6I64SK7E.js");return new a(this)})),this.isWorkflowsEnabled()&&await s(A.WORKFLOW,async()=>{let{WorkflowTool:a}=await import("./workflow-ODYOFAKB.js");return new a(this)}),this.isComputerUseEnabled()){let{registerComputerUseTools:a}=await import("./computer-use-Z4JLQKGC.js");await a(s,this)}if(await s(A.MONITOR,async()=>{let{MonitorTool:a}=await import("./monitor-DOIBVKS6.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 KVe="refs/notes/ai-attribution";function Sue(r,e){let t=JSON.stringify(r);return Buffer.byteLength(t,"utf-8")>30720?null:{command:"git",args:["notes",`--ref=${KVe}`,"add","-f","-m",t,e]}}var Gue=Ve(Va(),1);g();import*as Cue from"node:fs";var _b=class extends Error{constructor(t,n){super(t);this.errorType=n;Object.setPrototypeOf(this,new.target.prototype)}name="StructuredToolError"};function XA(r){return r instanceof _b||typeof r=="object"&&r!==null&&r.name==="StructuredToolError"&&"errorType"in r}async function Eue(r,e,t,n={}){let s;try{s=await Cue.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 ${A.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 ${A.READ_FILE} first.`}}return{ok:!0}}let p=`Could not stat ${e} to verify prior read (${f??"unknown error"}). Re-read with the ${A.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 ${A.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 ${A.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 ${A.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 ${A.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 ${A.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 ${A.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 ${A.READ_FILE} tool first to load the current content ${u} before ${t} it.`;return{ok:!1,type:"edit_requires_prior_read",rawMessage:h,displayMessage:`${A.READ_FILE} required before ${l}.`}}g();var Aue=Ve(Va(),1);var Tue=new Set(["+","?","|","(",")","{","}"]),YVe=new Set(["*","+","?"]);function Rue(r){let e=r.trim(),t=e.match(/^\s*sed\s+/);if(!t)return null;let n;try{n=(0,Aue.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(JVe(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||XVe(l)||c.startsWith("~")||c.includes("$"))return null;let h=s8e(l);if(h===null)return null;let d={filePath:c,...h,extendedRegex:a};return ZVe(d)?d:null}function JVe(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 XVe(r){return r.includes("`")||/\$(?:[A-Za-z_][A-Za-z0-9_]*|\{|\(|\d|[#?@$!*])/u.test(r)}function ZVe(r){try{let e=Iue(r);return QVe(e)||e8e(e)||(new RegExp(e),t8e(r.replacement,r8e(e)))?!1:!n8e(e)}catch{return!1}}function QVe(r){return/\[\[:[A-Za-z]+:\]\]/u.test(r)}function e8e(r){return/\\[<>dDwWsS]/u.test(r)}function t8e(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 r8e(r){let e=0;for(let t=0;t<r.length;t++){let n=r[t];if(n==="\\"){t++;continue}if(n==="["){t=Pue(r,t);continue}n==="("&&r[t+1]!=="?"&&e++}return e}function n8e(r){let e=[];for(let t=0;t<r.length;t++){let n=r[t];if(n==="\\"){t++;continue}if(n==="["){t=Pue(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=kue(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=kue(r,t);s!==null&&(e.length>0&&(e[e.length-1].hasQuantifier=!0),t=s-1)}return!1}function Pue(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 kue(r,e){let t=r[e];if(t===void 0)return null;if(YVe.has(t))return e+1;if(t!=="{")return null;let n=e+1,s=!1;for(;xue(r[n]);)s=!0,n++;if(!s)return null;if(r[n]===",")for(n++;xue(r[n]);)n++;return r[n]==="}"?n+1:null}function xue(r){return r!==void 0&&r>="0"&&r<="9"}function s8e(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"||!i8e(s)||o8e(n)?null:{pattern:t,replacement:n,flags:s}}function i8e(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 o8e(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 Mue(r,e){if(r.length===0)return"";let t=Iue(e),n=l8e(e.flags),s=e.flags.includes("g");try{let o=new RegExp(t,"g"),a=r.split(/(\n)/);return(r.endsWith(`
|
|
2187
|
+
`),UVe.warn(t),{...VA}}return r}function nB(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 GVe=[A.READ_FILE,A.EDIT,A.NOTEBOOK_EDIT,A.SHELL],VVe=Object.freeze(new Set),bue=!1,ap=class{sessionId;sessionData;pendingStartupWorktreeNotice=null;debugLogger;toolRegistry;pendingMcpBudgetCallback;promptRegistry;subagentManager;memoryPressureConfig;memoryPressureMonitor;backgroundTaskRegistry=new iA;monitorRegistry=new $E;backgroundAgentResumeService;backgroundShellRegistry=new UE;workflowRunRegistry=new HE;fileReadCache=new iy;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=Rm();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??yue(),!bue&&hr.env&&(hr.env.MATILDA_CODE_SESSION_ID=this.sessionId,bue=!0),this.sessionData=e.sessionData,iR(this),this.debugLogger=F(),this.embeddingModel=e.embeddingModel??MR,this.fileSystemService=new aE,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=qVe(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??PR,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={...HVe(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??wG(),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??BVe,this.truncateToolOutputLines=e.truncateToolOutputLines??jVe,this.toolOutputBatchBudget=e.toolOutputBatchBudget??zVe,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 $B(this),this.eventEmitter=e.eventEmitter,this.arenaAgentClient=Xb.create(),this.agentsSettings=e.agents??{},this.worktreeSettings=e.worktree??{},e.contextFileName&&NB(e.contextFileName),this.modelsConfig=new Fb({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&&oj(this);let o=this.getProxy();o&&(0,JA.setGlobalDispatcher)(new JA.ProxyAgent(o)),this.geminiClient=new WA(this),this.chatRecordingService=this.chatRecordingEnabled?new jd(this):void 0,this.extensionManager=new Ux({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=pP(e.stopHookBlockingCap),this.userHooks=e.userHooks,this.projectHooks=e.projectHooks,this.hooks=e.hooks,this.memoryManager=new fb}async initialize(e){if(this.initialized)throw Error("Config was already initialized");this.initialized=!0,this.debugLogger.info("Config initialization started"),this.getFileService(),this.promptRegistry=new KA,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 vp(this),await this.hookSystem.initialize(),this.debugLogger.debug("Hook system initialized"),this.messageBus=new X_,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 b_(this),this.skillManager=new T_(this),this.getBareMode()?await this.skillManager.refreshCache():await this.skillManager.startWatching(),this.debugLogger.debug("Skill manager initialized"),this.memoryPressureConfig=WVe(),this.memoryPressureMonitor=new wb(this,this.memoryPressureConfig),this.permissionManager=new xm(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 Vj().getInstallationId(),dR(this,new SR(this)),this.debugLogger.info("Config initialization completed"),this.getBareMode()||(async()=>{try{let a=await new rs(this.targetDir).getRepoTopLevel()??this.targetDir,l=bn.join(a,".matilda","worktrees");try{await vue.access(l)}catch{this.debugLogger.debug(`Stale worktree sweep skipped: ${l} does not exist`);return}let c=await hue(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)||kC(n)!=="connected"&&t.push(n);return t}async refreshHierarchicalMemory(e="refresh"){let{memoryContent:t,fileCount:n,conditionalRules:s,projectRoot:o}=await Gle(this.getWorkingDir(),this.getMemoryDiscoveryDirectories(),this.getFileService(),this.getExtensionContextFilePaths(),this.isTrustedFolder(),this.getImportFormat(),this.contextRuleExcludes,{explicitOnly:this.getBareMode(),loadReason:e,onInstructionsLoaded:OA(()=>this.hookSystem)});if(this.getManagedAutoMemoryEnabled()){let[a,l]=await Promise.all([FW(this.getProjectRoot()),UW().catch(()=>null)]);this.setUserMemory(this.memoryManager.appendToUserMemory(t,Ar(this.getProjectRoot()),a,{memoryDir:Vs(),indexContent:l}))}else this.setUserMemory(t);this.setGeminiMdFileCount(n),this.conditionalRulesRegistry=new Y_(s,o)}buildMemoryContextWarning(e){let t=this.getContentGeneratorConfig()?.contextWindowSize??this.modelsConfig.getGenerationConfig().contextWindowSize??Np(this.getModel(),"input");if(!t||t<=0||!e)return;let n=Math.ceil(e.length/Es),s=Math.floor(t*wue);if(!(n<=s))return`Warning: Loaded MATILDA.md/context instructions use about ${n.toLocaleString()} tokens, more than ${Math.round(wue*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 gm()?.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}=LR(this,e,this.modelsConfig.getGenerationConfig(),this.modelsConfig.getGenerationConfigSources(),{strictModelProvider:this.modelsConfig.isStrictModelProviderSelection()}),l=o;this.contentGenerator=await Cd(l,this,s?!0:t),this.contentGeneratorConfig=l,this.contentGeneratorConfigSources=a,this.baseLlmClient=new Gp(this.contentGenerator,this);let c=this.getMessageBus();!this.getDisableAllHooks()&&c&&ym(c,`Successfully authenticated with ${e}`,"auth_success","Authentication successful").catch(()=>{})}getBaseLlmClient(){if(!this.baseLlmClient)if(this.contentGenerator)this.baseLlmClient=new Gp(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??yue(),hr.env&&(hr.env.MATILDA_CODE_SESSION_ID=this.sessionId),this.sessionData=t,iR(this),this.debugLogger=F(),this.chatRecordingService=this.chatRecordingEnabled?new jd(this):void 0,this.getFileReadCache().clear(),this.toolResultBudget.bytesWritten=0,this.getMemoryPressureMonitor()?.resetForNewSession(),this.fileHistoryService=void 0,aj(this.sessionId),sj(),Qs.resetInstance(),this.initialized&&dR(this,new SR(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 Jz(o),await OP(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 OP(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 gm()?.contentGeneratorConfig??this.contentGeneratorConfig}getContentGeneratorConfigSources(){return Object.keys(this.contentGeneratorConfigSources).length===0&&this.modelsConfig?this.modelsConfig.getGenerationConfigSources():this.contentGeneratorConfigSources}getModel(){return this.getContentGeneratorConfig()?.model||this.modelsConfig.getModel()}getModelDisplayName(){return this.modelDisplayName||this.modelsConfig.getModelDisplayName(this.getModel())}getPublicModelId(e){return this.modelsConfig.getPublicModelId(e)}isManagedMatildaModel(e){return this.modelsConfig.isManagedMatildaModel(e)}onModelChange(e){return this.modelChangeListeners.add(e),()=>{this.modelChangeListeners.delete(e)}}notifyModelChangeListeners(){let e=this.getModel();for(let t of this.modelChangeListeners)t(e)}getFastModel(){let e=this.resolveFastModelSelector();if(!e||!(e.authType?this.getAllConfiguredModels([e.authType]):this.getAllConfiguredModels()).some(s=>s.id===e.modelId))return;let n=Ys(this.fastModel);return n?.authType?`${n.authType}:${e.modelId}`:e.modelId}resolveFastModelSelector(){if(this.fastModel)try{return Ys(this.fastModel,{currentAuthType:this.getContentGeneratorConfig()?.authType,getAvailableModels:e=>this.getAllConfiguredModels(e)})}catch{return}}setFastModel(e){this.fastModel=e||void 0}async setModel(e,t){await this.modelsConfig.setModel(e,t),this.contentGeneratorConfig&&(this.contentGeneratorConfig.model=e),this.notifyModelChangeListeners()}async handleModelChange(e,t){if(this.contentGeneratorConfig){if(e==="matilda-oauth"&&!t){let{config:n,sources:s}=LR(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{ij()&&await lj()}}getPromptRegistry(){return this.promptRegistry}getDebugMode(){return this.debugMode}getQuestion(){return this.question}getSystemPrompt(){return this.systemPrompt}getAppendSystemPrompt(){return this.appendSystemPrompt}getCoreTools(){return this.getBareMode()?GVe: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?.()??VVe}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 sB("Cannot enable privileged approval modes in an untrusted folder.");e==="plan"&&this.approvalMode!=="plan"?(this.prePlanMode=this.approvalMode,this.planGateState=sz(++this.planGateEntryCounter)):e!=="plan"&&this.approvalMode==="plan"&&(this.prePlanMode=void 0,this.planGateState=void 0);let t=e==="auto"?"default":e,n=this.approvalMode;this.permissionManager&&n==="auto"&&this.permissionManager.restoreDangerousRules(),n!==t&&(this.autoModeDenialState=$0()),this.approvalMode=t}getPlansDir(){return this.plansDir}assertPlansDirWithinTargetDir(){this.plansDirectoryConfigured&&fe.assertPathWithinDirectory(this.plansDir,this.targetDir,"plansDirectory must resolve within the project root.")}assertPlanFilePathWithinTargetDir(e){this.plansDirectoryConfigured&&fe.assertPathWithinDirectory(e,this.targetDir,"plansDirectory must resolve within the project root.")}addLegacyPlanLocationWarning(){try{if(!this.plansDirectoryConfigured)return;let e=fe.getPlansDir(),t=this.getPlanFileNames(e);if(t.length===0)return;let n=new Set(this.getPlanFileNames(this.plansDir));if(t.filter(o=>!n.has(o)).length===0)return;this.warnings.push(`Warning: Saved plan files exist at ${e}, but plansDirectory is configured to use ${this.plansDir}. Move existing plan files to ${this.plansDir} if you want to keep using them.`)}catch(e){let t=`Failed to check legacy plan directory migration warning: ${e instanceof Error?e.message:String(e)}`;this.warnings.push(t),this.debugLogger.warn(t,e)}}getPlanFileNames(e){try{return 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??Dj}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??PR}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 wb(this,this.memoryPressureConfig)}return this.memoryPressureMonitor}getCronScheduler(){return this.cronScheduler||(this.cronScheduler=new $C(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 lv(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 Kle(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()||!Uj()}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 jd(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 dv(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 aA(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 iy),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 AC(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(A.STRUCTURED_OUTPUT,async()=>{let{SyntheticOutputTool:l}=await import("./syntheticOutput-LLA4WQR7.js");return new l(a)})};if(this.getBareMode())return await s(A.READ_FILE,async()=>{let{ReadFileTool:a}=await import("./read-file-HEVXSNSO.js");return new a(this)}),await s(A.EDIT,async()=>{let{EditTool:a}=await import("./edit-ECFAMGBL.js");return new a(this)}),await s(A.NOTEBOOK_EDIT,async()=>{let{NotebookEditTool:a}=await import("./notebook-edit-K3O75JIG.js");return new a(this)}),await s(A.SHELL,async()=>{let{ShellTool:a}=await import("./shell-Z6CWCFSW.js");return new a(this)}),await o(),this.debugLogger.debug(`ToolRegistry created: ${JSON.stringify(n.getAllToolNames())} (${n.getAllToolNames().length} tools)`),n;if(await s(A.TOOL_SEARCH,async()=>{let{ToolSearchTool:a}=await import("./tool-search-47TA6SG4.js");return new a(this)}),await s(A.AGENT,async()=>{let{AgentTool:a}=await import("./agent-HSHZY2QX.js");return new a(this)}),await s(A.TASK_STOP,async()=>{let{TaskStopTool:a}=await import("./task-stop-UKRXMCZV.js");return new a(this)}),await s(A.SEND_MESSAGE,async()=>{let{SendMessageTool:a}=await import("./send-message-K3T7GVHO.js");return new a(this)}),await s(A.SKILL,async()=>{let{SkillTool:a}=await import("./skill-YXHHDMLR.js");return new a(this)}),await s(A.LS,async()=>{let{LSTool:a}=await import("./ls-4QPI2E7A.js");return new a(this)}),await s(A.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 n5(this.getUseBuiltinRipgrep())}catch(c){l=Q(c)}a?await s(A.GREP,async()=>{let{RipGrepTool:c}=await import("./ripGrep-2ZK4OFYZ.js");return new c(this)}):(uj(this,new kj(this.getUseRipgrep(),this.getUseBuiltinRipgrep(),l||"ripgrep is not available")),await s(A.GREP,async()=>{let{GrepTool:c}=await import("./grep-6J5W5EJ7.js");return new c(this)}))}else await s(A.GREP,async()=>{let{GrepTool:a}=await import("./grep-6J5W5EJ7.js");return new a(this)});if(await s(A.GLOB,async()=>{let{GlobTool:a}=await import("./glob-42PS64FP.js");return new a(this)}),await s(A.EDIT,async()=>{let{EditTool:a}=await import("./edit-ECFAMGBL.js");return new a(this)}),await s(A.NOTEBOOK_EDIT,async()=>{let{NotebookEditTool:a}=await import("./notebook-edit-K3O75JIG.js");return new a(this)}),await s(A.WRITE_FILE,async()=>{let{WriteFileTool:a}=await import("./write-file-D7TUBP7Q.js");return new a(this)}),await s(A.SHELL,async()=>{let{ShellTool:a}=await import("./shell-Z6CWCFSW.js");return new a(this)}),await s(A.TODO_WRITE,async()=>{let{TodoWriteTool:a}=await import("./todoWrite-DKJAYA4S.js");return new a(this)}),await s(A.UPDATE_GOAL,async()=>{let{UpdateGoalTool:a}=await import("./update-goal-6WDBMJ2I.js");return new a(this)}),await s(A.ASK_USER_QUESTION,async()=>{let{AskUserQuestionTool:a}=await import("./askUserQuestion-MFLZ7MGJ.js");return new a(this)}),this.sdkMode||(await s(A.EXIT_PLAN_MODE,async()=>{let{ExitPlanModeTool:a}=await import("./exitPlanMode-OCEXPM5C.js");return new a(this)}),await s(A.ENTER_PLAN_MODE,async()=>{let{EnterPlanModeTool:a}=await import("./enterPlanMode-HJDOWUYD.js");return new a(this)})),await s(A.ENTER_WORKTREE,async()=>{let{EnterWorktreeTool:a}=await import("./enter-worktree-C3HT4E6R.js");return new a(this)}),await s(A.EXIT_WORKTREE,async()=>{let{ExitWorktreeTool:a}=await import("./exit-worktree-GYSJXOUF.js");return new a(this)}),await s(A.WEB_FETCH,async()=>{let{WebFetchTool:a}=await import("./web-fetch-QP42GV23.js");return new a(this)}),await s(A.WEB_SEARCH,async()=>{let{WebSearchTool:a}=await import("./web-search-FURCBRRK.js");return new a(this)}),await s(A.SYMBOL_SEARCH,async()=>{let{SymbolSearchTool:a}=await import("./symbol-search-WVNUJRET.js");return new a(this)}),this.isLspEnabled()&&this.getLspClient()&&await s(A.LSP,async()=>{let{LspTool:a}=await import("./lsp-P3GKBOP3.js");return new a(this)}),await o(),this.isCronEnabled()&&(await s(A.CRON_CREATE,async()=>{let{CronCreateTool:a}=await import("./cron-create-JHL5JGIM.js");return new a(this)}),await s(A.CRON_LIST,async()=>{let{CronListTool:a}=await import("./cron-list-R3YHZBHA.js");return new a(this)}),await s(A.CRON_DELETE,async()=>{let{CronDeleteTool:a}=await import("./cron-delete-K2R3KI2W.js");return new a(this)})),this.isAgentTeamEnabled()&&(await s(A.TEAM_CREATE,async()=>{let{TeamCreateTool:a}=await import("./team-create-TV7R2OKS.js");return new a(this)}),await s(A.TEAM_DELETE,async()=>{let{TeamDeleteTool:a}=await import("./team-delete-DEPXAMUE.js");return new a(this)}),await s(A.TASK_CREATE,async()=>{let{TaskCreateTool:a}=await import("./task-create-ZZTSVXZN.js");return new a(this)}),await s(A.TASK_UPDATE,async()=>{let{TaskUpdateTool:a}=await import("./task-update-XZWORLJB.js");return new a(this)}),await s(A.TASK_LIST,async()=>{let{TaskListTool:a}=await import("./task-list-6I64SK7E.js");return new a(this)})),this.isWorkflowsEnabled()&&await s(A.WORKFLOW,async()=>{let{WorkflowTool:a}=await import("./workflow-IV7OR3QI.js");return new a(this)}),this.isComputerUseEnabled()){let{registerComputerUseTools:a}=await import("./computer-use-E54F2OXO.js");await a(s,this)}if(await s(A.MONITOR,async()=>{let{MonitorTool:a}=await import("./monitor-JGJ5W74B.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 KVe="refs/notes/ai-attribution";function Sue(r,e){let t=JSON.stringify(r);return Buffer.byteLength(t,"utf-8")>30720?null:{command:"git",args:["notes",`--ref=${KVe}`,"add","-f","-m",t,e]}}var Gue=Ve(Va(),1);g();import*as Cue from"node:fs";var _b=class extends Error{constructor(t,n){super(t);this.errorType=n;Object.setPrototypeOf(this,new.target.prototype)}name="StructuredToolError"};function XA(r){return r instanceof _b||typeof r=="object"&&r!==null&&r.name==="StructuredToolError"&&"errorType"in r}async function Eue(r,e,t,n={}){let s;try{s=await Cue.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 ${A.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 ${A.READ_FILE} first.`}}return{ok:!0}}let p=`Could not stat ${e} to verify prior read (${f??"unknown error"}). Re-read with the ${A.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 ${A.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 ${A.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 ${A.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 ${A.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 ${A.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 ${A.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 ${A.READ_FILE} tool first to load the current content ${u} before ${t} it.`;return{ok:!1,type:"edit_requires_prior_read",rawMessage:h,displayMessage:`${A.READ_FILE} required before ${l}.`}}g();var Aue=Ve(Va(),1);var Tue=new Set(["+","?","|","(",")","{","}"]),YVe=new Set(["*","+","?"]);function Rue(r){let e=r.trim(),t=e.match(/^\s*sed\s+/);if(!t)return null;let n;try{n=(0,Aue.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(JVe(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||XVe(l)||c.startsWith("~")||c.includes("$"))return null;let h=s8e(l);if(h===null)return null;let d={filePath:c,...h,extendedRegex:a};return ZVe(d)?d:null}function JVe(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 XVe(r){return r.includes("`")||/\$(?:[A-Za-z_][A-Za-z0-9_]*|\{|\(|\d|[#?@$!*])/u.test(r)}function ZVe(r){try{let e=Iue(r);return QVe(e)||e8e(e)||(new RegExp(e),t8e(r.replacement,r8e(e)))?!1:!n8e(e)}catch{return!1}}function QVe(r){return/\[\[:[A-Za-z]+:\]\]/u.test(r)}function e8e(r){return/\\[<>dDwWsS]/u.test(r)}function t8e(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 r8e(r){let e=0;for(let t=0;t<r.length;t++){let n=r[t];if(n==="\\"){t++;continue}if(n==="["){t=Pue(r,t);continue}n==="("&&r[t+1]!=="?"&&e++}return e}function n8e(r){let e=[];for(let t=0;t<r.length;t++){let n=r[t];if(n==="\\"){t++;continue}if(n==="["){t=Pue(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=kue(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=kue(r,t);s!==null&&(e.length>0&&(e[e.length-1].hasQuantifier=!0),t=s-1)}return!1}function Pue(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 kue(r,e){let t=r[e];if(t===void 0)return null;if(YVe.has(t))return e+1;if(t!=="{")return null;let n=e+1,s=!1;for(;xue(r[n]);)s=!0,n++;if(!s)return null;if(r[n]===",")for(n++;xue(r[n]);)n++;return r[n]==="}"?n+1:null}function xue(r){return r!==void 0&&r>="0"&&r<="9"}function s8e(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"||!i8e(s)||o8e(n)?null:{pattern:t,replacement:n,flags:s}}function i8e(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 o8e(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 Mue(r,e){if(r.length===0)return"";let t=Iue(e),n=l8e(e.flags),s=e.flags.includes("g");try{let o=new RegExp(t,"g"),a=r.split(/(\n)/);return(r.endsWith(`
|
|
2188
2188
|
`)?a.slice(0,-1):a).map((c,u)=>u%2===1?c:c8e(c,o,e.replacement,{occurrence:n,replaceAll:s})).join("")}catch(o){throw new Error(`sed pattern simulation failed: ${Q(o)}`)}}function Iue(r){let e=a8e(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];Tue.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+=Tue.has(o)?`\\${o}`:o}return t}function a8e(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 l8e(r){let e=r.match(/[1-9][0-9]*/);return e?Number(e[0]):null}function c8e(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 u8e(c,d,t)})}function u8e(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 d8e(r){let e=r.trimEnd();return!e.endsWith("&")||e.endsWith("&&")||e.endsWith("\\&")?r:e.slice(0,-1).trimEnd()}function Due(r){return r.replace(/[\\"$`]/g,"\\$&")}function Lue(r){return r.replace(/'/g,"'\\''")}function ZA(r){let e=null;for(let t of r)e=t;return e}function Nue(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 Fue(r){return r?{start:r.index??0,end:(r.index??0)+r[0].length}:null}function $ue(r,e){let t=Fue(r),n=Fue(e);return!!(t&&n&&t.start>=n.start&&t.end<=n.end)}function Uue(r,e){return r&&e?$ue(e,r)?{match:r,isDouble:!0}:$ue(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 eR(r){let e;try{e=(0,Gue.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=Bue(e[t]);if(n===null)break;if(Hue.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"?p8e:n==="sudo"?m8e:null;if(o&&g8e(s,o))return null;(n==="sudo"&&h8e.has(s)||n==="env"&&f8e.has(s))&&t<e.length&&t++}if(n==="env")for(;t<e.length;){let s=Bue(e[t]);if(s===null)break;if(Hue.has(s))return null;t++}}return e.slice(t)}var h8e=new Set(["-u","-g","-h","-D","-r","-t","-C","--user","--group","--host","--chdir","--role","--type"]),f8e=new Set(["-u","--unset","-S","--split-string"]),p8e=new Set(["-C","--chdir"]),m8e=new Set(["-D","--chdir"]);function g8e(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 Hue=new Set(["GIT_DIR","GIT_WORK_TREE","GIT_COMMON_DIR","GIT_INDEX_FILE"]);function Bue(r){let e=/^([A-Za-z_][A-Za-z0-9_]*)=/.exec(r);return e?e[1]:null}var y8e=new Set(["-c","-C","--git-dir","--work-tree","--namespace","--exec-path","--config-env","--super-prefix","--list-cmds"]),w8e=new Set(["-C","--git-dir","--work-tree"]);function jue(r){let e=r.trim();return e==="."||e==="./"}function lB(r){let e=1,t=!1;for(;e<r.length;){let n=r[e];if(y8e.has(n)){let s=r[e+1]??"";n==="-C"?jue(s)||(t=!0):w8e.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);jue(s)||(t=!0),e++;continue}if(n.startsWith("-")){e++;continue}return{subcommand:n,changesCwd:t}}return{subcommand:void 0,changesCwd:t}}function zue(r){let e=!1,t=!1,n=!1;for(let s of Ni(r)){let o=eR(s);if(!o||o.length===0)continue;let a=o[0];if(a==="cd"||a==="pushd"){!e&&cB(o)&&(n=!0);continue}if(a==="popd"){e||(n=!0);continue}if(a==="git"){let{subcommand:l,changesCwd:c}=lB(o);l==="commit"?(e=!0,!n&&!c&&(t=!0)):c&&!e&&(n=!0)}}return{hasCommit:e,attributableInCwd:t}}var _8e=new Set(["--repo","-R","--hostname"]);function b8e(r){let e=1;for(;e<r.length;){let t=r[e];if(_8e.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 cB(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 v8e(r){let e=!1;for(let t of Ni(r)){let n=eR(t);if(!n||n.length===0)continue;let s=n[0];if(s==="cd"||s==="pushd"){!e&&cB(n)&&(e=!0);continue}if(s==="popd"){e=!0;continue}if(s!=="git")continue;let{subcommand:o,changesCwd:a}=lB(n);if(o==="commit"&&!e&&!a)return n.includes("--amend")||n.some(l=>l.startsWith("--amend="));a&&!e&&(e=!0)}return!1}function S8e(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=eR(n);if(!a||a.length===0)continue;let l=a[0];if(l==="cd"||l==="pushd"){!t&&cB(a)&&(t=!0);continue}if(l==="popd"){t=!0;continue}if(l==="git"){let{subcommand:c,changesCwd:u}=lB(a);if(c==="commit"&&!t&&!u)return{start:s,end:o};u&&!t&&(t=!0)}}return null}function C8e(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=eR(t);if(!o||o[0]!=="gh")continue;let a=b8e(o);if(a[0]==="pr"&&(a[1]==="create"||a[1]==="new"))return{start:n,end:s}}return null}var E8e=40,T8e=1024;function k8e(r){let e=new Map,t=r.split(`
|
|
2189
2189
|
`).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,T8e);continue}let l=parseInt(o[1],10),c=parseInt(o[2],10);Number.isNaN(l)||Number.isNaN(c)||e.set(a,(l+c)*E8e)}return e}var iB=1e3,x8e=12e4,A8e=200,que=1e4,R8e=1e3;function P8e(r){return Math.max(R8e,Math.floor(r/2))}function M8e(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 c6t(r){return Vue(r)?.description??null}function Vue(r){let{command:e,comment:t}=Yue(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])&&![";","&","|",`
|
|
2190
2190
|
`].includes(s[o]);)o++;let l=s.slice(a,o),c=L8e(l);if(c===null||c<2)return null;let u=s.slice(o),h=N8e(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(Kue)){let w=D8e(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>I8e?{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 Kue="intentional-sleep:",I8e=10*60,O8e=8;function D8e(r){let e=r.slice(Kue.length).trim();return e.length>=O8e?e:null}function L8e(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 N8e(r){let e=0;for(;e<r.length&&r[e]!==`
|