@maincode-ai/matilda-code 0.21.6-preview.0 → 0.21.7-nightly.20260919.d953e31d2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/chunks/{agent-KYTWNT5B.js → agent-6WJWHK33.js} +1 -1
  2. package/chunks/{agent-headless-O2QFYUGL.js → agent-headless-QEKAFQC2.js} +1 -1
  3. package/chunks/{chunk-AC7V5HGT.js → chunk-77N2Q3QZ.js} +8 -8
  4. package/chunks/{chunk-LB2LZKIS.js → chunk-IC3HJLOD.js} +1 -1
  5. package/chunks/{chunk-N5UZND2H.js → chunk-JF6ED3QG.js} +1 -1
  6. package/chunks/{chunk-ERD4AVF5.js → chunk-L6RZIQQE.js} +1 -1
  7. package/chunks/{chunk-OCYTOKZC.js → chunk-SNTDBBLK.js} +1 -1
  8. package/chunks/{chunk-BQFYMLHH.js → chunk-TI3VD43G.js} +1 -1
  9. package/chunks/{chunk-2SD4SGKF.js → chunk-UY56RCKZ.js} +2 -2
  10. package/chunks/{computer-use-PHYIWQFA.js → computer-use-NPZQKWAA.js} +1 -1
  11. package/chunks/{contextCommand-URYU4N6P.js → contextCommand-3E2GKMYJ.js} +1 -1
  12. package/chunks/{edit-ZLVT3HLS.js → edit-BV6UXJHV.js} +1 -1
  13. package/chunks/{enter-worktree-TZ4BHFV3.js → enter-worktree-WFRS6DOO.js} +1 -1
  14. package/chunks/{enterPlanMode-H6P74G54.js → enterPlanMode-6XO2FCD4.js} +1 -1
  15. package/chunks/{exit-worktree-TRFH3EKK.js → exit-worktree-YRVXXUJG.js} +1 -1
  16. package/chunks/{exitPlanMode-3DSR3TTH.js → exitPlanMode-XSANODDU.js} +1 -1
  17. package/chunks/{geminiContentGenerator-PULU6AOZ.js → geminiContentGenerator-YT3R7XR7.js} +1 -1
  18. package/chunks/{glob-JGVGPH7O.js → glob-72QENSN5.js} +1 -1
  19. package/chunks/{grep-YXF7LG25.js → grep-XOHANNB6.js} +1 -1
  20. package/chunks/{matildaAgentContentGenerator-MYD7CTHU.js → matildaAgentContentGenerator-ZKC3SSAZ.js} +1 -1
  21. package/chunks/{matildaContentGenerator-NTMW3R45.js → matildaContentGenerator-GQZIZKRP.js} +1 -1
  22. package/chunks/{monitor-DBD44UCH.js → monitor-KB6FBBGO.js} +1 -1
  23. package/chunks/{notebook-edit-UBSCMF55.js → notebook-edit-L6PI7HSF.js} +1 -1
  24. package/chunks/{openaiContentGenerator-SDDETC25.js → openaiContentGenerator-6K7CKWZW.js} +1 -1
  25. package/chunks/{ripGrep-RTSNQ27E.js → ripGrep-INSEEE7H.js} +1 -1
  26. package/chunks/{scheduler-APKZPCNX.js → scheduler-LOT5MRJN.js} +1 -1
  27. package/chunks/{serve-GCZSYJ4D.js → serve-DLXQ2XQC.js} +1 -1
  28. package/chunks/{shell-JDSST5O4.js → shell-VENIQ6VU.js} +1 -1
  29. package/chunks/{skill-GLBTH3Q4.js → skill-CZPMRNLD.js} +1 -1
  30. package/chunks/{src-FSJDBAGQ.js → src-HILUWMHH.js} +1 -1
  31. package/chunks/{team-create-TQHT5HCX.js → team-create-QFMW37FS.js} +1 -1
  32. package/chunks/{workflow-WMRTYTZE.js → workflow-YDVW6LM6.js} +2 -2
  33. package/chunks/{write-file-FMBJAKLZ.js → write-file-ML7S4MKZ.js} +1 -1
  34. package/cli.js +445 -443
  35. 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 xe,b as mz,c as kP,d as gz,e as B,f as yz,g as Ze,h as Tt,i as wz,j as _z,k as rr,l as oe,m as le,n as mr,o as Ut,p as xP,q as AP,r as At,s as Vn,t as de,u as Zt,v as bz,w as RP,x as vz,y as Sz}from"./chunk-TZIDSCTF.js";import{d as kz,e as xz,g as Oz,h as Dz,i as Lz,j as PP,m as Nz}from"./chunk-ROETRE5J.js";import{d as Fz,k as MP,n as $z,p as Uz}from"./chunk-INAZKGGR.js";import{b as Che,i as Az,j as Rz,k as Pz,o as rm,p as Mz,r as Iz}from"./chunk-DCQKJTAX.js";import{a as Wt}from"./chunk-LSDMWVW6.js";import{a as lv,b as Ez,d as LP,e as dv}from"./chunk-MTMU7JYZ.js";import{a as Hz,b as Bz,c as nm}from"./chunk-TXMXCR7D.js";import{a as IP}from"./chunk-YULUB745.js";import{a as jz,b as zz,c as qz,d as OP,e as Wz,f as DP}from"./chunk-VYTYYCBR.js";import{a as wj,b as Ha,c as _j}from"./chunk-TISQNFB5.js";import{a as Bi,b as EP,c as $d,t as TP}from"./chunk-34DXSYJZ.js";import{a as uv,b as sm}from"./chunk-FWIVFCKF.js";import{b as Cz,g as cv,j as tm,k as Tz,l as As}from"./chunk-QKYGQLWC.js";import{a as nt,b as Ud,d as Bd,e as jd}from"./chunk-FRL6KOLY.js";import{b as No,d as iz,f as oz,i as ct,j as az,k as lz,l as cz,m as uz,n as dz,o as hz,p as fz,q as pz}from"./chunk-VWWEEU4V.js";import{b as Hd}from"./chunk-RNKDFE2S.js";import{a as sz}from"./chunk-Q2I3ARPJ.js";import{a as av}from"./chunk-OCYTOKZC.js";import{a as bj}from"./chunk-QHA3ZBRO.js";import{$ as vP,U as yP,V as J2,W as Q2,Z as Rc,_ as em,b as pP,ba as SP,c as mP,d as z2,e as gP,ea as iv,f as q2,ga as ov,pa as an,qa as CP,ta as Fd}from"./chunk-ERD4AVF5.js";import{a as Do,c as wP}from"./chunk-4F4DA5UI.js";import{e as _P,f as bP}from"./chunk-DC7LAFZZ.js";import{m as Nd,p as X2,r as Z2,v as Qp}from"./chunk-S7G6QPEP.js";import{a as Uj,b as Gr,c as xs,d as Hj,f as Bj}from"./chunk-4J6DC24J.js";import{a as W2,g as G2,h as V2,k as Ld,l as K2,m as Y2}from"./chunk-SDTWBD62.js";import{$a as Yb,$b as S2,$c as aP,Ab as f2,Ac as sP,B as Vj,Bb as p2,Bc as iP,Cb as m2,Cc as Oo,Db as g2,Eb as y2,Ec as oP,F as Id,G as Kj,Gb as YR,Ha as Xj,Ic as O2,Jb as w2,Mc as D2,Ob as _2,Oc as L2,Qc as Dd,Rc as N2,Sb as Od,Sc as F2,Tb as b2,Ub as v2,Va as Zj,Vc as tv,Yb as Xb,Za as Qj,_a as za,_b as JR,aa as Yj,ab as e2,ac as Tc,ad as Ac,bb as t2,bc as XR,bd as $2,cb as on,cd as rv,d as Oj,da as ja,dc as C2,ec as ZR,ed as lP,f as Io,fc as E2,fd as cP,g as Wb,ga as Yp,gb as VR,gc as QR,gd as uP,h as Gn,ha as Kb,hb as r2,hc as eP,i as Ba,ib as n2,ic as tP,id as dP,jb as s2,k as jj,kb as KR,kd as U2,l as zj,lb as i2,m as qj,mb as o2,mc as T2,nb as a2,nc as k2,ob as l2,oc as x2,od as H2,p as Cc,pb as c2,pd as B2,q as Kp,qb as u2,qd as j2,r as Wj,rb as d2,rc as rP,rd as hP,s as Gj,sb as h2,sc as Zb,t as Ec,tc as Qb,uc as R2,ud as fP,vb as Jb,vc as P2,vd as nv,wd as sv,xc as nP,ya as GR,yc as Zp,za as Jj,zc as M2}from"./chunk-B3NVKOSU.js";import{b as Hi,h as Mr,k as A2,l as kc,m as Ir,n as xc,o as Jp,s as ei,t as Xp,w as ev}from"./chunk-32PTAACU.js";import{a as I2}from"./chunk-32T6RWWT.js";import{b as Dj,c as vhe,d as She,e as Lj,f as Nj,g as Zs,i as Qs,j as Fj,k as qR,o as $j,p as R,q as Cn,r as Gb,s as Vb}from"./chunk-6B5BDE7S.js";import{a as nz}from"./chunk-RJX7DK4Y.js";import{a as tz,b as Lo,c as rz}from"./chunk-ESSYHTAZ.js";import{b as ez}from"./chunk-3YLXGE6T.js";import{b as Xe,c as ks,e as Md}from"./chunk-EQEQPZLQ.js";import{A as Rd,D as Ej,E as Tj,G as Xs,H as Pd,J as Sc,K as kj,N as BR,O as jR,P as fe,U as Pj,V as Mj,X as Ij,_ as zR,aa as $,b as Ot,c as zb,d as re,e as Mo,q as vj,s as Sj,v as Cj,w as sn}from"./chunk-VLYRNOD3.js";import{a as WR}from"./chunk-G7R2XEEF.js";import{g as qb,h as xj,l as Aj,n as Rj}from"./chunk-FWDMPRKU.js";import{a as __matilda_dirname,b as g}from"./chunk-GZPNIYVZ.js";import{a as Se,c as _he,d as N,e as bhe,f as Ve}from"./chunk-OWGSC52X.js";var w3=N((tet,y3)=>{"use strict";g();y3.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 T3=N((net,E3)=>{"use strict";g();var C3="(?:"+["\\|\\|","\\&\\&",";;","\\|\\&","\\<\\(","\\<\\<\\<",">>",">\\&","<\\&","[&;()|<>]"].join("|")+")",_3=new RegExp("^"+C3+"$"),b3="|&;()<> \\t",Yye='"((\\\\"|[^"])*?)"',Jye="'((\\\\'|[^'])*?)'",Xye=/^#$/,v3="'",S3='"',RM="$",Yc="",Zye=4294967296;for(PM=0;PM<4;PM++)Yc+=(Zye*Math.random()).toString(16);var PM,Qye=new RegExp("^"+Yc);function ewe(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 twe(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+Yc+JSON.stringify(n)+Yc:e+n}function rwe(r,e,t){t||(t={});var n=t.escape||"\\",s="(\\"+n+`['"`+b3+`]|[^\\s'"`+b3+"])+",o=new RegExp(["("+C3+")","("+s+"|"+Yye+"|"+Jye+")+"].join("|"),"g"),a=ewe(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(_3.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 twe(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==v3?f+=m:m===n?(y+=1,m=u.charAt(y),m===S3||m===n||m===RM?f+=m:f+=n+m):m===RM?f+=w():f+=m;else if(m===S3||m===v3)h=m;else{if(_3.test(m))return{op:u};if(Xye.test(m)){l=!0;var _={comment:r.slice(c.index+y+1)};return f.length?[f,_]:[_]}else m===n?d=!0:m===RM?f+=w():f+=m}}return p?{op:"glob",pattern:f}:f}).reduce(function(c,u){return typeof u>"u"?c:c.concat(u)},[])}E3.exports=function(e,t,n){var s=rwe(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("("+Yc+".*?"+Yc+")","g"));return l.length===1?o.concat(l[0]):o.concat(l.filter(Boolean).map(function(c){return Qye.test(c)?JSON.parse(c.split(Yc)[1]):c}))},[])}});var rl=N(MM=>{"use strict";g();MM.quote=w3();MM.parse=T3()});var r4=N((exports,module)=>{g();var Module=typeof Module<"u"?Module:{},ENVIRONMENT_IS_WEB=typeof window=="object",ENVIRONMENT_IS_WORKER=typeof importScripts=="function",ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",TreeSitter=function(){var initPromise,document=typeof window=="object"?{currentScript:window.document.currentScript}:null;class Parser{constructor(){this.initialize()}initialize(){throw new Error("cannot construct a Parser before calling `init()`")}static init(moduleOptions){return initPromise||(Module=Object.assign({},Module,moduleOptions),initPromise=new Promise(resolveInitPromise=>{var moduleOverrides=Object.assign({},Module),arguments_=[],thisProgram="./this.program",quit_=(r,e)=>{throw e},scriptDirectory="";function locateFile(r){return Module.locateFile?Module.locateFile(r,scriptDirectory):scriptDirectory+r}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=Se("fs"),nodePath=Se("path");scriptDirectory=__matilda_dirname+"/",readBinary=r=>{r=isFileURI(r)?new URL(r):nodePath.normalize(r);var e=fs.readFileSync(r);return e},readAsync=(r,e=!0)=>(r=isFileURI(r)?new URL(r):nodePath.normalize(r),new Promise((t,n)=>{fs.readFile(r,e?void 0:"utf8",(s,o)=>{s?n(s):t(e?o.buffer:o)})})),!Module.thisProgram&&process.argv.length>1&&(thisProgram=process.argv[1].replace(/\\/g,"/")),arguments_=process.argv.slice(2),typeof module<"u"&&(module.exports=Module),quit_=(r,e)=>{throw process.exitCode=r,e}}else(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)&&(ENVIRONMENT_IS_WORKER?scriptDirectory=self.location.href:typeof document<"u"&&document.currentScript&&(scriptDirectory=document.currentScript.src),scriptDirectory.startsWith("blob:")?scriptDirectory="":scriptDirectory=scriptDirectory.substr(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1),ENVIRONMENT_IS_WORKER&&(readBinary=r=>{var e=new XMLHttpRequest;return e.open("GET",r,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),readAsync=r=>isFileURI(r)?new Promise((e,t)=>{var n=new XMLHttpRequest;n.open("GET",r,!0),n.responseType="arraybuffer",n.onload=()=>{(n.status==200||n.status==0&&n.response)&&t(n.response),e(n.status)},n.onerror=e,n.send(null)}):fetch(r,{credentials:"same-origin"}).then(e=>e.ok?e.arrayBuffer():Promise.reject(new Error(e.status+" : "+e.url))));var out=Module.print||console.log.bind(console),err=Module.printErr||console.error.bind(console);Object.assign(Module,moduleOverrides),moduleOverrides=null,Module.arguments&&(arguments_=Module.arguments),Module.thisProgram&&(thisProgram=Module.thisProgram),Module.quit&&(quit_=Module.quit);var dynamicLibraries=Module.dynamicLibraries||[],wasmBinary;Module.wasmBinary&&(wasmBinary=Module.wasmBinary);var wasmMemory,ABORT=!1,EXITSTATUS,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64,HEAP_DATA_VIEW;function updateMemoryViews(){var r=wasmMemory.buffer;Module.HEAP_DATA_VIEW=HEAP_DATA_VIEW=new DataView(r),Module.HEAP8=HEAP8=new Int8Array(r),Module.HEAP16=HEAP16=new Int16Array(r),Module.HEAPU8=HEAPU8=new Uint8Array(r),Module.HEAPU16=HEAPU16=new Uint16Array(r),Module.HEAP32=HEAP32=new Int32Array(r),Module.HEAPU32=HEAPU32=new Uint32Array(r),Module.HEAPF32=HEAPF32=new Float32Array(r),Module.HEAPF64=HEAPF64=new Float64Array(r)}if(Module.wasmMemory)wasmMemory=Module.wasmMemory;else{var INITIAL_MEMORY=Module.INITIAL_MEMORY||33554432;wasmMemory=new WebAssembly.Memory({initial:INITIAL_MEMORY/65536,maximum:2147483648/65536})}updateMemoryViews();var __ATPRERUN__=[],__ATINIT__=[],__ATMAIN__=[],__ATPOSTRUN__=[],__RELOC_FUNCS__=[],runtimeInitialized=!1;function preRun(){if(Module.preRun)for(typeof Module.preRun=="function"&&(Module.preRun=[Module.preRun]);Module.preRun.length;)addOnPreRun(Module.preRun.shift());callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=!0,callRuntimeCallbacks(__RELOC_FUNCS__),callRuntimeCallbacks(__ATINIT__)}function preMain(){callRuntimeCallbacks(__ATMAIN__)}function postRun(){if(Module.postRun)for(typeof Module.postRun=="function"&&(Module.postRun=[Module.postRun]);Module.postRun.length;)addOnPostRun(Module.postRun.shift());callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(r){__ATPRERUN__.unshift(r)}function addOnInit(r){__ATINIT__.unshift(r)}function addOnPostRun(r){__ATPOSTRUN__.unshift(r)}var runDependencies=0,runDependencyWatcher=null,dependenciesFulfilled=null;function getUniqueRunDependency(r){return r}function addRunDependency(r){runDependencies++,Module.monitorRunDependencies?.(runDependencies)}function removeRunDependency(r){if(runDependencies--,Module.monitorRunDependencies?.(runDependencies),runDependencies==0&&(runDependencyWatcher!==null&&(clearInterval(runDependencyWatcher),runDependencyWatcher=null),dependenciesFulfilled)){var e=dependenciesFulfilled;dependenciesFulfilled=null,e()}}function abort(r){Module.onAbort?.(r),r="Aborted("+r+")",err(r),ABORT=!0,EXITSTATUS=1,r+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(r);throw e}var dataURIPrefix="data:application/octet-stream;base64,",isDataURI=r=>r.startsWith(dataURIPrefix),isFileURI=r=>r.startsWith("file://");function findWasmBinary(){var r="tree-sitter.wasm";return isDataURI(r)?r:locateFile(r)}var wasmBinaryFile;function getBinarySync(r){if(r==wasmBinaryFile&&wasmBinary)return new Uint8Array(wasmBinary);if(readBinary)return readBinary(r);throw"both async and sync fetching of the wasm failed"}function getBinaryPromise(r){return wasmBinary?Promise.resolve().then(()=>getBinarySync(r)):readAsync(r).then(e=>new Uint8Array(e),()=>getBinarySync(r))}function instantiateArrayBuffer(r,e,t){return getBinaryPromise(r).then(n=>WebAssembly.instantiate(n,e)).then(t,n=>{err(`failed to asynchronously prepare wasm: ${n}`),abort(n)})}function instantiateAsync(r,e,t,n){return!r&&typeof WebAssembly.instantiateStreaming=="function"&&!isDataURI(e)&&!isFileURI(e)&&!ENVIRONMENT_IS_NODE&&typeof fetch=="function"?fetch(e,{credentials:"same-origin"}).then(s=>{var o=WebAssembly.instantiateStreaming(s,t);return o.then(n,function(a){return err(`wasm streaming compile failed: ${a}`),err("falling back to ArrayBuffer instantiation"),instantiateArrayBuffer(e,t,n)})}):instantiateArrayBuffer(e,t,n)}function getWasmImports(){return{env:wasmImports,wasi_snapshot_preview1:wasmImports,"GOT.mem":new Proxy(wasmImports,GOTHandler),"GOT.func":new Proxy(wasmImports,GOTHandler)}}function createWasm(){var r=getWasmImports();function e(n,s){wasmExports=n.exports,wasmExports=relocateExports(wasmExports,1024);var o=getDylinkMetadata(s);return o.neededDynlibs&&(dynamicLibraries=o.neededDynlibs.concat(dynamicLibraries)),mergeLibSymbols(wasmExports,"main"),LDSO.init(),loadDylibs(),addOnInit(wasmExports.__wasm_call_ctors),__RELOC_FUNCS__.push(wasmExports.__wasm_apply_data_relocs),removeRunDependency("wasm-instantiate"),wasmExports}addRunDependency("wasm-instantiate");function t(n){e(n.instance,n.module)}if(Module.instantiateWasm)try{return Module.instantiateWasm(r,e)}catch(n){return err(`Module.instantiateWasm callback failed with error: ${n}`),!1}return wasmBinaryFile||(wasmBinaryFile=findWasmBinary()),instantiateAsync(wasmBinary,wasmBinaryFile,r,t),{}}var ASM_CONSTS={};function ExitStatus(r){this.name="ExitStatus",this.message=`Program terminated with exit(${r})`,this.status=r}var GOT={},currentModuleWeakSymbols=new Set([]),GOTHandler={get(r,e){var t=GOT[e];return t||(t=GOT[e]=new WebAssembly.Global({value:"i32",mutable:!0})),currentModuleWeakSymbols.has(e)||(t.required=!0),t}},LE_HEAP_LOAD_F32=r=>HEAP_DATA_VIEW.getFloat32(r,!0),LE_HEAP_LOAD_F64=r=>HEAP_DATA_VIEW.getFloat64(r,!0),LE_HEAP_LOAD_I16=r=>HEAP_DATA_VIEW.getInt16(r,!0),LE_HEAP_LOAD_I32=r=>HEAP_DATA_VIEW.getInt32(r,!0),LE_HEAP_LOAD_U32=r=>HEAP_DATA_VIEW.getUint32(r,!0),LE_HEAP_STORE_F32=(r,e)=>HEAP_DATA_VIEW.setFloat32(r,e,!0),LE_HEAP_STORE_F64=(r,e)=>HEAP_DATA_VIEW.setFloat64(r,e,!0),LE_HEAP_STORE_I16=(r,e)=>HEAP_DATA_VIEW.setInt16(r,e,!0),LE_HEAP_STORE_I32=(r,e)=>HEAP_DATA_VIEW.setInt32(r,e,!0),LE_HEAP_STORE_U32=(r,e)=>HEAP_DATA_VIEW.setUint32(r,e,!0),callRuntimeCallbacks=r=>{for(;r.length>0;)r.shift()(Module)},UTF8Decoder=typeof TextDecoder<"u"?new TextDecoder:void 0,UTF8ArrayToString=(r,e,t)=>{for(var n=e+t,s=e;r[s]&&!(s>=n);)++s;if(s-e>16&&r.buffer&&UTF8Decoder)return UTF8Decoder.decode(r.subarray(e,s));for(var o="";e<s;){var a=r[e++];if(!(a&128)){o+=String.fromCharCode(a);continue}var l=r[e++]&63;if((a&224)==192){o+=String.fromCharCode((a&31)<<6|l);continue}var c=r[e++]&63;if((a&240)==224?a=(a&15)<<12|l<<6|c:a=(a&7)<<18|l<<12|c<<6|r[e++]&63,a<65536)o+=String.fromCharCode(a);else{var u=a-65536;o+=String.fromCharCode(55296|u>>10,56320|u&1023)}}return o},getDylinkMetadata=r=>{var e=0,t=0;function n(){return r[e++]}function s(){for(var H=0,G=1;;){var j=r[e++];if(H+=(j&127)*G,G*=128,!(j&128))break}return H}function o(){var H=s();return e+=H,UTF8ArrayToString(r,e-H,H)}function a(H,G){if(H)throw new Error(G)}var l="dylink.0";if(r instanceof WebAssembly.Module){var c=WebAssembly.Module.customSections(r,l);c.length===0&&(l="dylink",c=WebAssembly.Module.customSections(r,l)),a(c.length===0,"need dylink section"),r=new Uint8Array(c[0]),t=r.length}else{var u=new Uint32Array(new Uint8Array(r.subarray(0,24)).buffer),h=u[0]==1836278016||u[0]==6386541;a(!h,"need to see wasm magic number"),a(r[8]!==0,"need the dylink section to be first"),e=9;var d=s();t=e+d,l=o()}var f={neededDynlibs:[],tlsExports:new Set,weakImports:new Set};if(l=="dylink"){f.memorySize=s(),f.memoryAlign=s(),f.tableSize=s(),f.tableAlign=s();for(var p=s(),y=0;y<p;++y){var w=o();f.neededDynlibs.push(w)}}else{a(l!=="dylink.0");for(var m=1,_=2,b=3,v=4,S=256,E=3,T=1;e<t;){var A=n(),k=s();if(A===m)f.memorySize=s(),f.memoryAlign=s(),f.tableSize=s(),f.tableAlign=s();else if(A===_)for(var p=s(),y=0;y<p;++y)w=o(),f.neededDynlibs.push(w);else if(A===b)for(var P=s();P--;){var U=o(),F=s();F&S&&f.tlsExports.add(U)}else if(A===v)for(var P=s();P--;){var D=o(),U=o(),F=s();(F&E)==T&&f.weakImports.add(U)}else e+=k}}return f};function getValue(r,e="i8"){switch(e.endsWith("*")&&(e="*"),e){case"i1":return HEAP8[r];case"i8":return HEAP8[r];case"i16":return LE_HEAP_LOAD_I16((r>>1)*2);case"i32":return LE_HEAP_LOAD_I32((r>>2)*4);case"i64":abort("to do getValue(i64) use WASM_BIGINT");case"float":return LE_HEAP_LOAD_F32((r>>2)*4);case"double":return LE_HEAP_LOAD_F64((r>>3)*8);case"*":return LE_HEAP_LOAD_U32((r>>2)*4);default:abort(`invalid type for getValue: ${e}`)}}var newDSO=(r,e,t)=>{var n={refcount:1/0,name:r,exports:t,global:!0};return LDSO.loadedLibsByName[r]=n,e!=null&&(LDSO.loadedLibsByHandle[e]=n),n},LDSO={loadedLibsByName:{},loadedLibsByHandle:{},init(){newDSO("__main__",0,wasmImports)}},___heap_base=78112,zeroMemory=(r,e)=>(HEAPU8.fill(0,r,r+e),r),alignMemory=(r,e)=>Math.ceil(r/e)*e,getMemory=r=>{if(runtimeInitialized)return zeroMemory(_malloc(r),r);var e=___heap_base,t=e+alignMemory(r,16);return ___heap_base=t,GOT.__heap_base.value=t,e},isInternalSym=r=>["__cpp_exception","__c_longjmp","__wasm_apply_data_relocs","__dso_handle","__tls_size","__tls_align","__set_stack_limits","_emscripten_tls_init","__wasm_init_tls","__wasm_call_ctors","__start_em_asm","__stop_em_asm","__start_em_js","__stop_em_js"].includes(r)||r.startsWith("__em_js__"),uleb128Encode=(r,e)=>{r<128?e.push(r):e.push(r%128|128,r>>7)},sigToWasmTypes=r=>{for(var e={i:"i32",j:"i64",f:"f32",d:"f64",e:"externref",p:"i32"},t={parameters:[],results:r[0]=="v"?[]:[e[r[0]]]},n=1;n<r.length;++n)t.parameters.push(e[r[n]]);return t},generateFuncType=(r,e)=>{var t=r.slice(0,1),n=r.slice(1),s={i:127,p:127,j:126,f:125,d:124,e:111};e.push(96),uleb128Encode(n.length,e);for(var o=0;o<n.length;++o)e.push(s[n[o]]);t=="v"?e.push(0):e.push(1,s[t])},convertJsFunctionToWasm=(r,e)=>{if(typeof WebAssembly.Function=="function")return new WebAssembly.Function(sigToWasmTypes(e),r);var t=[1];generateFuncType(e,t);var n=[0,97,115,109,1,0,0,0,1];uleb128Encode(t.length,n),n.push(...t),n.push(2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0);var s=new WebAssembly.Module(new Uint8Array(n)),o=new WebAssembly.Instance(s,{e:{f:r}}),a=o.exports.f;return a},wasmTableMirror=[],wasmTable=new WebAssembly.Table({initial:28,element:"anyfunc"}),getWasmTableEntry=r=>{var e=wasmTableMirror[r];return e||(r>=wasmTableMirror.length&&(wasmTableMirror.length=r+1),wasmTableMirror[r]=e=wasmTable.get(r)),e},updateTableMap=(r,e)=>{if(functionsInTableMap)for(var t=r;t<r+e;t++){var n=getWasmTableEntry(t);n&&functionsInTableMap.set(n,t)}},functionsInTableMap,getFunctionAddress=r=>(functionsInTableMap||(functionsInTableMap=new WeakMap,updateTableMap(0,wasmTable.length)),functionsInTableMap.get(r)||0),freeTableIndexes=[],getEmptyTableSlot=()=>{if(freeTableIndexes.length)return freeTableIndexes.pop();try{wasmTable.grow(1)}catch(r){throw r instanceof RangeError?"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.":r}return wasmTable.length-1},setWasmTableEntry=(r,e)=>{wasmTable.set(r,e),wasmTableMirror[r]=wasmTable.get(r)},addFunction=(r,e)=>{var t=getFunctionAddress(r);if(t)return t;var n=getEmptyTableSlot();try{setWasmTableEntry(n,r)}catch(o){if(!(o instanceof TypeError))throw o;var s=convertJsFunctionToWasm(r,e);setWasmTableEntry(n,s)}return functionsInTableMap.set(r,n),n},updateGOT=(r,e)=>{for(var t in r)if(!isInternalSym(t)){var n=r[t];t.startsWith("orig$")&&(t=t.split("$")[1],e=!0),GOT[t]||=new WebAssembly.Global({value:"i32",mutable:!0}),(e||GOT[t].value==0)&&(typeof n=="function"?GOT[t].value=addFunction(n):typeof n=="number"?GOT[t].value=n:err(`unhandled export type for '${t}': ${typeof n}`))}},relocateExports=(r,e,t)=>{var n={};for(var s in r){var o=r[s];typeof o=="object"&&(o=o.value),typeof o=="number"&&(o+=e),n[s]=o}return updateGOT(n,t),n},isSymbolDefined=r=>{var e=wasmImports[r];return!(!e||e.stub)},dynCallLegacy=(r,e,t)=>{r=r.replace(/p/g,"i");var n=Module["dynCall_"+r];return n(e,...t)},dynCall=(r,e,t=[])=>{if(r.includes("j"))return dynCallLegacy(r,e,t);var n=getWasmTableEntry(e)(...t);return n},stackSave=()=>_emscripten_stack_get_current(),stackRestore=r=>__emscripten_stack_restore(r),createInvokeFunction=r=>(e,...t)=>{var n=stackSave();try{return dynCall(r,e,t)}catch(s){if(stackRestore(n),s!==s+0)throw s;_setThrew(1,0)}},resolveGlobalSymbol=(r,e=!1)=>{var t;return e&&"orig$"+r in wasmImports&&(r="orig$"+r),isSymbolDefined(r)?t=wasmImports[r]:r.startsWith("invoke_")&&(t=wasmImports[r]=createInvokeFunction(r.split("_")[1])),{sym:t,name:r}},UTF8ToString=(r,e)=>r?UTF8ArrayToString(HEAPU8,r,e):"",loadWebAssemblyModule=(binary,flags,libName,localScope,handle)=>{var metadata=getDylinkMetadata(binary);currentModuleWeakSymbols=metadata.weakImports;function loadModule(){var firstLoad=!handle||!HEAP8[handle+8];if(firstLoad){var memAlign=Math.pow(2,metadata.memoryAlign),memoryBase=metadata.memorySize?alignMemory(getMemory(metadata.memorySize+memAlign),memAlign):0,tableBase=metadata.tableSize?wasmTable.length:0;handle&&(HEAP8[handle+8]=1,LE_HEAP_STORE_U32((handle+12>>2)*4,memoryBase),LE_HEAP_STORE_I32((handle+16>>2)*4,metadata.memorySize),LE_HEAP_STORE_U32((handle+20>>2)*4,tableBase),LE_HEAP_STORE_I32((handle+24>>2)*4,metadata.tableSize))}else memoryBase=LE_HEAP_LOAD_U32((handle+12>>2)*4),tableBase=LE_HEAP_LOAD_U32((handle+20>>2)*4);var tableGrowthNeeded=tableBase+metadata.tableSize-wasmTable.length;tableGrowthNeeded>0&&wasmTable.grow(tableGrowthNeeded);var moduleExports;function resolveSymbol(r){var e=resolveGlobalSymbol(r).sym;return!e&&localScope&&(e=localScope[r]),e||(e=moduleExports[r]),e}var proxyHandler={get(r,e){switch(e){case"__memory_base":return memoryBase;case"__table_base":return tableBase}if(e in wasmImports&&!wasmImports[e].stub)return wasmImports[e];if(!(e in r)){var t;r[e]=(...n)=>(t||=resolveSymbol(e),t(...n))}return r[e]}},proxy=new Proxy({},proxyHandler),info={"GOT.mem":new Proxy({},GOTHandler),"GOT.func":new Proxy({},GOTHandler),env:proxy,wasi_snapshot_preview1:proxy};function postInstantiation(module,instance){updateTableMap(tableBase,metadata.tableSize),moduleExports=relocateExports(instance.exports,memoryBase),flags.allowUndefined||reportUndefinedSymbols();function addEmAsm(addr,body){for(var args=[],arity=0;arity<16&&body.indexOf("$"+arity)!=-1;arity++)args.push("$"+arity);args=args.join(",");var func=`(${args}) => { ${body} };`;ASM_CONSTS[start]=eval(func)}if("__start_em_asm"in moduleExports)for(var start=moduleExports.__start_em_asm,stop=moduleExports.__stop_em_asm;start<stop;){var jsString=UTF8ToString(start);addEmAsm(start,jsString),start=HEAPU8.indexOf(0,start)+1}function addEmJs(name,cSig,body){var jsArgs=[];if(cSig=cSig.slice(1,-1),cSig!="void"){cSig=cSig.split(",");for(var i in cSig){var jsArg=cSig[i].split(" ").pop();jsArgs.push(jsArg.replace("*",""))}}var func=`(${jsArgs}) => ${body};`;moduleExports[name]=eval(func)}for(var name in moduleExports)if(name.startsWith("__em_js__")){var start=moduleExports[name],jsString=UTF8ToString(start),parts=jsString.split("<::>");addEmJs(name.replace("__em_js__",""),parts[0],parts[1]),delete moduleExports[name]}var applyRelocs=moduleExports.__wasm_apply_data_relocs;applyRelocs&&(runtimeInitialized?applyRelocs():__RELOC_FUNCS__.push(applyRelocs));var init=moduleExports.__wasm_call_ctors;return init&&(runtimeInitialized?init():__ATINIT__.push(init)),moduleExports}if(flags.loadAsync){if(binary instanceof WebAssembly.Module){var instance=new WebAssembly.Instance(binary,info);return Promise.resolve(postInstantiation(binary,instance))}return WebAssembly.instantiate(binary,info).then(r=>postInstantiation(r.module,r.instance))}var module=binary instanceof WebAssembly.Module?binary:new WebAssembly.Module(binary),instance=new WebAssembly.Instance(module,info);return postInstantiation(module,instance)}return flags.loadAsync?metadata.neededDynlibs.reduce((r,e)=>r.then(()=>loadDynamicLibrary(e,flags,localScope)),Promise.resolve()).then(loadModule):(metadata.neededDynlibs.forEach(r=>loadDynamicLibrary(r,flags,localScope)),loadModule())},mergeLibSymbols=(r,e)=>{for(var[t,n]of Object.entries(r)){let s=a=>{isSymbolDefined(a)||(wasmImports[a]=n)};s(t);let o="__main_argc_argv";t=="main"&&s(o),t==o&&s("main"),t.startsWith("dynCall_")&&!Module.hasOwnProperty(t)&&(Module[t]=n)}},asyncLoad=(r,e,t,n)=>{var s=n?"":`al ${r}`;readAsync(r).then(o=>{e(new Uint8Array(o)),s&&removeRunDependency(s)},o=>{if(t)t();else throw`Loading data file "${r}" failed.`}),s&&addRunDependency(s)};function loadDynamicLibrary(r,e={global:!0,nodelete:!0},t,n){var s=LDSO.loadedLibsByName[r];if(s)return e.global?s.global||(s.global=!0,mergeLibSymbols(s.exports,r)):t&&Object.assign(t,s.exports),e.nodelete&&s.refcount!==1/0&&(s.refcount=1/0),s.refcount++,n&&(LDSO.loadedLibsByHandle[n]=s),e.loadAsync?Promise.resolve(!0):!0;s=newDSO(r,n,"loading"),s.refcount=e.nodelete?1/0:1,s.global=e.global;function o(){if(n){var c=LE_HEAP_LOAD_U32((n+28>>2)*4),u=LE_HEAP_LOAD_U32((n+32>>2)*4);if(c&&u){var h=HEAP8.slice(c,c+u);return e.loadAsync?Promise.resolve(h):h}}var d=locateFile(r);if(e.loadAsync)return new Promise(function(f,p){asyncLoad(d,f,p)});if(!readBinary)throw new Error(`${d}: file not found, and synchronous loading of external files is not available`);return readBinary(d)}function a(){return e.loadAsync?o().then(c=>loadWebAssemblyModule(c,e,r,t,n)):loadWebAssemblyModule(o(),e,r,t,n)}function l(c){s.global?mergeLibSymbols(c,r):t&&Object.assign(t,c),s.exports=c}return e.loadAsync?a().then(c=>(l(c),!0)):(l(a()),!0)}var reportUndefinedSymbols=()=>{for(var[r,e]of Object.entries(GOT))if(e.value==0){var t=resolveGlobalSymbol(r,!0).sym;if(!t&&!e.required)continue;if(typeof t=="function")e.value=addFunction(t,t.sig);else if(typeof t=="number")e.value=t;else throw new Error(`bad export type for '${r}': ${typeof t}`)}},loadDylibs=()=>{if(!dynamicLibraries.length){reportUndefinedSymbols();return}addRunDependency("loadDylibs"),dynamicLibraries.reduce((r,e)=>r.then(()=>loadDynamicLibrary(e,{loadAsync:!0,global:!0,nodelete:!0,allowUndefined:!0})),Promise.resolve()).then(()=>{reportUndefinedSymbols(),removeRunDependency("loadDylibs")})},noExitRuntime=Module.noExitRuntime||!0;function setValue(r,e,t="i8"){switch(t.endsWith("*")&&(t="*"),t){case"i1":HEAP8[r]=e;break;case"i8":HEAP8[r]=e;break;case"i16":LE_HEAP_STORE_I16((r>>1)*2,e);break;case"i32":LE_HEAP_STORE_I32((r>>2)*4,e);break;case"i64":abort("to do setValue(i64) use WASM_BIGINT");case"float":LE_HEAP_STORE_F32((r>>2)*4,e);break;case"double":LE_HEAP_STORE_F64((r>>3)*8,e);break;case"*":LE_HEAP_STORE_U32((r>>2)*4,e);break;default:abort(`invalid type for setValue: ${t}`)}}var ___memory_base=new WebAssembly.Global({value:"i32",mutable:!1},1024),___stack_pointer=new WebAssembly.Global({value:"i32",mutable:!0},78112),___table_base=new WebAssembly.Global({value:"i32",mutable:!1},1),__abort_js=()=>{abort("")};__abort_js.sig="v";var nowIsMonotonic=1,__emscripten_get_now_is_monotonic=()=>nowIsMonotonic;__emscripten_get_now_is_monotonic.sig="i";var __emscripten_memcpy_js=(r,e,t)=>HEAPU8.copyWithin(r,e,e+t);__emscripten_memcpy_js.sig="vppp";var _emscripten_date_now=()=>Date.now();_emscripten_date_now.sig="d";var _emscripten_get_now;_emscripten_get_now=()=>performance.now(),_emscripten_get_now.sig="d";var getHeapMax=()=>2147483648,growMemory=r=>{var e=wasmMemory.buffer,t=(r-e.byteLength+65535)/65536;try{return wasmMemory.grow(t),updateMemoryViews(),1}catch{}},_emscripten_resize_heap=r=>{var e=HEAPU8.length;r>>>=0;var t=getHeapMax();if(r>t)return!1;for(var n=(c,u)=>c+(u-c%u)%u,s=1;s<=4;s*=2){var o=e*(1+.2/s);o=Math.min(o,r+100663296);var a=Math.min(t,n(Math.max(r,o),65536)),l=growMemory(a);if(l)return!0}return!1};_emscripten_resize_heap.sig="ip";var _fd_close=r=>52;_fd_close.sig="ii";var convertI32PairToI53Checked=(r,e)=>e+2097152>>>0<4194305-!!r?(r>>>0)+e*4294967296:NaN;function _fd_seek(r,e,t,n,s){var o=convertI32PairToI53Checked(e,t);return 70}_fd_seek.sig="iiiiip";var printCharBuffers=[null,[],[]],printChar=(r,e)=>{var t=printCharBuffers[r];e===0||e===10?((r===1?out:err)(UTF8ArrayToString(t,0)),t.length=0):t.push(e)},_fd_write=(r,e,t,n)=>{for(var s=0,o=0;o<t;o++){var a=LE_HEAP_LOAD_U32((e>>2)*4),l=LE_HEAP_LOAD_U32((e+4>>2)*4);e+=8;for(var c=0;c<l;c++)printChar(r,HEAPU8[a+c]);s+=l}return LE_HEAP_STORE_U32((n>>2)*4,s),0};_fd_write.sig="iippp";function _tree_sitter_log_callback(r,e){if(currentLogCallback){let t=UTF8ToString(e);currentLogCallback(t,r!==0)}}function _tree_sitter_parse_callback(r,e,t,n,s){let a=currentParseCallback(e,{row:t,column:n});typeof a=="string"?(setValue(s,a.length,"i32"),stringToUTF16(a,r,10240)):setValue(s,0,"i32")}var runtimeKeepaliveCounter=0,keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0,_proc_exit=r=>{EXITSTATUS=r,keepRuntimeAlive()||(Module.onExit?.(r),ABORT=!0),quit_(r,new ExitStatus(r))};_proc_exit.sig="vi";var exitJS=(r,e)=>{EXITSTATUS=r,_proc_exit(r)},handleException=r=>{if(r instanceof ExitStatus||r=="unwind")return EXITSTATUS;quit_(1,r)},lengthBytesUTF8=r=>{for(var e=0,t=0;t<r.length;++t){var n=r.charCodeAt(t);n<=127?e++:n<=2047?e+=2:n>=55296&&n<=57343?(e+=4,++t):e+=3}return e},stringToUTF8Array=(r,e,t,n)=>{if(!(n>0))return 0;for(var s=t,o=t+n-1,a=0;a<r.length;++a){var l=r.charCodeAt(a);if(l>=55296&&l<=57343){var c=r.charCodeAt(++a);l=65536+((l&1023)<<10)|c&1023}if(l<=127){if(t>=o)break;e[t++]=l}else if(l<=2047){if(t+1>=o)break;e[t++]=192|l>>6,e[t++]=128|l&63}else if(l<=65535){if(t+2>=o)break;e[t++]=224|l>>12,e[t++]=128|l>>6&63,e[t++]=128|l&63}else{if(t+3>=o)break;e[t++]=240|l>>18,e[t++]=128|l>>12&63,e[t++]=128|l>>6&63,e[t++]=128|l&63}}return e[t]=0,t-s},stringToUTF8=(r,e,t)=>stringToUTF8Array(r,HEAPU8,e,t),stackAlloc=r=>__emscripten_stack_alloc(r),stringToUTF8OnStack=r=>{var e=lengthBytesUTF8(r)+1,t=stackAlloc(e);return stringToUTF8(r,t,e),t},stringToUTF16=(r,e,t)=>{if(t??=2147483647,t<2)return 0;t-=2;for(var n=e,s=t<r.length*2?t/2:r.length,o=0;o<s;++o){var a=r.charCodeAt(o);LE_HEAP_STORE_I16((e>>1)*2,a),e+=2}return LE_HEAP_STORE_I16((e>>1)*2,0),e-n},AsciiToString=r=>{for(var e="";;){var t=HEAPU8[r++];if(!t)return e;e+=String.fromCharCode(t)}},wasmImports={__heap_base:___heap_base,__indirect_function_table:wasmTable,__memory_base:___memory_base,__stack_pointer:___stack_pointer,__table_base:___table_base,_abort_js:__abort_js,_emscripten_get_now_is_monotonic:__emscripten_get_now_is_monotonic,_emscripten_memcpy_js:__emscripten_memcpy_js,emscripten_get_now:_emscripten_get_now,emscripten_resize_heap:_emscripten_resize_heap,fd_close:_fd_close,fd_seek:_fd_seek,fd_write:_fd_write,memory:wasmMemory,tree_sitter_log_callback:_tree_sitter_log_callback,tree_sitter_parse_callback:_tree_sitter_parse_callback},wasmExports=createWasm(),___wasm_call_ctors=()=>(___wasm_call_ctors=wasmExports.__wasm_call_ctors)(),___wasm_apply_data_relocs=()=>(___wasm_apply_data_relocs=wasmExports.__wasm_apply_data_relocs)(),_malloc=Module._malloc=r=>(_malloc=Module._malloc=wasmExports.malloc)(r),_calloc=Module._calloc=(r,e)=>(_calloc=Module._calloc=wasmExports.calloc)(r,e),_realloc=Module._realloc=(r,e)=>(_realloc=Module._realloc=wasmExports.realloc)(r,e),_free=Module._free=r=>(_free=Module._free=wasmExports.free)(r),_ts_language_symbol_count=Module._ts_language_symbol_count=r=>(_ts_language_symbol_count=Module._ts_language_symbol_count=wasmExports.ts_language_symbol_count)(r),_ts_language_state_count=Module._ts_language_state_count=r=>(_ts_language_state_count=Module._ts_language_state_count=wasmExports.ts_language_state_count)(r),_ts_language_version=Module._ts_language_version=r=>(_ts_language_version=Module._ts_language_version=wasmExports.ts_language_version)(r),_ts_language_field_count=Module._ts_language_field_count=r=>(_ts_language_field_count=Module._ts_language_field_count=wasmExports.ts_language_field_count)(r),_ts_language_next_state=Module._ts_language_next_state=(r,e,t)=>(_ts_language_next_state=Module._ts_language_next_state=wasmExports.ts_language_next_state)(r,e,t),_ts_language_symbol_name=Module._ts_language_symbol_name=(r,e)=>(_ts_language_symbol_name=Module._ts_language_symbol_name=wasmExports.ts_language_symbol_name)(r,e),_ts_language_symbol_for_name=Module._ts_language_symbol_for_name=(r,e,t,n)=>(_ts_language_symbol_for_name=Module._ts_language_symbol_for_name=wasmExports.ts_language_symbol_for_name)(r,e,t,n),_strncmp=Module._strncmp=(r,e,t)=>(_strncmp=Module._strncmp=wasmExports.strncmp)(r,e,t),_ts_language_symbol_type=Module._ts_language_symbol_type=(r,e)=>(_ts_language_symbol_type=Module._ts_language_symbol_type=wasmExports.ts_language_symbol_type)(r,e),_ts_language_field_name_for_id=Module._ts_language_field_name_for_id=(r,e)=>(_ts_language_field_name_for_id=Module._ts_language_field_name_for_id=wasmExports.ts_language_field_name_for_id)(r,e),_ts_lookahead_iterator_new=Module._ts_lookahead_iterator_new=(r,e)=>(_ts_lookahead_iterator_new=Module._ts_lookahead_iterator_new=wasmExports.ts_lookahead_iterator_new)(r,e),_ts_lookahead_iterator_delete=Module._ts_lookahead_iterator_delete=r=>(_ts_lookahead_iterator_delete=Module._ts_lookahead_iterator_delete=wasmExports.ts_lookahead_iterator_delete)(r),_ts_lookahead_iterator_reset_state=Module._ts_lookahead_iterator_reset_state=(r,e)=>(_ts_lookahead_iterator_reset_state=Module._ts_lookahead_iterator_reset_state=wasmExports.ts_lookahead_iterator_reset_state)(r,e),_ts_lookahead_iterator_reset=Module._ts_lookahead_iterator_reset=(r,e,t)=>(_ts_lookahead_iterator_reset=Module._ts_lookahead_iterator_reset=wasmExports.ts_lookahead_iterator_reset)(r,e,t),_ts_lookahead_iterator_next=Module._ts_lookahead_iterator_next=r=>(_ts_lookahead_iterator_next=Module._ts_lookahead_iterator_next=wasmExports.ts_lookahead_iterator_next)(r),_ts_lookahead_iterator_current_symbol=Module._ts_lookahead_iterator_current_symbol=r=>(_ts_lookahead_iterator_current_symbol=Module._ts_lookahead_iterator_current_symbol=wasmExports.ts_lookahead_iterator_current_symbol)(r),_memset=Module._memset=(r,e,t)=>(_memset=Module._memset=wasmExports.memset)(r,e,t),_memcpy=Module._memcpy=(r,e,t)=>(_memcpy=Module._memcpy=wasmExports.memcpy)(r,e,t),_ts_parser_delete=Module._ts_parser_delete=r=>(_ts_parser_delete=Module._ts_parser_delete=wasmExports.ts_parser_delete)(r),_ts_parser_reset=Module._ts_parser_reset=r=>(_ts_parser_reset=Module._ts_parser_reset=wasmExports.ts_parser_reset)(r),_ts_parser_set_language=Module._ts_parser_set_language=(r,e)=>(_ts_parser_set_language=Module._ts_parser_set_language=wasmExports.ts_parser_set_language)(r,e),_ts_parser_timeout_micros=Module._ts_parser_timeout_micros=r=>(_ts_parser_timeout_micros=Module._ts_parser_timeout_micros=wasmExports.ts_parser_timeout_micros)(r),_ts_parser_set_timeout_micros=Module._ts_parser_set_timeout_micros=(r,e,t)=>(_ts_parser_set_timeout_micros=Module._ts_parser_set_timeout_micros=wasmExports.ts_parser_set_timeout_micros)(r,e,t),_ts_parser_set_included_ranges=Module._ts_parser_set_included_ranges=(r,e,t)=>(_ts_parser_set_included_ranges=Module._ts_parser_set_included_ranges=wasmExports.ts_parser_set_included_ranges)(r,e,t),_memmove=Module._memmove=(r,e,t)=>(_memmove=Module._memmove=wasmExports.memmove)(r,e,t),_memcmp=Module._memcmp=(r,e,t)=>(_memcmp=Module._memcmp=wasmExports.memcmp)(r,e,t),_ts_query_new=Module._ts_query_new=(r,e,t,n,s)=>(_ts_query_new=Module._ts_query_new=wasmExports.ts_query_new)(r,e,t,n,s),_ts_query_delete=Module._ts_query_delete=r=>(_ts_query_delete=Module._ts_query_delete=wasmExports.ts_query_delete)(r),_iswspace=Module._iswspace=r=>(_iswspace=Module._iswspace=wasmExports.iswspace)(r),_iswalnum=Module._iswalnum=r=>(_iswalnum=Module._iswalnum=wasmExports.iswalnum)(r),_ts_query_pattern_count=Module._ts_query_pattern_count=r=>(_ts_query_pattern_count=Module._ts_query_pattern_count=wasmExports.ts_query_pattern_count)(r),_ts_query_capture_count=Module._ts_query_capture_count=r=>(_ts_query_capture_count=Module._ts_query_capture_count=wasmExports.ts_query_capture_count)(r),_ts_query_string_count=Module._ts_query_string_count=r=>(_ts_query_string_count=Module._ts_query_string_count=wasmExports.ts_query_string_count)(r),_ts_query_capture_name_for_id=Module._ts_query_capture_name_for_id=(r,e,t)=>(_ts_query_capture_name_for_id=Module._ts_query_capture_name_for_id=wasmExports.ts_query_capture_name_for_id)(r,e,t),_ts_query_string_value_for_id=Module._ts_query_string_value_for_id=(r,e,t)=>(_ts_query_string_value_for_id=Module._ts_query_string_value_for_id=wasmExports.ts_query_string_value_for_id)(r,e,t),_ts_query_predicates_for_pattern=Module._ts_query_predicates_for_pattern=(r,e,t)=>(_ts_query_predicates_for_pattern=Module._ts_query_predicates_for_pattern=wasmExports.ts_query_predicates_for_pattern)(r,e,t),_ts_query_disable_capture=Module._ts_query_disable_capture=(r,e,t)=>(_ts_query_disable_capture=Module._ts_query_disable_capture=wasmExports.ts_query_disable_capture)(r,e,t),_ts_tree_copy=Module._ts_tree_copy=r=>(_ts_tree_copy=Module._ts_tree_copy=wasmExports.ts_tree_copy)(r),_ts_tree_delete=Module._ts_tree_delete=r=>(_ts_tree_delete=Module._ts_tree_delete=wasmExports.ts_tree_delete)(r),_ts_init=Module._ts_init=()=>(_ts_init=Module._ts_init=wasmExports.ts_init)(),_ts_parser_new_wasm=Module._ts_parser_new_wasm=()=>(_ts_parser_new_wasm=Module._ts_parser_new_wasm=wasmExports.ts_parser_new_wasm)(),_ts_parser_enable_logger_wasm=Module._ts_parser_enable_logger_wasm=(r,e)=>(_ts_parser_enable_logger_wasm=Module._ts_parser_enable_logger_wasm=wasmExports.ts_parser_enable_logger_wasm)(r,e),_ts_parser_parse_wasm=Module._ts_parser_parse_wasm=(r,e,t,n,s)=>(_ts_parser_parse_wasm=Module._ts_parser_parse_wasm=wasmExports.ts_parser_parse_wasm)(r,e,t,n,s),_ts_parser_included_ranges_wasm=Module._ts_parser_included_ranges_wasm=r=>(_ts_parser_included_ranges_wasm=Module._ts_parser_included_ranges_wasm=wasmExports.ts_parser_included_ranges_wasm)(r),_ts_language_type_is_named_wasm=Module._ts_language_type_is_named_wasm=(r,e)=>(_ts_language_type_is_named_wasm=Module._ts_language_type_is_named_wasm=wasmExports.ts_language_type_is_named_wasm)(r,e),_ts_language_type_is_visible_wasm=Module._ts_language_type_is_visible_wasm=(r,e)=>(_ts_language_type_is_visible_wasm=Module._ts_language_type_is_visible_wasm=wasmExports.ts_language_type_is_visible_wasm)(r,e),_ts_tree_root_node_wasm=Module._ts_tree_root_node_wasm=r=>(_ts_tree_root_node_wasm=Module._ts_tree_root_node_wasm=wasmExports.ts_tree_root_node_wasm)(r),_ts_tree_root_node_with_offset_wasm=Module._ts_tree_root_node_with_offset_wasm=r=>(_ts_tree_root_node_with_offset_wasm=Module._ts_tree_root_node_with_offset_wasm=wasmExports.ts_tree_root_node_with_offset_wasm)(r),_ts_tree_edit_wasm=Module._ts_tree_edit_wasm=r=>(_ts_tree_edit_wasm=Module._ts_tree_edit_wasm=wasmExports.ts_tree_edit_wasm)(r),_ts_tree_included_ranges_wasm=Module._ts_tree_included_ranges_wasm=r=>(_ts_tree_included_ranges_wasm=Module._ts_tree_included_ranges_wasm=wasmExports.ts_tree_included_ranges_wasm)(r),_ts_tree_get_changed_ranges_wasm=Module._ts_tree_get_changed_ranges_wasm=(r,e)=>(_ts_tree_get_changed_ranges_wasm=Module._ts_tree_get_changed_ranges_wasm=wasmExports.ts_tree_get_changed_ranges_wasm)(r,e),_ts_tree_cursor_new_wasm=Module._ts_tree_cursor_new_wasm=r=>(_ts_tree_cursor_new_wasm=Module._ts_tree_cursor_new_wasm=wasmExports.ts_tree_cursor_new_wasm)(r),_ts_tree_cursor_delete_wasm=Module._ts_tree_cursor_delete_wasm=r=>(_ts_tree_cursor_delete_wasm=Module._ts_tree_cursor_delete_wasm=wasmExports.ts_tree_cursor_delete_wasm)(r),_ts_tree_cursor_reset_wasm=Module._ts_tree_cursor_reset_wasm=r=>(_ts_tree_cursor_reset_wasm=Module._ts_tree_cursor_reset_wasm=wasmExports.ts_tree_cursor_reset_wasm)(r),_ts_tree_cursor_reset_to_wasm=Module._ts_tree_cursor_reset_to_wasm=(r,e)=>(_ts_tree_cursor_reset_to_wasm=Module._ts_tree_cursor_reset_to_wasm=wasmExports.ts_tree_cursor_reset_to_wasm)(r,e),_ts_tree_cursor_goto_first_child_wasm=Module._ts_tree_cursor_goto_first_child_wasm=r=>(_ts_tree_cursor_goto_first_child_wasm=Module._ts_tree_cursor_goto_first_child_wasm=wasmExports.ts_tree_cursor_goto_first_child_wasm)(r),_ts_tree_cursor_goto_last_child_wasm=Module._ts_tree_cursor_goto_last_child_wasm=r=>(_ts_tree_cursor_goto_last_child_wasm=Module._ts_tree_cursor_goto_last_child_wasm=wasmExports.ts_tree_cursor_goto_last_child_wasm)(r),_ts_tree_cursor_goto_first_child_for_index_wasm=Module._ts_tree_cursor_goto_first_child_for_index_wasm=r=>(_ts_tree_cursor_goto_first_child_for_index_wasm=Module._ts_tree_cursor_goto_first_child_for_index_wasm=wasmExports.ts_tree_cursor_goto_first_child_for_index_wasm)(r),_ts_tree_cursor_goto_first_child_for_position_wasm=Module._ts_tree_cursor_goto_first_child_for_position_wasm=r=>(_ts_tree_cursor_goto_first_child_for_position_wasm=Module._ts_tree_cursor_goto_first_child_for_position_wasm=wasmExports.ts_tree_cursor_goto_first_child_for_position_wasm)(r),_ts_tree_cursor_goto_next_sibling_wasm=Module._ts_tree_cursor_goto_next_sibling_wasm=r=>(_ts_tree_cursor_goto_next_sibling_wasm=Module._ts_tree_cursor_goto_next_sibling_wasm=wasmExports.ts_tree_cursor_goto_next_sibling_wasm)(r),_ts_tree_cursor_goto_previous_sibling_wasm=Module._ts_tree_cursor_goto_previous_sibling_wasm=r=>(_ts_tree_cursor_goto_previous_sibling_wasm=Module._ts_tree_cursor_goto_previous_sibling_wasm=wasmExports.ts_tree_cursor_goto_previous_sibling_wasm)(r),_ts_tree_cursor_goto_descendant_wasm=Module._ts_tree_cursor_goto_descendant_wasm=(r,e)=>(_ts_tree_cursor_goto_descendant_wasm=Module._ts_tree_cursor_goto_descendant_wasm=wasmExports.ts_tree_cursor_goto_descendant_wasm)(r,e),_ts_tree_cursor_goto_parent_wasm=Module._ts_tree_cursor_goto_parent_wasm=r=>(_ts_tree_cursor_goto_parent_wasm=Module._ts_tree_cursor_goto_parent_wasm=wasmExports.ts_tree_cursor_goto_parent_wasm)(r),_ts_tree_cursor_current_node_type_id_wasm=Module._ts_tree_cursor_current_node_type_id_wasm=r=>(_ts_tree_cursor_current_node_type_id_wasm=Module._ts_tree_cursor_current_node_type_id_wasm=wasmExports.ts_tree_cursor_current_node_type_id_wasm)(r),_ts_tree_cursor_current_node_state_id_wasm=Module._ts_tree_cursor_current_node_state_id_wasm=r=>(_ts_tree_cursor_current_node_state_id_wasm=Module._ts_tree_cursor_current_node_state_id_wasm=wasmExports.ts_tree_cursor_current_node_state_id_wasm)(r),_ts_tree_cursor_current_node_is_named_wasm=Module._ts_tree_cursor_current_node_is_named_wasm=r=>(_ts_tree_cursor_current_node_is_named_wasm=Module._ts_tree_cursor_current_node_is_named_wasm=wasmExports.ts_tree_cursor_current_node_is_named_wasm)(r),_ts_tree_cursor_current_node_is_missing_wasm=Module._ts_tree_cursor_current_node_is_missing_wasm=r=>(_ts_tree_cursor_current_node_is_missing_wasm=Module._ts_tree_cursor_current_node_is_missing_wasm=wasmExports.ts_tree_cursor_current_node_is_missing_wasm)(r),_ts_tree_cursor_current_node_id_wasm=Module._ts_tree_cursor_current_node_id_wasm=r=>(_ts_tree_cursor_current_node_id_wasm=Module._ts_tree_cursor_current_node_id_wasm=wasmExports.ts_tree_cursor_current_node_id_wasm)(r),_ts_tree_cursor_start_position_wasm=Module._ts_tree_cursor_start_position_wasm=r=>(_ts_tree_cursor_start_position_wasm=Module._ts_tree_cursor_start_position_wasm=wasmExports.ts_tree_cursor_start_position_wasm)(r),_ts_tree_cursor_end_position_wasm=Module._ts_tree_cursor_end_position_wasm=r=>(_ts_tree_cursor_end_position_wasm=Module._ts_tree_cursor_end_position_wasm=wasmExports.ts_tree_cursor_end_position_wasm)(r),_ts_tree_cursor_start_index_wasm=Module._ts_tree_cursor_start_index_wasm=r=>(_ts_tree_cursor_start_index_wasm=Module._ts_tree_cursor_start_index_wasm=wasmExports.ts_tree_cursor_start_index_wasm)(r),_ts_tree_cursor_end_index_wasm=Module._ts_tree_cursor_end_index_wasm=r=>(_ts_tree_cursor_end_index_wasm=Module._ts_tree_cursor_end_index_wasm=wasmExports.ts_tree_cursor_end_index_wasm)(r),_ts_tree_cursor_current_field_id_wasm=Module._ts_tree_cursor_current_field_id_wasm=r=>(_ts_tree_cursor_current_field_id_wasm=Module._ts_tree_cursor_current_field_id_wasm=wasmExports.ts_tree_cursor_current_field_id_wasm)(r),_ts_tree_cursor_current_depth_wasm=Module._ts_tree_cursor_current_depth_wasm=r=>(_ts_tree_cursor_current_depth_wasm=Module._ts_tree_cursor_current_depth_wasm=wasmExports.ts_tree_cursor_current_depth_wasm)(r),_ts_tree_cursor_current_descendant_index_wasm=Module._ts_tree_cursor_current_descendant_index_wasm=r=>(_ts_tree_cursor_current_descendant_index_wasm=Module._ts_tree_cursor_current_descendant_index_wasm=wasmExports.ts_tree_cursor_current_descendant_index_wasm)(r),_ts_tree_cursor_current_node_wasm=Module._ts_tree_cursor_current_node_wasm=r=>(_ts_tree_cursor_current_node_wasm=Module._ts_tree_cursor_current_node_wasm=wasmExports.ts_tree_cursor_current_node_wasm)(r),_ts_node_symbol_wasm=Module._ts_node_symbol_wasm=r=>(_ts_node_symbol_wasm=Module._ts_node_symbol_wasm=wasmExports.ts_node_symbol_wasm)(r),_ts_node_field_name_for_child_wasm=Module._ts_node_field_name_for_child_wasm=(r,e)=>(_ts_node_field_name_for_child_wasm=Module._ts_node_field_name_for_child_wasm=wasmExports.ts_node_field_name_for_child_wasm)(r,e),_ts_node_children_by_field_id_wasm=Module._ts_node_children_by_field_id_wasm=(r,e)=>(_ts_node_children_by_field_id_wasm=Module._ts_node_children_by_field_id_wasm=wasmExports.ts_node_children_by_field_id_wasm)(r,e),_ts_node_first_child_for_byte_wasm=Module._ts_node_first_child_for_byte_wasm=r=>(_ts_node_first_child_for_byte_wasm=Module._ts_node_first_child_for_byte_wasm=wasmExports.ts_node_first_child_for_byte_wasm)(r),_ts_node_first_named_child_for_byte_wasm=Module._ts_node_first_named_child_for_byte_wasm=r=>(_ts_node_first_named_child_for_byte_wasm=Module._ts_node_first_named_child_for_byte_wasm=wasmExports.ts_node_first_named_child_for_byte_wasm)(r),_ts_node_grammar_symbol_wasm=Module._ts_node_grammar_symbol_wasm=r=>(_ts_node_grammar_symbol_wasm=Module._ts_node_grammar_symbol_wasm=wasmExports.ts_node_grammar_symbol_wasm)(r),_ts_node_child_count_wasm=Module._ts_node_child_count_wasm=r=>(_ts_node_child_count_wasm=Module._ts_node_child_count_wasm=wasmExports.ts_node_child_count_wasm)(r),_ts_node_named_child_count_wasm=Module._ts_node_named_child_count_wasm=r=>(_ts_node_named_child_count_wasm=Module._ts_node_named_child_count_wasm=wasmExports.ts_node_named_child_count_wasm)(r),_ts_node_child_wasm=Module._ts_node_child_wasm=(r,e)=>(_ts_node_child_wasm=Module._ts_node_child_wasm=wasmExports.ts_node_child_wasm)(r,e),_ts_node_named_child_wasm=Module._ts_node_named_child_wasm=(r,e)=>(_ts_node_named_child_wasm=Module._ts_node_named_child_wasm=wasmExports.ts_node_named_child_wasm)(r,e),_ts_node_child_by_field_id_wasm=Module._ts_node_child_by_field_id_wasm=(r,e)=>(_ts_node_child_by_field_id_wasm=Module._ts_node_child_by_field_id_wasm=wasmExports.ts_node_child_by_field_id_wasm)(r,e),_ts_node_next_sibling_wasm=Module._ts_node_next_sibling_wasm=r=>(_ts_node_next_sibling_wasm=Module._ts_node_next_sibling_wasm=wasmExports.ts_node_next_sibling_wasm)(r),_ts_node_prev_sibling_wasm=Module._ts_node_prev_sibling_wasm=r=>(_ts_node_prev_sibling_wasm=Module._ts_node_prev_sibling_wasm=wasmExports.ts_node_prev_sibling_wasm)(r),_ts_node_next_named_sibling_wasm=Module._ts_node_next_named_sibling_wasm=r=>(_ts_node_next_named_sibling_wasm=Module._ts_node_next_named_sibling_wasm=wasmExports.ts_node_next_named_sibling_wasm)(r),_ts_node_prev_named_sibling_wasm=Module._ts_node_prev_named_sibling_wasm=r=>(_ts_node_prev_named_sibling_wasm=Module._ts_node_prev_named_sibling_wasm=wasmExports.ts_node_prev_named_sibling_wasm)(r),_ts_node_descendant_count_wasm=Module._ts_node_descendant_count_wasm=r=>(_ts_node_descendant_count_wasm=Module._ts_node_descendant_count_wasm=wasmExports.ts_node_descendant_count_wasm)(r),_ts_node_parent_wasm=Module._ts_node_parent_wasm=r=>(_ts_node_parent_wasm=Module._ts_node_parent_wasm=wasmExports.ts_node_parent_wasm)(r),_ts_node_descendant_for_index_wasm=Module._ts_node_descendant_for_index_wasm=r=>(_ts_node_descendant_for_index_wasm=Module._ts_node_descendant_for_index_wasm=wasmExports.ts_node_descendant_for_index_wasm)(r),_ts_node_named_descendant_for_index_wasm=Module._ts_node_named_descendant_for_index_wasm=r=>(_ts_node_named_descendant_for_index_wasm=Module._ts_node_named_descendant_for_index_wasm=wasmExports.ts_node_named_descendant_for_index_wasm)(r),_ts_node_descendant_for_position_wasm=Module._ts_node_descendant_for_position_wasm=r=>(_ts_node_descendant_for_position_wasm=Module._ts_node_descendant_for_position_wasm=wasmExports.ts_node_descendant_for_position_wasm)(r),_ts_node_named_descendant_for_position_wasm=Module._ts_node_named_descendant_for_position_wasm=r=>(_ts_node_named_descendant_for_position_wasm=Module._ts_node_named_descendant_for_position_wasm=wasmExports.ts_node_named_descendant_for_position_wasm)(r),_ts_node_start_point_wasm=Module._ts_node_start_point_wasm=r=>(_ts_node_start_point_wasm=Module._ts_node_start_point_wasm=wasmExports.ts_node_start_point_wasm)(r),_ts_node_end_point_wasm=Module._ts_node_end_point_wasm=r=>(_ts_node_end_point_wasm=Module._ts_node_end_point_wasm=wasmExports.ts_node_end_point_wasm)(r),_ts_node_start_index_wasm=Module._ts_node_start_index_wasm=r=>(_ts_node_start_index_wasm=Module._ts_node_start_index_wasm=wasmExports.ts_node_start_index_wasm)(r),_ts_node_end_index_wasm=Module._ts_node_end_index_wasm=r=>(_ts_node_end_index_wasm=Module._ts_node_end_index_wasm=wasmExports.ts_node_end_index_wasm)(r),_ts_node_to_string_wasm=Module._ts_node_to_string_wasm=r=>(_ts_node_to_string_wasm=Module._ts_node_to_string_wasm=wasmExports.ts_node_to_string_wasm)(r),_ts_node_children_wasm=Module._ts_node_children_wasm=r=>(_ts_node_children_wasm=Module._ts_node_children_wasm=wasmExports.ts_node_children_wasm)(r),_ts_node_named_children_wasm=Module._ts_node_named_children_wasm=r=>(_ts_node_named_children_wasm=Module._ts_node_named_children_wasm=wasmExports.ts_node_named_children_wasm)(r),_ts_node_descendants_of_type_wasm=Module._ts_node_descendants_of_type_wasm=(r,e,t,n,s,o,a)=>(_ts_node_descendants_of_type_wasm=Module._ts_node_descendants_of_type_wasm=wasmExports.ts_node_descendants_of_type_wasm)(r,e,t,n,s,o,a),_ts_node_is_named_wasm=Module._ts_node_is_named_wasm=r=>(_ts_node_is_named_wasm=Module._ts_node_is_named_wasm=wasmExports.ts_node_is_named_wasm)(r),_ts_node_has_changes_wasm=Module._ts_node_has_changes_wasm=r=>(_ts_node_has_changes_wasm=Module._ts_node_has_changes_wasm=wasmExports.ts_node_has_changes_wasm)(r),_ts_node_has_error_wasm=Module._ts_node_has_error_wasm=r=>(_ts_node_has_error_wasm=Module._ts_node_has_error_wasm=wasmExports.ts_node_has_error_wasm)(r),_ts_node_is_error_wasm=Module._ts_node_is_error_wasm=r=>(_ts_node_is_error_wasm=Module._ts_node_is_error_wasm=wasmExports.ts_node_is_error_wasm)(r),_ts_node_is_missing_wasm=Module._ts_node_is_missing_wasm=r=>(_ts_node_is_missing_wasm=Module._ts_node_is_missing_wasm=wasmExports.ts_node_is_missing_wasm)(r),_ts_node_is_extra_wasm=Module._ts_node_is_extra_wasm=r=>(_ts_node_is_extra_wasm=Module._ts_node_is_extra_wasm=wasmExports.ts_node_is_extra_wasm)(r),_ts_node_parse_state_wasm=Module._ts_node_parse_state_wasm=r=>(_ts_node_parse_state_wasm=Module._ts_node_parse_state_wasm=wasmExports.ts_node_parse_state_wasm)(r),_ts_node_next_parse_state_wasm=Module._ts_node_next_parse_state_wasm=r=>(_ts_node_next_parse_state_wasm=Module._ts_node_next_parse_state_wasm=wasmExports.ts_node_next_parse_state_wasm)(r),_ts_query_matches_wasm=Module._ts_query_matches_wasm=(r,e,t,n,s,o,a,l,c,u,h)=>(_ts_query_matches_wasm=Module._ts_query_matches_wasm=wasmExports.ts_query_matches_wasm)(r,e,t,n,s,o,a,l,c,u,h),_ts_query_captures_wasm=Module._ts_query_captures_wasm=(r,e,t,n,s,o,a,l,c,u,h)=>(_ts_query_captures_wasm=Module._ts_query_captures_wasm=wasmExports.ts_query_captures_wasm)(r,e,t,n,s,o,a,l,c,u,h),_iswalpha=Module._iswalpha=r=>(_iswalpha=Module._iswalpha=wasmExports.iswalpha)(r),_iswblank=Module._iswblank=r=>(_iswblank=Module._iswblank=wasmExports.iswblank)(r),_iswdigit=Module._iswdigit=r=>(_iswdigit=Module._iswdigit=wasmExports.iswdigit)(r),_iswlower=Module._iswlower=r=>(_iswlower=Module._iswlower=wasmExports.iswlower)(r),_iswupper=Module._iswupper=r=>(_iswupper=Module._iswupper=wasmExports.iswupper)(r),_iswxdigit=Module._iswxdigit=r=>(_iswxdigit=Module._iswxdigit=wasmExports.iswxdigit)(r),_memchr=Module._memchr=(r,e,t)=>(_memchr=Module._memchr=wasmExports.memchr)(r,e,t),_strlen=Module._strlen=r=>(_strlen=Module._strlen=wasmExports.strlen)(r),_strcmp=Module._strcmp=(r,e)=>(_strcmp=Module._strcmp=wasmExports.strcmp)(r,e),_strncat=Module._strncat=(r,e,t)=>(_strncat=Module._strncat=wasmExports.strncat)(r,e,t),_strncpy=Module._strncpy=(r,e,t)=>(_strncpy=Module._strncpy=wasmExports.strncpy)(r,e,t),_towlower=Module._towlower=r=>(_towlower=Module._towlower=wasmExports.towlower)(r),_towupper=Module._towupper=r=>(_towupper=Module._towupper=wasmExports.towupper)(r),_setThrew=(r,e)=>(_setThrew=wasmExports.setThrew)(r,e),__emscripten_stack_restore=r=>(__emscripten_stack_restore=wasmExports._emscripten_stack_restore)(r),__emscripten_stack_alloc=r=>(__emscripten_stack_alloc=wasmExports._emscripten_stack_alloc)(r),_emscripten_stack_get_current=()=>(_emscripten_stack_get_current=wasmExports.emscripten_stack_get_current)(),dynCall_jiji=Module.dynCall_jiji=(r,e,t,n,s)=>(dynCall_jiji=Module.dynCall_jiji=wasmExports.dynCall_jiji)(r,e,t,n,s),_orig$ts_parser_timeout_micros=Module._orig$ts_parser_timeout_micros=r=>(_orig$ts_parser_timeout_micros=Module._orig$ts_parser_timeout_micros=wasmExports.orig$ts_parser_timeout_micros)(r),_orig$ts_parser_set_timeout_micros=Module._orig$ts_parser_set_timeout_micros=(r,e)=>(_orig$ts_parser_set_timeout_micros=Module._orig$ts_parser_set_timeout_micros=wasmExports.orig$ts_parser_set_timeout_micros)(r,e);Module.AsciiToString=AsciiToString,Module.stringToUTF16=stringToUTF16;var calledRun;dependenciesFulfilled=function r(){calledRun||run(),calledRun||(dependenciesFulfilled=r)};function callMain(r=[]){var e=resolveGlobalSymbol("main").sym;if(e){r.unshift(thisProgram);var t=r.length,n=stackAlloc((t+1)*4),s=n;r.forEach(a=>{LE_HEAP_STORE_U32((s>>2)*4,stringToUTF8OnStack(a)),s+=4}),LE_HEAP_STORE_U32((s>>2)*4,0);try{var o=e(t,n);return exitJS(o,!0),o}catch(a){return handleException(a)}}}function run(r=arguments_){if(runDependencies>0||(preRun(),runDependencies>0))return;function e(){calledRun||(calledRun=!0,Module.calledRun=!0,!ABORT&&(initRuntime(),preMain(),Module.onRuntimeInitialized?.(),shouldRunNow&&callMain(r),postRun()))}Module.setStatus?(Module.setStatus("Running..."),setTimeout(function(){setTimeout(function(){Module.setStatus("")},1),e()},1)):e()}if(Module.preInit)for(typeof Module.preInit=="function"&&(Module.preInit=[Module.preInit]);Module.preInit.length>0;)Module.preInit.pop()();var shouldRunNow=!0;Module.noInitialRun&&(shouldRunNow=!1),run();let C=Module,INTERNAL={},SIZE_OF_INT=4,SIZE_OF_CURSOR=4*SIZE_OF_INT,SIZE_OF_NODE=5*SIZE_OF_INT,SIZE_OF_POINT=2*SIZE_OF_INT,SIZE_OF_RANGE=2*SIZE_OF_INT+2*SIZE_OF_POINT,ZERO_POINT={row:0,column:0},QUERY_WORD_REGEX=/[\w-.]*/g,PREDICATE_STEP_TYPE_CAPTURE=1,PREDICATE_STEP_TYPE_STRING=2,LANGUAGE_FUNCTION_REGEX=/^_?tree_sitter_\w+/,VERSION,MIN_COMPATIBLE_VERSION,TRANSFER_BUFFER,currentParseCallback,currentLogCallback;class ParserImpl{static init(){TRANSFER_BUFFER=C._ts_init(),VERSION=getValue(TRANSFER_BUFFER,"i32"),MIN_COMPATIBLE_VERSION=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32")}initialize(){C._ts_parser_new_wasm(),this[0]=getValue(TRANSFER_BUFFER,"i32"),this[1]=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32")}delete(){C._ts_parser_delete(this[0]),C._free(this[1]),this[0]=0,this[1]=0}setLanguage(e){let t;if(!e)t=0,e=null;else if(e.constructor===Language){t=e[0];let n=C._ts_language_version(t);if(n<MIN_COMPATIBLE_VERSION||VERSION<n)throw new Error(`Incompatible language version ${n}. Compatibility range ${MIN_COMPATIBLE_VERSION} through ${VERSION}.`)}else throw new Error("Argument must be a Language");return this.language=e,C._ts_parser_set_language(this[0],t),this}getLanguage(){return this.language}parse(e,t,n){if(typeof e=="string")currentParseCallback=(c,u)=>e.slice(c);else if(typeof e=="function")currentParseCallback=e;else throw new Error("Argument must be a string or a function");this.logCallback?(currentLogCallback=this.logCallback,C._ts_parser_enable_logger_wasm(this[0],1)):(currentLogCallback=null,C._ts_parser_enable_logger_wasm(this[0],0));let s=0,o=0;if(n?.includedRanges){s=n.includedRanges.length,o=C._calloc(s,SIZE_OF_RANGE);let c=o;for(let u=0;u<s;u++)marshalRange(c,n.includedRanges[u]),c+=SIZE_OF_RANGE}let a=C._ts_parser_parse_wasm(this[0],this[1],t?t[0]:0,o,s);if(!a)throw currentParseCallback=null,currentLogCallback=null,new Error("Parsing failed");let l=new Tree(INTERNAL,a,this.language,currentParseCallback);return currentParseCallback=null,currentLogCallback=null,l}reset(){C._ts_parser_reset(this[0])}getIncludedRanges(){C._ts_parser_included_ranges_wasm(this[0]);let e=getValue(TRANSFER_BUFFER,"i32"),t=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32"),n=new Array(e);if(e>0){let s=t;for(let o=0;o<e;o++)n[o]=unmarshalRange(s),s+=SIZE_OF_RANGE;C._free(t)}return n}getTimeoutMicros(){return C._ts_parser_timeout_micros(this[0])}setTimeoutMicros(e){C._ts_parser_set_timeout_micros(this[0],e)}setLogger(e){if(!e)e=null;else if(typeof e!="function")throw new Error("Logger callback must be a function");return this.logCallback=e,this}getLogger(){return this.logCallback}}class Tree{constructor(e,t,n,s){assertInternal(e),this[0]=t,this.language=n,this.textCallback=s}copy(){let e=C._ts_tree_copy(this[0]);return new Tree(INTERNAL,e,this.language,this.textCallback)}delete(){C._ts_tree_delete(this[0]),this[0]=0}edit(e){marshalEdit(e),C._ts_tree_edit_wasm(this[0])}get rootNode(){return C._ts_tree_root_node_wasm(this[0]),unmarshalNode(this)}rootNodeWithOffset(e,t){let n=TRANSFER_BUFFER+SIZE_OF_NODE;return setValue(n,e,"i32"),marshalPoint(n+SIZE_OF_INT,t),C._ts_tree_root_node_with_offset_wasm(this[0]),unmarshalNode(this)}getLanguage(){return this.language}walk(){return this.rootNode.walk()}getChangedRanges(e){if(e.constructor!==Tree)throw new TypeError("Argument must be a Tree");C._ts_tree_get_changed_ranges_wasm(this[0],e[0]);let t=getValue(TRANSFER_BUFFER,"i32"),n=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32"),s=new Array(t);if(t>0){let o=n;for(let a=0;a<t;a++)s[a]=unmarshalRange(o),o+=SIZE_OF_RANGE;C._free(n)}return s}getIncludedRanges(){C._ts_tree_included_ranges_wasm(this[0]);let e=getValue(TRANSFER_BUFFER,"i32"),t=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32"),n=new Array(e);if(e>0){let s=t;for(let o=0;o<e;o++)n[o]=unmarshalRange(s),s+=SIZE_OF_RANGE;C._free(t)}return n}}class Node{constructor(e,t){assertInternal(e),this.tree=t}get typeId(){return marshalNode(this),C._ts_node_symbol_wasm(this.tree[0])}get grammarId(){return marshalNode(this),C._ts_node_grammar_symbol_wasm(this.tree[0])}get type(){return this.tree.language.types[this.typeId]||"ERROR"}get grammarType(){return this.tree.language.types[this.grammarId]||"ERROR"}get endPosition(){return marshalNode(this),C._ts_node_end_point_wasm(this.tree[0]),unmarshalPoint(TRANSFER_BUFFER)}get endIndex(){return marshalNode(this),C._ts_node_end_index_wasm(this.tree[0])}get text(){return getText(this.tree,this.startIndex,this.endIndex)}get parseState(){return marshalNode(this),C._ts_node_parse_state_wasm(this.tree[0])}get nextParseState(){return marshalNode(this),C._ts_node_next_parse_state_wasm(this.tree[0])}get isNamed(){return marshalNode(this),C._ts_node_is_named_wasm(this.tree[0])===1}get hasError(){return marshalNode(this),C._ts_node_has_error_wasm(this.tree[0])===1}get hasChanges(){return marshalNode(this),C._ts_node_has_changes_wasm(this.tree[0])===1}get isError(){return marshalNode(this),C._ts_node_is_error_wasm(this.tree[0])===1}get isMissing(){return marshalNode(this),C._ts_node_is_missing_wasm(this.tree[0])===1}get isExtra(){return marshalNode(this),C._ts_node_is_extra_wasm(this.tree[0])===1}equals(e){return this.id===e.id}child(e){return marshalNode(this),C._ts_node_child_wasm(this.tree[0],e),unmarshalNode(this.tree)}namedChild(e){return marshalNode(this),C._ts_node_named_child_wasm(this.tree[0],e),unmarshalNode(this.tree)}childForFieldId(e){return marshalNode(this),C._ts_node_child_by_field_id_wasm(this.tree[0],e),unmarshalNode(this.tree)}childForFieldName(e){let t=this.tree.language.fields.indexOf(e);return t!==-1?this.childForFieldId(t):null}fieldNameForChild(e){marshalNode(this);let t=C._ts_node_field_name_for_child_wasm(this.tree[0],e);return t?AsciiToString(t):null}childrenForFieldName(e){let t=this.tree.language.fields.indexOf(e);return t!==-1&&t!==0?this.childrenForFieldId(t):[]}childrenForFieldId(e){marshalNode(this),C._ts_node_children_by_field_id_wasm(this.tree[0],e);let t=getValue(TRANSFER_BUFFER,"i32"),n=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32"),s=new Array(t);if(t>0){let o=n;for(let a=0;a<t;a++)s[a]=unmarshalNode(this.tree,o),o+=SIZE_OF_NODE;C._free(n)}return s}firstChildForIndex(e){marshalNode(this);let t=TRANSFER_BUFFER+SIZE_OF_NODE;return setValue(t,e,"i32"),C._ts_node_first_child_for_byte_wasm(this.tree[0]),unmarshalNode(this.tree)}firstNamedChildForIndex(e){marshalNode(this);let t=TRANSFER_BUFFER+SIZE_OF_NODE;return setValue(t,e,"i32"),C._ts_node_first_named_child_for_byte_wasm(this.tree[0]),unmarshalNode(this.tree)}get childCount(){return marshalNode(this),C._ts_node_child_count_wasm(this.tree[0])}get namedChildCount(){return marshalNode(this),C._ts_node_named_child_count_wasm(this.tree[0])}get firstChild(){return this.child(0)}get firstNamedChild(){return this.namedChild(0)}get lastChild(){return this.child(this.childCount-1)}get lastNamedChild(){return this.namedChild(this.namedChildCount-1)}get children(){if(!this._children){marshalNode(this),C._ts_node_children_wasm(this.tree[0]);let e=getValue(TRANSFER_BUFFER,"i32"),t=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32");if(this._children=new Array(e),e>0){let n=t;for(let s=0;s<e;s++)this._children[s]=unmarshalNode(this.tree,n),n+=SIZE_OF_NODE;C._free(t)}}return this._children}get namedChildren(){if(!this._namedChildren){marshalNode(this),C._ts_node_named_children_wasm(this.tree[0]);let e=getValue(TRANSFER_BUFFER,"i32"),t=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32");if(this._namedChildren=new Array(e),e>0){let n=t;for(let s=0;s<e;s++)this._namedChildren[s]=unmarshalNode(this.tree,n),n+=SIZE_OF_NODE;C._free(t)}}return this._namedChildren}descendantsOfType(e,t,n){Array.isArray(e)||(e=[e]),t||(t=ZERO_POINT),n||(n=ZERO_POINT);let s=[],o=this.tree.language.types;for(let h=0,d=o.length;h<d;h++)e.includes(o[h])&&s.push(h);let a=C._malloc(SIZE_OF_INT*s.length);for(let h=0,d=s.length;h<d;h++)setValue(a+h*SIZE_OF_INT,s[h],"i32");marshalNode(this),C._ts_node_descendants_of_type_wasm(this.tree[0],a,s.length,t.row,t.column,n.row,n.column);let l=getValue(TRANSFER_BUFFER,"i32"),c=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32"),u=new Array(l);if(l>0){let h=c;for(let d=0;d<l;d++)u[d]=unmarshalNode(this.tree,h),h+=SIZE_OF_NODE}return C._free(c),C._free(a),u}get nextSibling(){return marshalNode(this),C._ts_node_next_sibling_wasm(this.tree[0]),unmarshalNode(this.tree)}get previousSibling(){return marshalNode(this),C._ts_node_prev_sibling_wasm(this.tree[0]),unmarshalNode(this.tree)}get nextNamedSibling(){return marshalNode(this),C._ts_node_next_named_sibling_wasm(this.tree[0]),unmarshalNode(this.tree)}get previousNamedSibling(){return marshalNode(this),C._ts_node_prev_named_sibling_wasm(this.tree[0]),unmarshalNode(this.tree)}get descendantCount(){return marshalNode(this),C._ts_node_descendant_count_wasm(this.tree[0])}get parent(){return marshalNode(this),C._ts_node_parent_wasm(this.tree[0]),unmarshalNode(this.tree)}descendantForIndex(e,t=e){if(typeof e!="number"||typeof t!="number")throw new Error("Arguments must be numbers");marshalNode(this);let n=TRANSFER_BUFFER+SIZE_OF_NODE;return setValue(n,e,"i32"),setValue(n+SIZE_OF_INT,t,"i32"),C._ts_node_descendant_for_index_wasm(this.tree[0]),unmarshalNode(this.tree)}namedDescendantForIndex(e,t=e){if(typeof e!="number"||typeof t!="number")throw new Error("Arguments must be numbers");marshalNode(this);let n=TRANSFER_BUFFER+SIZE_OF_NODE;return setValue(n,e,"i32"),setValue(n+SIZE_OF_INT,t,"i32"),C._ts_node_named_descendant_for_index_wasm(this.tree[0]),unmarshalNode(this.tree)}descendantForPosition(e,t=e){if(!isPoint(e)||!isPoint(t))throw new Error("Arguments must be {row, column} objects");marshalNode(this);let n=TRANSFER_BUFFER+SIZE_OF_NODE;return marshalPoint(n,e),marshalPoint(n+SIZE_OF_POINT,t),C._ts_node_descendant_for_position_wasm(this.tree[0]),unmarshalNode(this.tree)}namedDescendantForPosition(e,t=e){if(!isPoint(e)||!isPoint(t))throw new Error("Arguments must be {row, column} objects");marshalNode(this);let n=TRANSFER_BUFFER+SIZE_OF_NODE;return marshalPoint(n,e),marshalPoint(n+SIZE_OF_POINT,t),C._ts_node_named_descendant_for_position_wasm(this.tree[0]),unmarshalNode(this.tree)}walk(){return marshalNode(this),C._ts_tree_cursor_new_wasm(this.tree[0]),new TreeCursor(INTERNAL,this.tree)}toString(){marshalNode(this);let e=C._ts_node_to_string_wasm(this.tree[0]),t=AsciiToString(e);return C._free(e),t}}class TreeCursor{constructor(e,t){assertInternal(e),this.tree=t,unmarshalTreeCursor(this)}delete(){marshalTreeCursor(this),C._ts_tree_cursor_delete_wasm(this.tree[0]),this[0]=this[1]=this[2]=0}reset(e){marshalNode(e),marshalTreeCursor(this,TRANSFER_BUFFER+SIZE_OF_NODE),C._ts_tree_cursor_reset_wasm(this.tree[0]),unmarshalTreeCursor(this)}resetTo(e){marshalTreeCursor(this,TRANSFER_BUFFER),marshalTreeCursor(e,TRANSFER_BUFFER+SIZE_OF_CURSOR),C._ts_tree_cursor_reset_to_wasm(this.tree[0],e.tree[0]),unmarshalTreeCursor(this)}get nodeType(){return this.tree.language.types[this.nodeTypeId]||"ERROR"}get nodeTypeId(){return marshalTreeCursor(this),C._ts_tree_cursor_current_node_type_id_wasm(this.tree[0])}get nodeStateId(){return marshalTreeCursor(this),C._ts_tree_cursor_current_node_state_id_wasm(this.tree[0])}get nodeId(){return marshalTreeCursor(this),C._ts_tree_cursor_current_node_id_wasm(this.tree[0])}get nodeIsNamed(){return marshalTreeCursor(this),C._ts_tree_cursor_current_node_is_named_wasm(this.tree[0])===1}get nodeIsMissing(){return marshalTreeCursor(this),C._ts_tree_cursor_current_node_is_missing_wasm(this.tree[0])===1}get nodeText(){marshalTreeCursor(this);let e=C._ts_tree_cursor_start_index_wasm(this.tree[0]),t=C._ts_tree_cursor_end_index_wasm(this.tree[0]);return getText(this.tree,e,t)}get startPosition(){return marshalTreeCursor(this),C._ts_tree_cursor_start_position_wasm(this.tree[0]),unmarshalPoint(TRANSFER_BUFFER)}get endPosition(){return marshalTreeCursor(this),C._ts_tree_cursor_end_position_wasm(this.tree[0]),unmarshalPoint(TRANSFER_BUFFER)}get startIndex(){return marshalTreeCursor(this),C._ts_tree_cursor_start_index_wasm(this.tree[0])}get endIndex(){return marshalTreeCursor(this),C._ts_tree_cursor_end_index_wasm(this.tree[0])}get currentNode(){return marshalTreeCursor(this),C._ts_tree_cursor_current_node_wasm(this.tree[0]),unmarshalNode(this.tree)}get currentFieldId(){return marshalTreeCursor(this),C._ts_tree_cursor_current_field_id_wasm(this.tree[0])}get currentFieldName(){return this.tree.language.fields[this.currentFieldId]}get currentDepth(){return marshalTreeCursor(this),C._ts_tree_cursor_current_depth_wasm(this.tree[0])}get currentDescendantIndex(){return marshalTreeCursor(this),C._ts_tree_cursor_current_descendant_index_wasm(this.tree[0])}gotoFirstChild(){marshalTreeCursor(this);let e=C._ts_tree_cursor_goto_first_child_wasm(this.tree[0]);return unmarshalTreeCursor(this),e===1}gotoLastChild(){marshalTreeCursor(this);let e=C._ts_tree_cursor_goto_last_child_wasm(this.tree[0]);return unmarshalTreeCursor(this),e===1}gotoFirstChildForIndex(e){marshalTreeCursor(this),setValue(TRANSFER_BUFFER+SIZE_OF_CURSOR,e,"i32");let t=C._ts_tree_cursor_goto_first_child_for_index_wasm(this.tree[0]);return unmarshalTreeCursor(this),t===1}gotoFirstChildForPosition(e){marshalTreeCursor(this),marshalPoint(TRANSFER_BUFFER+SIZE_OF_CURSOR,e);let t=C._ts_tree_cursor_goto_first_child_for_position_wasm(this.tree[0]);return unmarshalTreeCursor(this),t===1}gotoNextSibling(){marshalTreeCursor(this);let e=C._ts_tree_cursor_goto_next_sibling_wasm(this.tree[0]);return unmarshalTreeCursor(this),e===1}gotoPreviousSibling(){marshalTreeCursor(this);let e=C._ts_tree_cursor_goto_previous_sibling_wasm(this.tree[0]);return unmarshalTreeCursor(this),e===1}gotoDescendant(e){marshalTreeCursor(this),C._ts_tree_cursor_goto_descendant_wasm(this.tree[0],e),unmarshalTreeCursor(this)}gotoParent(){marshalTreeCursor(this);let e=C._ts_tree_cursor_goto_parent_wasm(this.tree[0]);return unmarshalTreeCursor(this),e===1}}class Language{constructor(e,t){assertInternal(e),this[0]=t,this.types=new Array(C._ts_language_symbol_count(this[0]));for(let n=0,s=this.types.length;n<s;n++)C._ts_language_symbol_type(this[0],n)<2&&(this.types[n]=UTF8ToString(C._ts_language_symbol_name(this[0],n)));this.fields=new Array(C._ts_language_field_count(this[0])+1);for(let n=0,s=this.fields.length;n<s;n++){let o=C._ts_language_field_name_for_id(this[0],n);o!==0?this.fields[n]=UTF8ToString(o):this.fields[n]=null}}get version(){return C._ts_language_version(this[0])}get fieldCount(){return this.fields.length-1}get stateCount(){return C._ts_language_state_count(this[0])}fieldIdForName(e){let t=this.fields.indexOf(e);return t!==-1?t:null}fieldNameForId(e){return this.fields[e]||null}idForNodeType(e,t){let n=lengthBytesUTF8(e),s=C._malloc(n+1);stringToUTF8(e,s,n+1);let o=C._ts_language_symbol_for_name(this[0],s,n,t);return C._free(s),o||null}get nodeTypeCount(){return C._ts_language_symbol_count(this[0])}nodeTypeForId(e){let t=C._ts_language_symbol_name(this[0],e);return t?UTF8ToString(t):null}nodeTypeIsNamed(e){return!!C._ts_language_type_is_named_wasm(this[0],e)}nodeTypeIsVisible(e){return!!C._ts_language_type_is_visible_wasm(this[0],e)}nextState(e,t){return C._ts_language_next_state(this[0],e,t)}lookaheadIterator(e){let t=C._ts_lookahead_iterator_new(this[0],e);return t?new LookaheadIterable(INTERNAL,t,this):null}query(e){let t=lengthBytesUTF8(e),n=C._malloc(t+1);stringToUTF8(e,n,t+1);let s=C._ts_query_new(this[0],n,t,TRANSFER_BUFFER,TRANSFER_BUFFER+SIZE_OF_INT);if(!s){let w=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32"),m=getValue(TRANSFER_BUFFER,"i32"),_=UTF8ToString(n,m).length,b=e.substr(_,100).split(`
3
+ import{a as xe,b as mz,c as kP,d as gz,e as B,f as yz,g as Ze,h as Tt,i as wz,j as _z,k as rr,l as oe,m as le,n as mr,o as Ut,p as xP,q as AP,r as At,s as Vn,t as de,u as Zt,v as bz,w as RP,x as vz,y as Sz}from"./chunk-TZIDSCTF.js";import{d as kz,e as xz,g as Oz,h as Dz,i as Lz,j as PP,m as Nz}from"./chunk-ROETRE5J.js";import{d as Fz,k as MP,n as $z,p as Uz}from"./chunk-INAZKGGR.js";import{b as Che,i as Az,j as Rz,k as Pz,o as rm,p as Mz,r as Iz}from"./chunk-DCQKJTAX.js";import{a as Wt}from"./chunk-LSDMWVW6.js";import{a as lv,b as Ez,d as LP,e as dv}from"./chunk-MTMU7JYZ.js";import{a as Hz,b as Bz,c as nm}from"./chunk-TXMXCR7D.js";import{a as IP}from"./chunk-YULUB745.js";import{a as jz,b as zz,c as qz,d as OP,e as Wz,f as DP}from"./chunk-VYTYYCBR.js";import{a as wj,b as Ha,c as _j}from"./chunk-TISQNFB5.js";import{a as Bi,b as EP,c as $d,t as TP}from"./chunk-34DXSYJZ.js";import{a as uv,b as sm}from"./chunk-FWIVFCKF.js";import{b as Cz,g as cv,j as tm,k as Tz,l as As}from"./chunk-QKYGQLWC.js";import{a as nt,b as Ud,d as Bd,e as jd}from"./chunk-FRL6KOLY.js";import{b as No,d as iz,f as oz,i as ct,j as az,k as lz,l as cz,m as uz,n as dz,o as hz,p as fz,q as pz}from"./chunk-VWWEEU4V.js";import{b as Hd}from"./chunk-RNKDFE2S.js";import{a as sz}from"./chunk-Q2I3ARPJ.js";import{a as av}from"./chunk-SNTDBBLK.js";import{a as bj}from"./chunk-QHA3ZBRO.js";import{$ as vP,U as yP,V as J2,W as Q2,Z as Rc,_ as em,b as pP,ba as SP,c as mP,d as z2,e as gP,ea as iv,f as q2,ga as ov,pa as an,qa as CP,ta as Fd}from"./chunk-L6RZIQQE.js";import{a as Do,c as wP}from"./chunk-4F4DA5UI.js";import{e as _P,f as bP}from"./chunk-DC7LAFZZ.js";import{m as Nd,p as X2,r as Z2,v as Qp}from"./chunk-S7G6QPEP.js";import{a as Uj,b as Gr,c as xs,d as Hj,f as Bj}from"./chunk-4J6DC24J.js";import{a as W2,g as G2,h as V2,k as Ld,l as K2,m as Y2}from"./chunk-SDTWBD62.js";import{$a as Yb,$b as S2,$c as aP,Ab as f2,Ac as sP,B as Vj,Bb as p2,Bc as iP,Cb as m2,Cc as Oo,Db as g2,Eb as y2,Ec as oP,F as Id,G as Kj,Gb as YR,Ha as Xj,Ic as O2,Jb as w2,Mc as D2,Ob as _2,Oc as L2,Qc as Dd,Rc as N2,Sb as Od,Sc as F2,Tb as b2,Ub as v2,Va as Zj,Vc as tv,Yb as Xb,Za as Qj,_a as za,_b as JR,aa as Yj,ab as e2,ac as Tc,ad as Ac,bb as t2,bc as XR,bd as $2,cb as on,cd as rv,d as Oj,da as ja,dc as C2,ec as ZR,ed as lP,f as Io,fc as E2,fd as cP,g as Wb,ga as Yp,gb as VR,gc as QR,gd as uP,h as Gn,ha as Kb,hb as r2,hc as eP,i as Ba,ib as n2,ic as tP,id as dP,jb as s2,k as jj,kb as KR,kd as U2,l as zj,lb as i2,m as qj,mb as o2,mc as T2,nb as a2,nc as k2,ob as l2,oc as x2,od as H2,p as Cc,pb as c2,pd as B2,q as Kp,qb as u2,qd as j2,r as Wj,rb as d2,rc as rP,rd as hP,s as Gj,sb as h2,sc as Zb,t as Ec,tc as Qb,uc as R2,ud as fP,vb as Jb,vc as P2,vd as nv,wd as sv,xc as nP,ya as GR,yc as Zp,za as Jj,zc as M2}from"./chunk-B3NVKOSU.js";import{b as Hi,h as Mr,k as A2,l as kc,m as Ir,n as xc,o as Jp,s as ei,t as Xp,w as ev}from"./chunk-32PTAACU.js";import{a as I2}from"./chunk-32T6RWWT.js";import{b as Dj,c as vhe,d as She,e as Lj,f as Nj,g as Zs,i as Qs,j as Fj,k as qR,o as $j,p as R,q as Cn,r as Gb,s as Vb}from"./chunk-6B5BDE7S.js";import{a as nz}from"./chunk-RJX7DK4Y.js";import{a as tz,b as Lo,c as rz}from"./chunk-ESSYHTAZ.js";import{b as ez}from"./chunk-3YLXGE6T.js";import{b as Xe,c as ks,e as Md}from"./chunk-EQEQPZLQ.js";import{A as Rd,D as Ej,E as Tj,G as Xs,H as Pd,J as Sc,K as kj,N as BR,O as jR,P as fe,U as Pj,V as Mj,X as Ij,_ as zR,aa as $,b as Ot,c as zb,d as re,e as Mo,q as vj,s as Sj,v as Cj,w as sn}from"./chunk-VLYRNOD3.js";import{a as WR}from"./chunk-G7R2XEEF.js";import{g as qb,h as xj,l as Aj,n as Rj}from"./chunk-FWDMPRKU.js";import{a as __matilda_dirname,b as g}from"./chunk-GZPNIYVZ.js";import{a as Se,c as _he,d as N,e as bhe,f as Ve}from"./chunk-OWGSC52X.js";var w3=N((tet,y3)=>{"use strict";g();y3.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 T3=N((net,E3)=>{"use strict";g();var C3="(?:"+["\\|\\|","\\&\\&",";;","\\|\\&","\\<\\(","\\<\\<\\<",">>",">\\&","<\\&","[&;()|<>]"].join("|")+")",_3=new RegExp("^"+C3+"$"),b3="|&;()<> \\t",Yye='"((\\\\"|[^"])*?)"',Jye="'((\\\\'|[^'])*?)'",Xye=/^#$/,v3="'",S3='"',RM="$",Yc="",Zye=4294967296;for(PM=0;PM<4;PM++)Yc+=(Zye*Math.random()).toString(16);var PM,Qye=new RegExp("^"+Yc);function ewe(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 twe(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+Yc+JSON.stringify(n)+Yc:e+n}function rwe(r,e,t){t||(t={});var n=t.escape||"\\",s="(\\"+n+`['"`+b3+`]|[^\\s'"`+b3+"])+",o=new RegExp(["("+C3+")","("+s+"|"+Yye+"|"+Jye+")+"].join("|"),"g"),a=ewe(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(_3.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 twe(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==v3?f+=m:m===n?(y+=1,m=u.charAt(y),m===S3||m===n||m===RM?f+=m:f+=n+m):m===RM?f+=w():f+=m;else if(m===S3||m===v3)h=m;else{if(_3.test(m))return{op:u};if(Xye.test(m)){l=!0;var _={comment:r.slice(c.index+y+1)};return f.length?[f,_]:[_]}else m===n?d=!0:m===RM?f+=w():f+=m}}return p?{op:"glob",pattern:f}:f}).reduce(function(c,u){return typeof u>"u"?c:c.concat(u)},[])}E3.exports=function(e,t,n){var s=rwe(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("("+Yc+".*?"+Yc+")","g"));return l.length===1?o.concat(l[0]):o.concat(l.filter(Boolean).map(function(c){return Qye.test(c)?JSON.parse(c.split(Yc)[1]):c}))},[])}});var rl=N(MM=>{"use strict";g();MM.quote=w3();MM.parse=T3()});var r4=N((exports,module)=>{g();var Module=typeof Module<"u"?Module:{},ENVIRONMENT_IS_WEB=typeof window=="object",ENVIRONMENT_IS_WORKER=typeof importScripts=="function",ENVIRONMENT_IS_NODE=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",TreeSitter=function(){var initPromise,document=typeof window=="object"?{currentScript:window.document.currentScript}:null;class Parser{constructor(){this.initialize()}initialize(){throw new Error("cannot construct a Parser before calling `init()`")}static init(moduleOptions){return initPromise||(Module=Object.assign({},Module,moduleOptions),initPromise=new Promise(resolveInitPromise=>{var moduleOverrides=Object.assign({},Module),arguments_=[],thisProgram="./this.program",quit_=(r,e)=>{throw e},scriptDirectory="";function locateFile(r){return Module.locateFile?Module.locateFile(r,scriptDirectory):scriptDirectory+r}var readAsync,readBinary;if(ENVIRONMENT_IS_NODE){var fs=Se("fs"),nodePath=Se("path");scriptDirectory=__matilda_dirname+"/",readBinary=r=>{r=isFileURI(r)?new URL(r):nodePath.normalize(r);var e=fs.readFileSync(r);return e},readAsync=(r,e=!0)=>(r=isFileURI(r)?new URL(r):nodePath.normalize(r),new Promise((t,n)=>{fs.readFile(r,e?void 0:"utf8",(s,o)=>{s?n(s):t(e?o.buffer:o)})})),!Module.thisProgram&&process.argv.length>1&&(thisProgram=process.argv[1].replace(/\\/g,"/")),arguments_=process.argv.slice(2),typeof module<"u"&&(module.exports=Module),quit_=(r,e)=>{throw process.exitCode=r,e}}else(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER)&&(ENVIRONMENT_IS_WORKER?scriptDirectory=self.location.href:typeof document<"u"&&document.currentScript&&(scriptDirectory=document.currentScript.src),scriptDirectory.startsWith("blob:")?scriptDirectory="":scriptDirectory=scriptDirectory.substr(0,scriptDirectory.replace(/[?#].*/,"").lastIndexOf("/")+1),ENVIRONMENT_IS_WORKER&&(readBinary=r=>{var e=new XMLHttpRequest;return e.open("GET",r,!1),e.responseType="arraybuffer",e.send(null),new Uint8Array(e.response)}),readAsync=r=>isFileURI(r)?new Promise((e,t)=>{var n=new XMLHttpRequest;n.open("GET",r,!0),n.responseType="arraybuffer",n.onload=()=>{(n.status==200||n.status==0&&n.response)&&t(n.response),e(n.status)},n.onerror=e,n.send(null)}):fetch(r,{credentials:"same-origin"}).then(e=>e.ok?e.arrayBuffer():Promise.reject(new Error(e.status+" : "+e.url))));var out=Module.print||console.log.bind(console),err=Module.printErr||console.error.bind(console);Object.assign(Module,moduleOverrides),moduleOverrides=null,Module.arguments&&(arguments_=Module.arguments),Module.thisProgram&&(thisProgram=Module.thisProgram),Module.quit&&(quit_=Module.quit);var dynamicLibraries=Module.dynamicLibraries||[],wasmBinary;Module.wasmBinary&&(wasmBinary=Module.wasmBinary);var wasmMemory,ABORT=!1,EXITSTATUS,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64,HEAP_DATA_VIEW;function updateMemoryViews(){var r=wasmMemory.buffer;Module.HEAP_DATA_VIEW=HEAP_DATA_VIEW=new DataView(r),Module.HEAP8=HEAP8=new Int8Array(r),Module.HEAP16=HEAP16=new Int16Array(r),Module.HEAPU8=HEAPU8=new Uint8Array(r),Module.HEAPU16=HEAPU16=new Uint16Array(r),Module.HEAP32=HEAP32=new Int32Array(r),Module.HEAPU32=HEAPU32=new Uint32Array(r),Module.HEAPF32=HEAPF32=new Float32Array(r),Module.HEAPF64=HEAPF64=new Float64Array(r)}if(Module.wasmMemory)wasmMemory=Module.wasmMemory;else{var INITIAL_MEMORY=Module.INITIAL_MEMORY||33554432;wasmMemory=new WebAssembly.Memory({initial:INITIAL_MEMORY/65536,maximum:2147483648/65536})}updateMemoryViews();var __ATPRERUN__=[],__ATINIT__=[],__ATMAIN__=[],__ATPOSTRUN__=[],__RELOC_FUNCS__=[],runtimeInitialized=!1;function preRun(){if(Module.preRun)for(typeof Module.preRun=="function"&&(Module.preRun=[Module.preRun]);Module.preRun.length;)addOnPreRun(Module.preRun.shift());callRuntimeCallbacks(__ATPRERUN__)}function initRuntime(){runtimeInitialized=!0,callRuntimeCallbacks(__RELOC_FUNCS__),callRuntimeCallbacks(__ATINIT__)}function preMain(){callRuntimeCallbacks(__ATMAIN__)}function postRun(){if(Module.postRun)for(typeof Module.postRun=="function"&&(Module.postRun=[Module.postRun]);Module.postRun.length;)addOnPostRun(Module.postRun.shift());callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(r){__ATPRERUN__.unshift(r)}function addOnInit(r){__ATINIT__.unshift(r)}function addOnPostRun(r){__ATPOSTRUN__.unshift(r)}var runDependencies=0,runDependencyWatcher=null,dependenciesFulfilled=null;function getUniqueRunDependency(r){return r}function addRunDependency(r){runDependencies++,Module.monitorRunDependencies?.(runDependencies)}function removeRunDependency(r){if(runDependencies--,Module.monitorRunDependencies?.(runDependencies),runDependencies==0&&(runDependencyWatcher!==null&&(clearInterval(runDependencyWatcher),runDependencyWatcher=null),dependenciesFulfilled)){var e=dependenciesFulfilled;dependenciesFulfilled=null,e()}}function abort(r){Module.onAbort?.(r),r="Aborted("+r+")",err(r),ABORT=!0,EXITSTATUS=1,r+=". Build with -sASSERTIONS for more info.";var e=new WebAssembly.RuntimeError(r);throw e}var dataURIPrefix="data:application/octet-stream;base64,",isDataURI=r=>r.startsWith(dataURIPrefix),isFileURI=r=>r.startsWith("file://");function findWasmBinary(){var r="tree-sitter.wasm";return isDataURI(r)?r:locateFile(r)}var wasmBinaryFile;function getBinarySync(r){if(r==wasmBinaryFile&&wasmBinary)return new Uint8Array(wasmBinary);if(readBinary)return readBinary(r);throw"both async and sync fetching of the wasm failed"}function getBinaryPromise(r){return wasmBinary?Promise.resolve().then(()=>getBinarySync(r)):readAsync(r).then(e=>new Uint8Array(e),()=>getBinarySync(r))}function instantiateArrayBuffer(r,e,t){return getBinaryPromise(r).then(n=>WebAssembly.instantiate(n,e)).then(t,n=>{err(`failed to asynchronously prepare wasm: ${n}`),abort(n)})}function instantiateAsync(r,e,t,n){return!r&&typeof WebAssembly.instantiateStreaming=="function"&&!isDataURI(e)&&!isFileURI(e)&&!ENVIRONMENT_IS_NODE&&typeof fetch=="function"?fetch(e,{credentials:"same-origin"}).then(s=>{var o=WebAssembly.instantiateStreaming(s,t);return o.then(n,function(a){return err(`wasm streaming compile failed: ${a}`),err("falling back to ArrayBuffer instantiation"),instantiateArrayBuffer(e,t,n)})}):instantiateArrayBuffer(e,t,n)}function getWasmImports(){return{env:wasmImports,wasi_snapshot_preview1:wasmImports,"GOT.mem":new Proxy(wasmImports,GOTHandler),"GOT.func":new Proxy(wasmImports,GOTHandler)}}function createWasm(){var r=getWasmImports();function e(n,s){wasmExports=n.exports,wasmExports=relocateExports(wasmExports,1024);var o=getDylinkMetadata(s);return o.neededDynlibs&&(dynamicLibraries=o.neededDynlibs.concat(dynamicLibraries)),mergeLibSymbols(wasmExports,"main"),LDSO.init(),loadDylibs(),addOnInit(wasmExports.__wasm_call_ctors),__RELOC_FUNCS__.push(wasmExports.__wasm_apply_data_relocs),removeRunDependency("wasm-instantiate"),wasmExports}addRunDependency("wasm-instantiate");function t(n){e(n.instance,n.module)}if(Module.instantiateWasm)try{return Module.instantiateWasm(r,e)}catch(n){return err(`Module.instantiateWasm callback failed with error: ${n}`),!1}return wasmBinaryFile||(wasmBinaryFile=findWasmBinary()),instantiateAsync(wasmBinary,wasmBinaryFile,r,t),{}}var ASM_CONSTS={};function ExitStatus(r){this.name="ExitStatus",this.message=`Program terminated with exit(${r})`,this.status=r}var GOT={},currentModuleWeakSymbols=new Set([]),GOTHandler={get(r,e){var t=GOT[e];return t||(t=GOT[e]=new WebAssembly.Global({value:"i32",mutable:!0})),currentModuleWeakSymbols.has(e)||(t.required=!0),t}},LE_HEAP_LOAD_F32=r=>HEAP_DATA_VIEW.getFloat32(r,!0),LE_HEAP_LOAD_F64=r=>HEAP_DATA_VIEW.getFloat64(r,!0),LE_HEAP_LOAD_I16=r=>HEAP_DATA_VIEW.getInt16(r,!0),LE_HEAP_LOAD_I32=r=>HEAP_DATA_VIEW.getInt32(r,!0),LE_HEAP_LOAD_U32=r=>HEAP_DATA_VIEW.getUint32(r,!0),LE_HEAP_STORE_F32=(r,e)=>HEAP_DATA_VIEW.setFloat32(r,e,!0),LE_HEAP_STORE_F64=(r,e)=>HEAP_DATA_VIEW.setFloat64(r,e,!0),LE_HEAP_STORE_I16=(r,e)=>HEAP_DATA_VIEW.setInt16(r,e,!0),LE_HEAP_STORE_I32=(r,e)=>HEAP_DATA_VIEW.setInt32(r,e,!0),LE_HEAP_STORE_U32=(r,e)=>HEAP_DATA_VIEW.setUint32(r,e,!0),callRuntimeCallbacks=r=>{for(;r.length>0;)r.shift()(Module)},UTF8Decoder=typeof TextDecoder<"u"?new TextDecoder:void 0,UTF8ArrayToString=(r,e,t)=>{for(var n=e+t,s=e;r[s]&&!(s>=n);)++s;if(s-e>16&&r.buffer&&UTF8Decoder)return UTF8Decoder.decode(r.subarray(e,s));for(var o="";e<s;){var a=r[e++];if(!(a&128)){o+=String.fromCharCode(a);continue}var l=r[e++]&63;if((a&224)==192){o+=String.fromCharCode((a&31)<<6|l);continue}var c=r[e++]&63;if((a&240)==224?a=(a&15)<<12|l<<6|c:a=(a&7)<<18|l<<12|c<<6|r[e++]&63,a<65536)o+=String.fromCharCode(a);else{var u=a-65536;o+=String.fromCharCode(55296|u>>10,56320|u&1023)}}return o},getDylinkMetadata=r=>{var e=0,t=0;function n(){return r[e++]}function s(){for(var H=0,G=1;;){var j=r[e++];if(H+=(j&127)*G,G*=128,!(j&128))break}return H}function o(){var H=s();return e+=H,UTF8ArrayToString(r,e-H,H)}function a(H,G){if(H)throw new Error(G)}var l="dylink.0";if(r instanceof WebAssembly.Module){var c=WebAssembly.Module.customSections(r,l);c.length===0&&(l="dylink",c=WebAssembly.Module.customSections(r,l)),a(c.length===0,"need dylink section"),r=new Uint8Array(c[0]),t=r.length}else{var u=new Uint32Array(new Uint8Array(r.subarray(0,24)).buffer),h=u[0]==1836278016||u[0]==6386541;a(!h,"need to see wasm magic number"),a(r[8]!==0,"need the dylink section to be first"),e=9;var d=s();t=e+d,l=o()}var f={neededDynlibs:[],tlsExports:new Set,weakImports:new Set};if(l=="dylink"){f.memorySize=s(),f.memoryAlign=s(),f.tableSize=s(),f.tableAlign=s();for(var p=s(),y=0;y<p;++y){var w=o();f.neededDynlibs.push(w)}}else{a(l!=="dylink.0");for(var m=1,_=2,b=3,v=4,S=256,E=3,T=1;e<t;){var A=n(),k=s();if(A===m)f.memorySize=s(),f.memoryAlign=s(),f.tableSize=s(),f.tableAlign=s();else if(A===_)for(var p=s(),y=0;y<p;++y)w=o(),f.neededDynlibs.push(w);else if(A===b)for(var P=s();P--;){var U=o(),F=s();F&S&&f.tlsExports.add(U)}else if(A===v)for(var P=s();P--;){var D=o(),U=o(),F=s();(F&E)==T&&f.weakImports.add(U)}else e+=k}}return f};function getValue(r,e="i8"){switch(e.endsWith("*")&&(e="*"),e){case"i1":return HEAP8[r];case"i8":return HEAP8[r];case"i16":return LE_HEAP_LOAD_I16((r>>1)*2);case"i32":return LE_HEAP_LOAD_I32((r>>2)*4);case"i64":abort("to do getValue(i64) use WASM_BIGINT");case"float":return LE_HEAP_LOAD_F32((r>>2)*4);case"double":return LE_HEAP_LOAD_F64((r>>3)*8);case"*":return LE_HEAP_LOAD_U32((r>>2)*4);default:abort(`invalid type for getValue: ${e}`)}}var newDSO=(r,e,t)=>{var n={refcount:1/0,name:r,exports:t,global:!0};return LDSO.loadedLibsByName[r]=n,e!=null&&(LDSO.loadedLibsByHandle[e]=n),n},LDSO={loadedLibsByName:{},loadedLibsByHandle:{},init(){newDSO("__main__",0,wasmImports)}},___heap_base=78112,zeroMemory=(r,e)=>(HEAPU8.fill(0,r,r+e),r),alignMemory=(r,e)=>Math.ceil(r/e)*e,getMemory=r=>{if(runtimeInitialized)return zeroMemory(_malloc(r),r);var e=___heap_base,t=e+alignMemory(r,16);return ___heap_base=t,GOT.__heap_base.value=t,e},isInternalSym=r=>["__cpp_exception","__c_longjmp","__wasm_apply_data_relocs","__dso_handle","__tls_size","__tls_align","__set_stack_limits","_emscripten_tls_init","__wasm_init_tls","__wasm_call_ctors","__start_em_asm","__stop_em_asm","__start_em_js","__stop_em_js"].includes(r)||r.startsWith("__em_js__"),uleb128Encode=(r,e)=>{r<128?e.push(r):e.push(r%128|128,r>>7)},sigToWasmTypes=r=>{for(var e={i:"i32",j:"i64",f:"f32",d:"f64",e:"externref",p:"i32"},t={parameters:[],results:r[0]=="v"?[]:[e[r[0]]]},n=1;n<r.length;++n)t.parameters.push(e[r[n]]);return t},generateFuncType=(r,e)=>{var t=r.slice(0,1),n=r.slice(1),s={i:127,p:127,j:126,f:125,d:124,e:111};e.push(96),uleb128Encode(n.length,e);for(var o=0;o<n.length;++o)e.push(s[n[o]]);t=="v"?e.push(0):e.push(1,s[t])},convertJsFunctionToWasm=(r,e)=>{if(typeof WebAssembly.Function=="function")return new WebAssembly.Function(sigToWasmTypes(e),r);var t=[1];generateFuncType(e,t);var n=[0,97,115,109,1,0,0,0,1];uleb128Encode(t.length,n),n.push(...t),n.push(2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0);var s=new WebAssembly.Module(new Uint8Array(n)),o=new WebAssembly.Instance(s,{e:{f:r}}),a=o.exports.f;return a},wasmTableMirror=[],wasmTable=new WebAssembly.Table({initial:28,element:"anyfunc"}),getWasmTableEntry=r=>{var e=wasmTableMirror[r];return e||(r>=wasmTableMirror.length&&(wasmTableMirror.length=r+1),wasmTableMirror[r]=e=wasmTable.get(r)),e},updateTableMap=(r,e)=>{if(functionsInTableMap)for(var t=r;t<r+e;t++){var n=getWasmTableEntry(t);n&&functionsInTableMap.set(n,t)}},functionsInTableMap,getFunctionAddress=r=>(functionsInTableMap||(functionsInTableMap=new WeakMap,updateTableMap(0,wasmTable.length)),functionsInTableMap.get(r)||0),freeTableIndexes=[],getEmptyTableSlot=()=>{if(freeTableIndexes.length)return freeTableIndexes.pop();try{wasmTable.grow(1)}catch(r){throw r instanceof RangeError?"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.":r}return wasmTable.length-1},setWasmTableEntry=(r,e)=>{wasmTable.set(r,e),wasmTableMirror[r]=wasmTable.get(r)},addFunction=(r,e)=>{var t=getFunctionAddress(r);if(t)return t;var n=getEmptyTableSlot();try{setWasmTableEntry(n,r)}catch(o){if(!(o instanceof TypeError))throw o;var s=convertJsFunctionToWasm(r,e);setWasmTableEntry(n,s)}return functionsInTableMap.set(r,n),n},updateGOT=(r,e)=>{for(var t in r)if(!isInternalSym(t)){var n=r[t];t.startsWith("orig$")&&(t=t.split("$")[1],e=!0),GOT[t]||=new WebAssembly.Global({value:"i32",mutable:!0}),(e||GOT[t].value==0)&&(typeof n=="function"?GOT[t].value=addFunction(n):typeof n=="number"?GOT[t].value=n:err(`unhandled export type for '${t}': ${typeof n}`))}},relocateExports=(r,e,t)=>{var n={};for(var s in r){var o=r[s];typeof o=="object"&&(o=o.value),typeof o=="number"&&(o+=e),n[s]=o}return updateGOT(n,t),n},isSymbolDefined=r=>{var e=wasmImports[r];return!(!e||e.stub)},dynCallLegacy=(r,e,t)=>{r=r.replace(/p/g,"i");var n=Module["dynCall_"+r];return n(e,...t)},dynCall=(r,e,t=[])=>{if(r.includes("j"))return dynCallLegacy(r,e,t);var n=getWasmTableEntry(e)(...t);return n},stackSave=()=>_emscripten_stack_get_current(),stackRestore=r=>__emscripten_stack_restore(r),createInvokeFunction=r=>(e,...t)=>{var n=stackSave();try{return dynCall(r,e,t)}catch(s){if(stackRestore(n),s!==s+0)throw s;_setThrew(1,0)}},resolveGlobalSymbol=(r,e=!1)=>{var t;return e&&"orig$"+r in wasmImports&&(r="orig$"+r),isSymbolDefined(r)?t=wasmImports[r]:r.startsWith("invoke_")&&(t=wasmImports[r]=createInvokeFunction(r.split("_")[1])),{sym:t,name:r}},UTF8ToString=(r,e)=>r?UTF8ArrayToString(HEAPU8,r,e):"",loadWebAssemblyModule=(binary,flags,libName,localScope,handle)=>{var metadata=getDylinkMetadata(binary);currentModuleWeakSymbols=metadata.weakImports;function loadModule(){var firstLoad=!handle||!HEAP8[handle+8];if(firstLoad){var memAlign=Math.pow(2,metadata.memoryAlign),memoryBase=metadata.memorySize?alignMemory(getMemory(metadata.memorySize+memAlign),memAlign):0,tableBase=metadata.tableSize?wasmTable.length:0;handle&&(HEAP8[handle+8]=1,LE_HEAP_STORE_U32((handle+12>>2)*4,memoryBase),LE_HEAP_STORE_I32((handle+16>>2)*4,metadata.memorySize),LE_HEAP_STORE_U32((handle+20>>2)*4,tableBase),LE_HEAP_STORE_I32((handle+24>>2)*4,metadata.tableSize))}else memoryBase=LE_HEAP_LOAD_U32((handle+12>>2)*4),tableBase=LE_HEAP_LOAD_U32((handle+20>>2)*4);var tableGrowthNeeded=tableBase+metadata.tableSize-wasmTable.length;tableGrowthNeeded>0&&wasmTable.grow(tableGrowthNeeded);var moduleExports;function resolveSymbol(r){var e=resolveGlobalSymbol(r).sym;return!e&&localScope&&(e=localScope[r]),e||(e=moduleExports[r]),e}var proxyHandler={get(r,e){switch(e){case"__memory_base":return memoryBase;case"__table_base":return tableBase}if(e in wasmImports&&!wasmImports[e].stub)return wasmImports[e];if(!(e in r)){var t;r[e]=(...n)=>(t||=resolveSymbol(e),t(...n))}return r[e]}},proxy=new Proxy({},proxyHandler),info={"GOT.mem":new Proxy({},GOTHandler),"GOT.func":new Proxy({},GOTHandler),env:proxy,wasi_snapshot_preview1:proxy};function postInstantiation(module,instance){updateTableMap(tableBase,metadata.tableSize),moduleExports=relocateExports(instance.exports,memoryBase),flags.allowUndefined||reportUndefinedSymbols();function addEmAsm(addr,body){for(var args=[],arity=0;arity<16&&body.indexOf("$"+arity)!=-1;arity++)args.push("$"+arity);args=args.join(",");var func=`(${args}) => { ${body} };`;ASM_CONSTS[start]=eval(func)}if("__start_em_asm"in moduleExports)for(var start=moduleExports.__start_em_asm,stop=moduleExports.__stop_em_asm;start<stop;){var jsString=UTF8ToString(start);addEmAsm(start,jsString),start=HEAPU8.indexOf(0,start)+1}function addEmJs(name,cSig,body){var jsArgs=[];if(cSig=cSig.slice(1,-1),cSig!="void"){cSig=cSig.split(",");for(var i in cSig){var jsArg=cSig[i].split(" ").pop();jsArgs.push(jsArg.replace("*",""))}}var func=`(${jsArgs}) => ${body};`;moduleExports[name]=eval(func)}for(var name in moduleExports)if(name.startsWith("__em_js__")){var start=moduleExports[name],jsString=UTF8ToString(start),parts=jsString.split("<::>");addEmJs(name.replace("__em_js__",""),parts[0],parts[1]),delete moduleExports[name]}var applyRelocs=moduleExports.__wasm_apply_data_relocs;applyRelocs&&(runtimeInitialized?applyRelocs():__RELOC_FUNCS__.push(applyRelocs));var init=moduleExports.__wasm_call_ctors;return init&&(runtimeInitialized?init():__ATINIT__.push(init)),moduleExports}if(flags.loadAsync){if(binary instanceof WebAssembly.Module){var instance=new WebAssembly.Instance(binary,info);return Promise.resolve(postInstantiation(binary,instance))}return WebAssembly.instantiate(binary,info).then(r=>postInstantiation(r.module,r.instance))}var module=binary instanceof WebAssembly.Module?binary:new WebAssembly.Module(binary),instance=new WebAssembly.Instance(module,info);return postInstantiation(module,instance)}return flags.loadAsync?metadata.neededDynlibs.reduce((r,e)=>r.then(()=>loadDynamicLibrary(e,flags,localScope)),Promise.resolve()).then(loadModule):(metadata.neededDynlibs.forEach(r=>loadDynamicLibrary(r,flags,localScope)),loadModule())},mergeLibSymbols=(r,e)=>{for(var[t,n]of Object.entries(r)){let s=a=>{isSymbolDefined(a)||(wasmImports[a]=n)};s(t);let o="__main_argc_argv";t=="main"&&s(o),t==o&&s("main"),t.startsWith("dynCall_")&&!Module.hasOwnProperty(t)&&(Module[t]=n)}},asyncLoad=(r,e,t,n)=>{var s=n?"":`al ${r}`;readAsync(r).then(o=>{e(new Uint8Array(o)),s&&removeRunDependency(s)},o=>{if(t)t();else throw`Loading data file "${r}" failed.`}),s&&addRunDependency(s)};function loadDynamicLibrary(r,e={global:!0,nodelete:!0},t,n){var s=LDSO.loadedLibsByName[r];if(s)return e.global?s.global||(s.global=!0,mergeLibSymbols(s.exports,r)):t&&Object.assign(t,s.exports),e.nodelete&&s.refcount!==1/0&&(s.refcount=1/0),s.refcount++,n&&(LDSO.loadedLibsByHandle[n]=s),e.loadAsync?Promise.resolve(!0):!0;s=newDSO(r,n,"loading"),s.refcount=e.nodelete?1/0:1,s.global=e.global;function o(){if(n){var c=LE_HEAP_LOAD_U32((n+28>>2)*4),u=LE_HEAP_LOAD_U32((n+32>>2)*4);if(c&&u){var h=HEAP8.slice(c,c+u);return e.loadAsync?Promise.resolve(h):h}}var d=locateFile(r);if(e.loadAsync)return new Promise(function(f,p){asyncLoad(d,f,p)});if(!readBinary)throw new Error(`${d}: file not found, and synchronous loading of external files is not available`);return readBinary(d)}function a(){return e.loadAsync?o().then(c=>loadWebAssemblyModule(c,e,r,t,n)):loadWebAssemblyModule(o(),e,r,t,n)}function l(c){s.global?mergeLibSymbols(c,r):t&&Object.assign(t,c),s.exports=c}return e.loadAsync?a().then(c=>(l(c),!0)):(l(a()),!0)}var reportUndefinedSymbols=()=>{for(var[r,e]of Object.entries(GOT))if(e.value==0){var t=resolveGlobalSymbol(r,!0).sym;if(!t&&!e.required)continue;if(typeof t=="function")e.value=addFunction(t,t.sig);else if(typeof t=="number")e.value=t;else throw new Error(`bad export type for '${r}': ${typeof t}`)}},loadDylibs=()=>{if(!dynamicLibraries.length){reportUndefinedSymbols();return}addRunDependency("loadDylibs"),dynamicLibraries.reduce((r,e)=>r.then(()=>loadDynamicLibrary(e,{loadAsync:!0,global:!0,nodelete:!0,allowUndefined:!0})),Promise.resolve()).then(()=>{reportUndefinedSymbols(),removeRunDependency("loadDylibs")})},noExitRuntime=Module.noExitRuntime||!0;function setValue(r,e,t="i8"){switch(t.endsWith("*")&&(t="*"),t){case"i1":HEAP8[r]=e;break;case"i8":HEAP8[r]=e;break;case"i16":LE_HEAP_STORE_I16((r>>1)*2,e);break;case"i32":LE_HEAP_STORE_I32((r>>2)*4,e);break;case"i64":abort("to do setValue(i64) use WASM_BIGINT");case"float":LE_HEAP_STORE_F32((r>>2)*4,e);break;case"double":LE_HEAP_STORE_F64((r>>3)*8,e);break;case"*":LE_HEAP_STORE_U32((r>>2)*4,e);break;default:abort(`invalid type for setValue: ${t}`)}}var ___memory_base=new WebAssembly.Global({value:"i32",mutable:!1},1024),___stack_pointer=new WebAssembly.Global({value:"i32",mutable:!0},78112),___table_base=new WebAssembly.Global({value:"i32",mutable:!1},1),__abort_js=()=>{abort("")};__abort_js.sig="v";var nowIsMonotonic=1,__emscripten_get_now_is_monotonic=()=>nowIsMonotonic;__emscripten_get_now_is_monotonic.sig="i";var __emscripten_memcpy_js=(r,e,t)=>HEAPU8.copyWithin(r,e,e+t);__emscripten_memcpy_js.sig="vppp";var _emscripten_date_now=()=>Date.now();_emscripten_date_now.sig="d";var _emscripten_get_now;_emscripten_get_now=()=>performance.now(),_emscripten_get_now.sig="d";var getHeapMax=()=>2147483648,growMemory=r=>{var e=wasmMemory.buffer,t=(r-e.byteLength+65535)/65536;try{return wasmMemory.grow(t),updateMemoryViews(),1}catch{}},_emscripten_resize_heap=r=>{var e=HEAPU8.length;r>>>=0;var t=getHeapMax();if(r>t)return!1;for(var n=(c,u)=>c+(u-c%u)%u,s=1;s<=4;s*=2){var o=e*(1+.2/s);o=Math.min(o,r+100663296);var a=Math.min(t,n(Math.max(r,o),65536)),l=growMemory(a);if(l)return!0}return!1};_emscripten_resize_heap.sig="ip";var _fd_close=r=>52;_fd_close.sig="ii";var convertI32PairToI53Checked=(r,e)=>e+2097152>>>0<4194305-!!r?(r>>>0)+e*4294967296:NaN;function _fd_seek(r,e,t,n,s){var o=convertI32PairToI53Checked(e,t);return 70}_fd_seek.sig="iiiiip";var printCharBuffers=[null,[],[]],printChar=(r,e)=>{var t=printCharBuffers[r];e===0||e===10?((r===1?out:err)(UTF8ArrayToString(t,0)),t.length=0):t.push(e)},_fd_write=(r,e,t,n)=>{for(var s=0,o=0;o<t;o++){var a=LE_HEAP_LOAD_U32((e>>2)*4),l=LE_HEAP_LOAD_U32((e+4>>2)*4);e+=8;for(var c=0;c<l;c++)printChar(r,HEAPU8[a+c]);s+=l}return LE_HEAP_STORE_U32((n>>2)*4,s),0};_fd_write.sig="iippp";function _tree_sitter_log_callback(r,e){if(currentLogCallback){let t=UTF8ToString(e);currentLogCallback(t,r!==0)}}function _tree_sitter_parse_callback(r,e,t,n,s){let a=currentParseCallback(e,{row:t,column:n});typeof a=="string"?(setValue(s,a.length,"i32"),stringToUTF16(a,r,10240)):setValue(s,0,"i32")}var runtimeKeepaliveCounter=0,keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0,_proc_exit=r=>{EXITSTATUS=r,keepRuntimeAlive()||(Module.onExit?.(r),ABORT=!0),quit_(r,new ExitStatus(r))};_proc_exit.sig="vi";var exitJS=(r,e)=>{EXITSTATUS=r,_proc_exit(r)},handleException=r=>{if(r instanceof ExitStatus||r=="unwind")return EXITSTATUS;quit_(1,r)},lengthBytesUTF8=r=>{for(var e=0,t=0;t<r.length;++t){var n=r.charCodeAt(t);n<=127?e++:n<=2047?e+=2:n>=55296&&n<=57343?(e+=4,++t):e+=3}return e},stringToUTF8Array=(r,e,t,n)=>{if(!(n>0))return 0;for(var s=t,o=t+n-1,a=0;a<r.length;++a){var l=r.charCodeAt(a);if(l>=55296&&l<=57343){var c=r.charCodeAt(++a);l=65536+((l&1023)<<10)|c&1023}if(l<=127){if(t>=o)break;e[t++]=l}else if(l<=2047){if(t+1>=o)break;e[t++]=192|l>>6,e[t++]=128|l&63}else if(l<=65535){if(t+2>=o)break;e[t++]=224|l>>12,e[t++]=128|l>>6&63,e[t++]=128|l&63}else{if(t+3>=o)break;e[t++]=240|l>>18,e[t++]=128|l>>12&63,e[t++]=128|l>>6&63,e[t++]=128|l&63}}return e[t]=0,t-s},stringToUTF8=(r,e,t)=>stringToUTF8Array(r,HEAPU8,e,t),stackAlloc=r=>__emscripten_stack_alloc(r),stringToUTF8OnStack=r=>{var e=lengthBytesUTF8(r)+1,t=stackAlloc(e);return stringToUTF8(r,t,e),t},stringToUTF16=(r,e,t)=>{if(t??=2147483647,t<2)return 0;t-=2;for(var n=e,s=t<r.length*2?t/2:r.length,o=0;o<s;++o){var a=r.charCodeAt(o);LE_HEAP_STORE_I16((e>>1)*2,a),e+=2}return LE_HEAP_STORE_I16((e>>1)*2,0),e-n},AsciiToString=r=>{for(var e="";;){var t=HEAPU8[r++];if(!t)return e;e+=String.fromCharCode(t)}},wasmImports={__heap_base:___heap_base,__indirect_function_table:wasmTable,__memory_base:___memory_base,__stack_pointer:___stack_pointer,__table_base:___table_base,_abort_js:__abort_js,_emscripten_get_now_is_monotonic:__emscripten_get_now_is_monotonic,_emscripten_memcpy_js:__emscripten_memcpy_js,emscripten_get_now:_emscripten_get_now,emscripten_resize_heap:_emscripten_resize_heap,fd_close:_fd_close,fd_seek:_fd_seek,fd_write:_fd_write,memory:wasmMemory,tree_sitter_log_callback:_tree_sitter_log_callback,tree_sitter_parse_callback:_tree_sitter_parse_callback},wasmExports=createWasm(),___wasm_call_ctors=()=>(___wasm_call_ctors=wasmExports.__wasm_call_ctors)(),___wasm_apply_data_relocs=()=>(___wasm_apply_data_relocs=wasmExports.__wasm_apply_data_relocs)(),_malloc=Module._malloc=r=>(_malloc=Module._malloc=wasmExports.malloc)(r),_calloc=Module._calloc=(r,e)=>(_calloc=Module._calloc=wasmExports.calloc)(r,e),_realloc=Module._realloc=(r,e)=>(_realloc=Module._realloc=wasmExports.realloc)(r,e),_free=Module._free=r=>(_free=Module._free=wasmExports.free)(r),_ts_language_symbol_count=Module._ts_language_symbol_count=r=>(_ts_language_symbol_count=Module._ts_language_symbol_count=wasmExports.ts_language_symbol_count)(r),_ts_language_state_count=Module._ts_language_state_count=r=>(_ts_language_state_count=Module._ts_language_state_count=wasmExports.ts_language_state_count)(r),_ts_language_version=Module._ts_language_version=r=>(_ts_language_version=Module._ts_language_version=wasmExports.ts_language_version)(r),_ts_language_field_count=Module._ts_language_field_count=r=>(_ts_language_field_count=Module._ts_language_field_count=wasmExports.ts_language_field_count)(r),_ts_language_next_state=Module._ts_language_next_state=(r,e,t)=>(_ts_language_next_state=Module._ts_language_next_state=wasmExports.ts_language_next_state)(r,e,t),_ts_language_symbol_name=Module._ts_language_symbol_name=(r,e)=>(_ts_language_symbol_name=Module._ts_language_symbol_name=wasmExports.ts_language_symbol_name)(r,e),_ts_language_symbol_for_name=Module._ts_language_symbol_for_name=(r,e,t,n)=>(_ts_language_symbol_for_name=Module._ts_language_symbol_for_name=wasmExports.ts_language_symbol_for_name)(r,e,t,n),_strncmp=Module._strncmp=(r,e,t)=>(_strncmp=Module._strncmp=wasmExports.strncmp)(r,e,t),_ts_language_symbol_type=Module._ts_language_symbol_type=(r,e)=>(_ts_language_symbol_type=Module._ts_language_symbol_type=wasmExports.ts_language_symbol_type)(r,e),_ts_language_field_name_for_id=Module._ts_language_field_name_for_id=(r,e)=>(_ts_language_field_name_for_id=Module._ts_language_field_name_for_id=wasmExports.ts_language_field_name_for_id)(r,e),_ts_lookahead_iterator_new=Module._ts_lookahead_iterator_new=(r,e)=>(_ts_lookahead_iterator_new=Module._ts_lookahead_iterator_new=wasmExports.ts_lookahead_iterator_new)(r,e),_ts_lookahead_iterator_delete=Module._ts_lookahead_iterator_delete=r=>(_ts_lookahead_iterator_delete=Module._ts_lookahead_iterator_delete=wasmExports.ts_lookahead_iterator_delete)(r),_ts_lookahead_iterator_reset_state=Module._ts_lookahead_iterator_reset_state=(r,e)=>(_ts_lookahead_iterator_reset_state=Module._ts_lookahead_iterator_reset_state=wasmExports.ts_lookahead_iterator_reset_state)(r,e),_ts_lookahead_iterator_reset=Module._ts_lookahead_iterator_reset=(r,e,t)=>(_ts_lookahead_iterator_reset=Module._ts_lookahead_iterator_reset=wasmExports.ts_lookahead_iterator_reset)(r,e,t),_ts_lookahead_iterator_next=Module._ts_lookahead_iterator_next=r=>(_ts_lookahead_iterator_next=Module._ts_lookahead_iterator_next=wasmExports.ts_lookahead_iterator_next)(r),_ts_lookahead_iterator_current_symbol=Module._ts_lookahead_iterator_current_symbol=r=>(_ts_lookahead_iterator_current_symbol=Module._ts_lookahead_iterator_current_symbol=wasmExports.ts_lookahead_iterator_current_symbol)(r),_memset=Module._memset=(r,e,t)=>(_memset=Module._memset=wasmExports.memset)(r,e,t),_memcpy=Module._memcpy=(r,e,t)=>(_memcpy=Module._memcpy=wasmExports.memcpy)(r,e,t),_ts_parser_delete=Module._ts_parser_delete=r=>(_ts_parser_delete=Module._ts_parser_delete=wasmExports.ts_parser_delete)(r),_ts_parser_reset=Module._ts_parser_reset=r=>(_ts_parser_reset=Module._ts_parser_reset=wasmExports.ts_parser_reset)(r),_ts_parser_set_language=Module._ts_parser_set_language=(r,e)=>(_ts_parser_set_language=Module._ts_parser_set_language=wasmExports.ts_parser_set_language)(r,e),_ts_parser_timeout_micros=Module._ts_parser_timeout_micros=r=>(_ts_parser_timeout_micros=Module._ts_parser_timeout_micros=wasmExports.ts_parser_timeout_micros)(r),_ts_parser_set_timeout_micros=Module._ts_parser_set_timeout_micros=(r,e,t)=>(_ts_parser_set_timeout_micros=Module._ts_parser_set_timeout_micros=wasmExports.ts_parser_set_timeout_micros)(r,e,t),_ts_parser_set_included_ranges=Module._ts_parser_set_included_ranges=(r,e,t)=>(_ts_parser_set_included_ranges=Module._ts_parser_set_included_ranges=wasmExports.ts_parser_set_included_ranges)(r,e,t),_memmove=Module._memmove=(r,e,t)=>(_memmove=Module._memmove=wasmExports.memmove)(r,e,t),_memcmp=Module._memcmp=(r,e,t)=>(_memcmp=Module._memcmp=wasmExports.memcmp)(r,e,t),_ts_query_new=Module._ts_query_new=(r,e,t,n,s)=>(_ts_query_new=Module._ts_query_new=wasmExports.ts_query_new)(r,e,t,n,s),_ts_query_delete=Module._ts_query_delete=r=>(_ts_query_delete=Module._ts_query_delete=wasmExports.ts_query_delete)(r),_iswspace=Module._iswspace=r=>(_iswspace=Module._iswspace=wasmExports.iswspace)(r),_iswalnum=Module._iswalnum=r=>(_iswalnum=Module._iswalnum=wasmExports.iswalnum)(r),_ts_query_pattern_count=Module._ts_query_pattern_count=r=>(_ts_query_pattern_count=Module._ts_query_pattern_count=wasmExports.ts_query_pattern_count)(r),_ts_query_capture_count=Module._ts_query_capture_count=r=>(_ts_query_capture_count=Module._ts_query_capture_count=wasmExports.ts_query_capture_count)(r),_ts_query_string_count=Module._ts_query_string_count=r=>(_ts_query_string_count=Module._ts_query_string_count=wasmExports.ts_query_string_count)(r),_ts_query_capture_name_for_id=Module._ts_query_capture_name_for_id=(r,e,t)=>(_ts_query_capture_name_for_id=Module._ts_query_capture_name_for_id=wasmExports.ts_query_capture_name_for_id)(r,e,t),_ts_query_string_value_for_id=Module._ts_query_string_value_for_id=(r,e,t)=>(_ts_query_string_value_for_id=Module._ts_query_string_value_for_id=wasmExports.ts_query_string_value_for_id)(r,e,t),_ts_query_predicates_for_pattern=Module._ts_query_predicates_for_pattern=(r,e,t)=>(_ts_query_predicates_for_pattern=Module._ts_query_predicates_for_pattern=wasmExports.ts_query_predicates_for_pattern)(r,e,t),_ts_query_disable_capture=Module._ts_query_disable_capture=(r,e,t)=>(_ts_query_disable_capture=Module._ts_query_disable_capture=wasmExports.ts_query_disable_capture)(r,e,t),_ts_tree_copy=Module._ts_tree_copy=r=>(_ts_tree_copy=Module._ts_tree_copy=wasmExports.ts_tree_copy)(r),_ts_tree_delete=Module._ts_tree_delete=r=>(_ts_tree_delete=Module._ts_tree_delete=wasmExports.ts_tree_delete)(r),_ts_init=Module._ts_init=()=>(_ts_init=Module._ts_init=wasmExports.ts_init)(),_ts_parser_new_wasm=Module._ts_parser_new_wasm=()=>(_ts_parser_new_wasm=Module._ts_parser_new_wasm=wasmExports.ts_parser_new_wasm)(),_ts_parser_enable_logger_wasm=Module._ts_parser_enable_logger_wasm=(r,e)=>(_ts_parser_enable_logger_wasm=Module._ts_parser_enable_logger_wasm=wasmExports.ts_parser_enable_logger_wasm)(r,e),_ts_parser_parse_wasm=Module._ts_parser_parse_wasm=(r,e,t,n,s)=>(_ts_parser_parse_wasm=Module._ts_parser_parse_wasm=wasmExports.ts_parser_parse_wasm)(r,e,t,n,s),_ts_parser_included_ranges_wasm=Module._ts_parser_included_ranges_wasm=r=>(_ts_parser_included_ranges_wasm=Module._ts_parser_included_ranges_wasm=wasmExports.ts_parser_included_ranges_wasm)(r),_ts_language_type_is_named_wasm=Module._ts_language_type_is_named_wasm=(r,e)=>(_ts_language_type_is_named_wasm=Module._ts_language_type_is_named_wasm=wasmExports.ts_language_type_is_named_wasm)(r,e),_ts_language_type_is_visible_wasm=Module._ts_language_type_is_visible_wasm=(r,e)=>(_ts_language_type_is_visible_wasm=Module._ts_language_type_is_visible_wasm=wasmExports.ts_language_type_is_visible_wasm)(r,e),_ts_tree_root_node_wasm=Module._ts_tree_root_node_wasm=r=>(_ts_tree_root_node_wasm=Module._ts_tree_root_node_wasm=wasmExports.ts_tree_root_node_wasm)(r),_ts_tree_root_node_with_offset_wasm=Module._ts_tree_root_node_with_offset_wasm=r=>(_ts_tree_root_node_with_offset_wasm=Module._ts_tree_root_node_with_offset_wasm=wasmExports.ts_tree_root_node_with_offset_wasm)(r),_ts_tree_edit_wasm=Module._ts_tree_edit_wasm=r=>(_ts_tree_edit_wasm=Module._ts_tree_edit_wasm=wasmExports.ts_tree_edit_wasm)(r),_ts_tree_included_ranges_wasm=Module._ts_tree_included_ranges_wasm=r=>(_ts_tree_included_ranges_wasm=Module._ts_tree_included_ranges_wasm=wasmExports.ts_tree_included_ranges_wasm)(r),_ts_tree_get_changed_ranges_wasm=Module._ts_tree_get_changed_ranges_wasm=(r,e)=>(_ts_tree_get_changed_ranges_wasm=Module._ts_tree_get_changed_ranges_wasm=wasmExports.ts_tree_get_changed_ranges_wasm)(r,e),_ts_tree_cursor_new_wasm=Module._ts_tree_cursor_new_wasm=r=>(_ts_tree_cursor_new_wasm=Module._ts_tree_cursor_new_wasm=wasmExports.ts_tree_cursor_new_wasm)(r),_ts_tree_cursor_delete_wasm=Module._ts_tree_cursor_delete_wasm=r=>(_ts_tree_cursor_delete_wasm=Module._ts_tree_cursor_delete_wasm=wasmExports.ts_tree_cursor_delete_wasm)(r),_ts_tree_cursor_reset_wasm=Module._ts_tree_cursor_reset_wasm=r=>(_ts_tree_cursor_reset_wasm=Module._ts_tree_cursor_reset_wasm=wasmExports.ts_tree_cursor_reset_wasm)(r),_ts_tree_cursor_reset_to_wasm=Module._ts_tree_cursor_reset_to_wasm=(r,e)=>(_ts_tree_cursor_reset_to_wasm=Module._ts_tree_cursor_reset_to_wasm=wasmExports.ts_tree_cursor_reset_to_wasm)(r,e),_ts_tree_cursor_goto_first_child_wasm=Module._ts_tree_cursor_goto_first_child_wasm=r=>(_ts_tree_cursor_goto_first_child_wasm=Module._ts_tree_cursor_goto_first_child_wasm=wasmExports.ts_tree_cursor_goto_first_child_wasm)(r),_ts_tree_cursor_goto_last_child_wasm=Module._ts_tree_cursor_goto_last_child_wasm=r=>(_ts_tree_cursor_goto_last_child_wasm=Module._ts_tree_cursor_goto_last_child_wasm=wasmExports.ts_tree_cursor_goto_last_child_wasm)(r),_ts_tree_cursor_goto_first_child_for_index_wasm=Module._ts_tree_cursor_goto_first_child_for_index_wasm=r=>(_ts_tree_cursor_goto_first_child_for_index_wasm=Module._ts_tree_cursor_goto_first_child_for_index_wasm=wasmExports.ts_tree_cursor_goto_first_child_for_index_wasm)(r),_ts_tree_cursor_goto_first_child_for_position_wasm=Module._ts_tree_cursor_goto_first_child_for_position_wasm=r=>(_ts_tree_cursor_goto_first_child_for_position_wasm=Module._ts_tree_cursor_goto_first_child_for_position_wasm=wasmExports.ts_tree_cursor_goto_first_child_for_position_wasm)(r),_ts_tree_cursor_goto_next_sibling_wasm=Module._ts_tree_cursor_goto_next_sibling_wasm=r=>(_ts_tree_cursor_goto_next_sibling_wasm=Module._ts_tree_cursor_goto_next_sibling_wasm=wasmExports.ts_tree_cursor_goto_next_sibling_wasm)(r),_ts_tree_cursor_goto_previous_sibling_wasm=Module._ts_tree_cursor_goto_previous_sibling_wasm=r=>(_ts_tree_cursor_goto_previous_sibling_wasm=Module._ts_tree_cursor_goto_previous_sibling_wasm=wasmExports.ts_tree_cursor_goto_previous_sibling_wasm)(r),_ts_tree_cursor_goto_descendant_wasm=Module._ts_tree_cursor_goto_descendant_wasm=(r,e)=>(_ts_tree_cursor_goto_descendant_wasm=Module._ts_tree_cursor_goto_descendant_wasm=wasmExports.ts_tree_cursor_goto_descendant_wasm)(r,e),_ts_tree_cursor_goto_parent_wasm=Module._ts_tree_cursor_goto_parent_wasm=r=>(_ts_tree_cursor_goto_parent_wasm=Module._ts_tree_cursor_goto_parent_wasm=wasmExports.ts_tree_cursor_goto_parent_wasm)(r),_ts_tree_cursor_current_node_type_id_wasm=Module._ts_tree_cursor_current_node_type_id_wasm=r=>(_ts_tree_cursor_current_node_type_id_wasm=Module._ts_tree_cursor_current_node_type_id_wasm=wasmExports.ts_tree_cursor_current_node_type_id_wasm)(r),_ts_tree_cursor_current_node_state_id_wasm=Module._ts_tree_cursor_current_node_state_id_wasm=r=>(_ts_tree_cursor_current_node_state_id_wasm=Module._ts_tree_cursor_current_node_state_id_wasm=wasmExports.ts_tree_cursor_current_node_state_id_wasm)(r),_ts_tree_cursor_current_node_is_named_wasm=Module._ts_tree_cursor_current_node_is_named_wasm=r=>(_ts_tree_cursor_current_node_is_named_wasm=Module._ts_tree_cursor_current_node_is_named_wasm=wasmExports.ts_tree_cursor_current_node_is_named_wasm)(r),_ts_tree_cursor_current_node_is_missing_wasm=Module._ts_tree_cursor_current_node_is_missing_wasm=r=>(_ts_tree_cursor_current_node_is_missing_wasm=Module._ts_tree_cursor_current_node_is_missing_wasm=wasmExports.ts_tree_cursor_current_node_is_missing_wasm)(r),_ts_tree_cursor_current_node_id_wasm=Module._ts_tree_cursor_current_node_id_wasm=r=>(_ts_tree_cursor_current_node_id_wasm=Module._ts_tree_cursor_current_node_id_wasm=wasmExports.ts_tree_cursor_current_node_id_wasm)(r),_ts_tree_cursor_start_position_wasm=Module._ts_tree_cursor_start_position_wasm=r=>(_ts_tree_cursor_start_position_wasm=Module._ts_tree_cursor_start_position_wasm=wasmExports.ts_tree_cursor_start_position_wasm)(r),_ts_tree_cursor_end_position_wasm=Module._ts_tree_cursor_end_position_wasm=r=>(_ts_tree_cursor_end_position_wasm=Module._ts_tree_cursor_end_position_wasm=wasmExports.ts_tree_cursor_end_position_wasm)(r),_ts_tree_cursor_start_index_wasm=Module._ts_tree_cursor_start_index_wasm=r=>(_ts_tree_cursor_start_index_wasm=Module._ts_tree_cursor_start_index_wasm=wasmExports.ts_tree_cursor_start_index_wasm)(r),_ts_tree_cursor_end_index_wasm=Module._ts_tree_cursor_end_index_wasm=r=>(_ts_tree_cursor_end_index_wasm=Module._ts_tree_cursor_end_index_wasm=wasmExports.ts_tree_cursor_end_index_wasm)(r),_ts_tree_cursor_current_field_id_wasm=Module._ts_tree_cursor_current_field_id_wasm=r=>(_ts_tree_cursor_current_field_id_wasm=Module._ts_tree_cursor_current_field_id_wasm=wasmExports.ts_tree_cursor_current_field_id_wasm)(r),_ts_tree_cursor_current_depth_wasm=Module._ts_tree_cursor_current_depth_wasm=r=>(_ts_tree_cursor_current_depth_wasm=Module._ts_tree_cursor_current_depth_wasm=wasmExports.ts_tree_cursor_current_depth_wasm)(r),_ts_tree_cursor_current_descendant_index_wasm=Module._ts_tree_cursor_current_descendant_index_wasm=r=>(_ts_tree_cursor_current_descendant_index_wasm=Module._ts_tree_cursor_current_descendant_index_wasm=wasmExports.ts_tree_cursor_current_descendant_index_wasm)(r),_ts_tree_cursor_current_node_wasm=Module._ts_tree_cursor_current_node_wasm=r=>(_ts_tree_cursor_current_node_wasm=Module._ts_tree_cursor_current_node_wasm=wasmExports.ts_tree_cursor_current_node_wasm)(r),_ts_node_symbol_wasm=Module._ts_node_symbol_wasm=r=>(_ts_node_symbol_wasm=Module._ts_node_symbol_wasm=wasmExports.ts_node_symbol_wasm)(r),_ts_node_field_name_for_child_wasm=Module._ts_node_field_name_for_child_wasm=(r,e)=>(_ts_node_field_name_for_child_wasm=Module._ts_node_field_name_for_child_wasm=wasmExports.ts_node_field_name_for_child_wasm)(r,e),_ts_node_children_by_field_id_wasm=Module._ts_node_children_by_field_id_wasm=(r,e)=>(_ts_node_children_by_field_id_wasm=Module._ts_node_children_by_field_id_wasm=wasmExports.ts_node_children_by_field_id_wasm)(r,e),_ts_node_first_child_for_byte_wasm=Module._ts_node_first_child_for_byte_wasm=r=>(_ts_node_first_child_for_byte_wasm=Module._ts_node_first_child_for_byte_wasm=wasmExports.ts_node_first_child_for_byte_wasm)(r),_ts_node_first_named_child_for_byte_wasm=Module._ts_node_first_named_child_for_byte_wasm=r=>(_ts_node_first_named_child_for_byte_wasm=Module._ts_node_first_named_child_for_byte_wasm=wasmExports.ts_node_first_named_child_for_byte_wasm)(r),_ts_node_grammar_symbol_wasm=Module._ts_node_grammar_symbol_wasm=r=>(_ts_node_grammar_symbol_wasm=Module._ts_node_grammar_symbol_wasm=wasmExports.ts_node_grammar_symbol_wasm)(r),_ts_node_child_count_wasm=Module._ts_node_child_count_wasm=r=>(_ts_node_child_count_wasm=Module._ts_node_child_count_wasm=wasmExports.ts_node_child_count_wasm)(r),_ts_node_named_child_count_wasm=Module._ts_node_named_child_count_wasm=r=>(_ts_node_named_child_count_wasm=Module._ts_node_named_child_count_wasm=wasmExports.ts_node_named_child_count_wasm)(r),_ts_node_child_wasm=Module._ts_node_child_wasm=(r,e)=>(_ts_node_child_wasm=Module._ts_node_child_wasm=wasmExports.ts_node_child_wasm)(r,e),_ts_node_named_child_wasm=Module._ts_node_named_child_wasm=(r,e)=>(_ts_node_named_child_wasm=Module._ts_node_named_child_wasm=wasmExports.ts_node_named_child_wasm)(r,e),_ts_node_child_by_field_id_wasm=Module._ts_node_child_by_field_id_wasm=(r,e)=>(_ts_node_child_by_field_id_wasm=Module._ts_node_child_by_field_id_wasm=wasmExports.ts_node_child_by_field_id_wasm)(r,e),_ts_node_next_sibling_wasm=Module._ts_node_next_sibling_wasm=r=>(_ts_node_next_sibling_wasm=Module._ts_node_next_sibling_wasm=wasmExports.ts_node_next_sibling_wasm)(r),_ts_node_prev_sibling_wasm=Module._ts_node_prev_sibling_wasm=r=>(_ts_node_prev_sibling_wasm=Module._ts_node_prev_sibling_wasm=wasmExports.ts_node_prev_sibling_wasm)(r),_ts_node_next_named_sibling_wasm=Module._ts_node_next_named_sibling_wasm=r=>(_ts_node_next_named_sibling_wasm=Module._ts_node_next_named_sibling_wasm=wasmExports.ts_node_next_named_sibling_wasm)(r),_ts_node_prev_named_sibling_wasm=Module._ts_node_prev_named_sibling_wasm=r=>(_ts_node_prev_named_sibling_wasm=Module._ts_node_prev_named_sibling_wasm=wasmExports.ts_node_prev_named_sibling_wasm)(r),_ts_node_descendant_count_wasm=Module._ts_node_descendant_count_wasm=r=>(_ts_node_descendant_count_wasm=Module._ts_node_descendant_count_wasm=wasmExports.ts_node_descendant_count_wasm)(r),_ts_node_parent_wasm=Module._ts_node_parent_wasm=r=>(_ts_node_parent_wasm=Module._ts_node_parent_wasm=wasmExports.ts_node_parent_wasm)(r),_ts_node_descendant_for_index_wasm=Module._ts_node_descendant_for_index_wasm=r=>(_ts_node_descendant_for_index_wasm=Module._ts_node_descendant_for_index_wasm=wasmExports.ts_node_descendant_for_index_wasm)(r),_ts_node_named_descendant_for_index_wasm=Module._ts_node_named_descendant_for_index_wasm=r=>(_ts_node_named_descendant_for_index_wasm=Module._ts_node_named_descendant_for_index_wasm=wasmExports.ts_node_named_descendant_for_index_wasm)(r),_ts_node_descendant_for_position_wasm=Module._ts_node_descendant_for_position_wasm=r=>(_ts_node_descendant_for_position_wasm=Module._ts_node_descendant_for_position_wasm=wasmExports.ts_node_descendant_for_position_wasm)(r),_ts_node_named_descendant_for_position_wasm=Module._ts_node_named_descendant_for_position_wasm=r=>(_ts_node_named_descendant_for_position_wasm=Module._ts_node_named_descendant_for_position_wasm=wasmExports.ts_node_named_descendant_for_position_wasm)(r),_ts_node_start_point_wasm=Module._ts_node_start_point_wasm=r=>(_ts_node_start_point_wasm=Module._ts_node_start_point_wasm=wasmExports.ts_node_start_point_wasm)(r),_ts_node_end_point_wasm=Module._ts_node_end_point_wasm=r=>(_ts_node_end_point_wasm=Module._ts_node_end_point_wasm=wasmExports.ts_node_end_point_wasm)(r),_ts_node_start_index_wasm=Module._ts_node_start_index_wasm=r=>(_ts_node_start_index_wasm=Module._ts_node_start_index_wasm=wasmExports.ts_node_start_index_wasm)(r),_ts_node_end_index_wasm=Module._ts_node_end_index_wasm=r=>(_ts_node_end_index_wasm=Module._ts_node_end_index_wasm=wasmExports.ts_node_end_index_wasm)(r),_ts_node_to_string_wasm=Module._ts_node_to_string_wasm=r=>(_ts_node_to_string_wasm=Module._ts_node_to_string_wasm=wasmExports.ts_node_to_string_wasm)(r),_ts_node_children_wasm=Module._ts_node_children_wasm=r=>(_ts_node_children_wasm=Module._ts_node_children_wasm=wasmExports.ts_node_children_wasm)(r),_ts_node_named_children_wasm=Module._ts_node_named_children_wasm=r=>(_ts_node_named_children_wasm=Module._ts_node_named_children_wasm=wasmExports.ts_node_named_children_wasm)(r),_ts_node_descendants_of_type_wasm=Module._ts_node_descendants_of_type_wasm=(r,e,t,n,s,o,a)=>(_ts_node_descendants_of_type_wasm=Module._ts_node_descendants_of_type_wasm=wasmExports.ts_node_descendants_of_type_wasm)(r,e,t,n,s,o,a),_ts_node_is_named_wasm=Module._ts_node_is_named_wasm=r=>(_ts_node_is_named_wasm=Module._ts_node_is_named_wasm=wasmExports.ts_node_is_named_wasm)(r),_ts_node_has_changes_wasm=Module._ts_node_has_changes_wasm=r=>(_ts_node_has_changes_wasm=Module._ts_node_has_changes_wasm=wasmExports.ts_node_has_changes_wasm)(r),_ts_node_has_error_wasm=Module._ts_node_has_error_wasm=r=>(_ts_node_has_error_wasm=Module._ts_node_has_error_wasm=wasmExports.ts_node_has_error_wasm)(r),_ts_node_is_error_wasm=Module._ts_node_is_error_wasm=r=>(_ts_node_is_error_wasm=Module._ts_node_is_error_wasm=wasmExports.ts_node_is_error_wasm)(r),_ts_node_is_missing_wasm=Module._ts_node_is_missing_wasm=r=>(_ts_node_is_missing_wasm=Module._ts_node_is_missing_wasm=wasmExports.ts_node_is_missing_wasm)(r),_ts_node_is_extra_wasm=Module._ts_node_is_extra_wasm=r=>(_ts_node_is_extra_wasm=Module._ts_node_is_extra_wasm=wasmExports.ts_node_is_extra_wasm)(r),_ts_node_parse_state_wasm=Module._ts_node_parse_state_wasm=r=>(_ts_node_parse_state_wasm=Module._ts_node_parse_state_wasm=wasmExports.ts_node_parse_state_wasm)(r),_ts_node_next_parse_state_wasm=Module._ts_node_next_parse_state_wasm=r=>(_ts_node_next_parse_state_wasm=Module._ts_node_next_parse_state_wasm=wasmExports.ts_node_next_parse_state_wasm)(r),_ts_query_matches_wasm=Module._ts_query_matches_wasm=(r,e,t,n,s,o,a,l,c,u,h)=>(_ts_query_matches_wasm=Module._ts_query_matches_wasm=wasmExports.ts_query_matches_wasm)(r,e,t,n,s,o,a,l,c,u,h),_ts_query_captures_wasm=Module._ts_query_captures_wasm=(r,e,t,n,s,o,a,l,c,u,h)=>(_ts_query_captures_wasm=Module._ts_query_captures_wasm=wasmExports.ts_query_captures_wasm)(r,e,t,n,s,o,a,l,c,u,h),_iswalpha=Module._iswalpha=r=>(_iswalpha=Module._iswalpha=wasmExports.iswalpha)(r),_iswblank=Module._iswblank=r=>(_iswblank=Module._iswblank=wasmExports.iswblank)(r),_iswdigit=Module._iswdigit=r=>(_iswdigit=Module._iswdigit=wasmExports.iswdigit)(r),_iswlower=Module._iswlower=r=>(_iswlower=Module._iswlower=wasmExports.iswlower)(r),_iswupper=Module._iswupper=r=>(_iswupper=Module._iswupper=wasmExports.iswupper)(r),_iswxdigit=Module._iswxdigit=r=>(_iswxdigit=Module._iswxdigit=wasmExports.iswxdigit)(r),_memchr=Module._memchr=(r,e,t)=>(_memchr=Module._memchr=wasmExports.memchr)(r,e,t),_strlen=Module._strlen=r=>(_strlen=Module._strlen=wasmExports.strlen)(r),_strcmp=Module._strcmp=(r,e)=>(_strcmp=Module._strcmp=wasmExports.strcmp)(r,e),_strncat=Module._strncat=(r,e,t)=>(_strncat=Module._strncat=wasmExports.strncat)(r,e,t),_strncpy=Module._strncpy=(r,e,t)=>(_strncpy=Module._strncpy=wasmExports.strncpy)(r,e,t),_towlower=Module._towlower=r=>(_towlower=Module._towlower=wasmExports.towlower)(r),_towupper=Module._towupper=r=>(_towupper=Module._towupper=wasmExports.towupper)(r),_setThrew=(r,e)=>(_setThrew=wasmExports.setThrew)(r,e),__emscripten_stack_restore=r=>(__emscripten_stack_restore=wasmExports._emscripten_stack_restore)(r),__emscripten_stack_alloc=r=>(__emscripten_stack_alloc=wasmExports._emscripten_stack_alloc)(r),_emscripten_stack_get_current=()=>(_emscripten_stack_get_current=wasmExports.emscripten_stack_get_current)(),dynCall_jiji=Module.dynCall_jiji=(r,e,t,n,s)=>(dynCall_jiji=Module.dynCall_jiji=wasmExports.dynCall_jiji)(r,e,t,n,s),_orig$ts_parser_timeout_micros=Module._orig$ts_parser_timeout_micros=r=>(_orig$ts_parser_timeout_micros=Module._orig$ts_parser_timeout_micros=wasmExports.orig$ts_parser_timeout_micros)(r),_orig$ts_parser_set_timeout_micros=Module._orig$ts_parser_set_timeout_micros=(r,e)=>(_orig$ts_parser_set_timeout_micros=Module._orig$ts_parser_set_timeout_micros=wasmExports.orig$ts_parser_set_timeout_micros)(r,e);Module.AsciiToString=AsciiToString,Module.stringToUTF16=stringToUTF16;var calledRun;dependenciesFulfilled=function r(){calledRun||run(),calledRun||(dependenciesFulfilled=r)};function callMain(r=[]){var e=resolveGlobalSymbol("main").sym;if(e){r.unshift(thisProgram);var t=r.length,n=stackAlloc((t+1)*4),s=n;r.forEach(a=>{LE_HEAP_STORE_U32((s>>2)*4,stringToUTF8OnStack(a)),s+=4}),LE_HEAP_STORE_U32((s>>2)*4,0);try{var o=e(t,n);return exitJS(o,!0),o}catch(a){return handleException(a)}}}function run(r=arguments_){if(runDependencies>0||(preRun(),runDependencies>0))return;function e(){calledRun||(calledRun=!0,Module.calledRun=!0,!ABORT&&(initRuntime(),preMain(),Module.onRuntimeInitialized?.(),shouldRunNow&&callMain(r),postRun()))}Module.setStatus?(Module.setStatus("Running..."),setTimeout(function(){setTimeout(function(){Module.setStatus("")},1),e()},1)):e()}if(Module.preInit)for(typeof Module.preInit=="function"&&(Module.preInit=[Module.preInit]);Module.preInit.length>0;)Module.preInit.pop()();var shouldRunNow=!0;Module.noInitialRun&&(shouldRunNow=!1),run();let C=Module,INTERNAL={},SIZE_OF_INT=4,SIZE_OF_CURSOR=4*SIZE_OF_INT,SIZE_OF_NODE=5*SIZE_OF_INT,SIZE_OF_POINT=2*SIZE_OF_INT,SIZE_OF_RANGE=2*SIZE_OF_INT+2*SIZE_OF_POINT,ZERO_POINT={row:0,column:0},QUERY_WORD_REGEX=/[\w-.]*/g,PREDICATE_STEP_TYPE_CAPTURE=1,PREDICATE_STEP_TYPE_STRING=2,LANGUAGE_FUNCTION_REGEX=/^_?tree_sitter_\w+/,VERSION,MIN_COMPATIBLE_VERSION,TRANSFER_BUFFER,currentParseCallback,currentLogCallback;class ParserImpl{static init(){TRANSFER_BUFFER=C._ts_init(),VERSION=getValue(TRANSFER_BUFFER,"i32"),MIN_COMPATIBLE_VERSION=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32")}initialize(){C._ts_parser_new_wasm(),this[0]=getValue(TRANSFER_BUFFER,"i32"),this[1]=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32")}delete(){C._ts_parser_delete(this[0]),C._free(this[1]),this[0]=0,this[1]=0}setLanguage(e){let t;if(!e)t=0,e=null;else if(e.constructor===Language){t=e[0];let n=C._ts_language_version(t);if(n<MIN_COMPATIBLE_VERSION||VERSION<n)throw new Error(`Incompatible language version ${n}. Compatibility range ${MIN_COMPATIBLE_VERSION} through ${VERSION}.`)}else throw new Error("Argument must be a Language");return this.language=e,C._ts_parser_set_language(this[0],t),this}getLanguage(){return this.language}parse(e,t,n){if(typeof e=="string")currentParseCallback=(c,u)=>e.slice(c);else if(typeof e=="function")currentParseCallback=e;else throw new Error("Argument must be a string or a function");this.logCallback?(currentLogCallback=this.logCallback,C._ts_parser_enable_logger_wasm(this[0],1)):(currentLogCallback=null,C._ts_parser_enable_logger_wasm(this[0],0));let s=0,o=0;if(n?.includedRanges){s=n.includedRanges.length,o=C._calloc(s,SIZE_OF_RANGE);let c=o;for(let u=0;u<s;u++)marshalRange(c,n.includedRanges[u]),c+=SIZE_OF_RANGE}let a=C._ts_parser_parse_wasm(this[0],this[1],t?t[0]:0,o,s);if(!a)throw currentParseCallback=null,currentLogCallback=null,new Error("Parsing failed");let l=new Tree(INTERNAL,a,this.language,currentParseCallback);return currentParseCallback=null,currentLogCallback=null,l}reset(){C._ts_parser_reset(this[0])}getIncludedRanges(){C._ts_parser_included_ranges_wasm(this[0]);let e=getValue(TRANSFER_BUFFER,"i32"),t=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32"),n=new Array(e);if(e>0){let s=t;for(let o=0;o<e;o++)n[o]=unmarshalRange(s),s+=SIZE_OF_RANGE;C._free(t)}return n}getTimeoutMicros(){return C._ts_parser_timeout_micros(this[0])}setTimeoutMicros(e){C._ts_parser_set_timeout_micros(this[0],e)}setLogger(e){if(!e)e=null;else if(typeof e!="function")throw new Error("Logger callback must be a function");return this.logCallback=e,this}getLogger(){return this.logCallback}}class Tree{constructor(e,t,n,s){assertInternal(e),this[0]=t,this.language=n,this.textCallback=s}copy(){let e=C._ts_tree_copy(this[0]);return new Tree(INTERNAL,e,this.language,this.textCallback)}delete(){C._ts_tree_delete(this[0]),this[0]=0}edit(e){marshalEdit(e),C._ts_tree_edit_wasm(this[0])}get rootNode(){return C._ts_tree_root_node_wasm(this[0]),unmarshalNode(this)}rootNodeWithOffset(e,t){let n=TRANSFER_BUFFER+SIZE_OF_NODE;return setValue(n,e,"i32"),marshalPoint(n+SIZE_OF_INT,t),C._ts_tree_root_node_with_offset_wasm(this[0]),unmarshalNode(this)}getLanguage(){return this.language}walk(){return this.rootNode.walk()}getChangedRanges(e){if(e.constructor!==Tree)throw new TypeError("Argument must be a Tree");C._ts_tree_get_changed_ranges_wasm(this[0],e[0]);let t=getValue(TRANSFER_BUFFER,"i32"),n=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32"),s=new Array(t);if(t>0){let o=n;for(let a=0;a<t;a++)s[a]=unmarshalRange(o),o+=SIZE_OF_RANGE;C._free(n)}return s}getIncludedRanges(){C._ts_tree_included_ranges_wasm(this[0]);let e=getValue(TRANSFER_BUFFER,"i32"),t=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32"),n=new Array(e);if(e>0){let s=t;for(let o=0;o<e;o++)n[o]=unmarshalRange(s),s+=SIZE_OF_RANGE;C._free(t)}return n}}class Node{constructor(e,t){assertInternal(e),this.tree=t}get typeId(){return marshalNode(this),C._ts_node_symbol_wasm(this.tree[0])}get grammarId(){return marshalNode(this),C._ts_node_grammar_symbol_wasm(this.tree[0])}get type(){return this.tree.language.types[this.typeId]||"ERROR"}get grammarType(){return this.tree.language.types[this.grammarId]||"ERROR"}get endPosition(){return marshalNode(this),C._ts_node_end_point_wasm(this.tree[0]),unmarshalPoint(TRANSFER_BUFFER)}get endIndex(){return marshalNode(this),C._ts_node_end_index_wasm(this.tree[0])}get text(){return getText(this.tree,this.startIndex,this.endIndex)}get parseState(){return marshalNode(this),C._ts_node_parse_state_wasm(this.tree[0])}get nextParseState(){return marshalNode(this),C._ts_node_next_parse_state_wasm(this.tree[0])}get isNamed(){return marshalNode(this),C._ts_node_is_named_wasm(this.tree[0])===1}get hasError(){return marshalNode(this),C._ts_node_has_error_wasm(this.tree[0])===1}get hasChanges(){return marshalNode(this),C._ts_node_has_changes_wasm(this.tree[0])===1}get isError(){return marshalNode(this),C._ts_node_is_error_wasm(this.tree[0])===1}get isMissing(){return marshalNode(this),C._ts_node_is_missing_wasm(this.tree[0])===1}get isExtra(){return marshalNode(this),C._ts_node_is_extra_wasm(this.tree[0])===1}equals(e){return this.id===e.id}child(e){return marshalNode(this),C._ts_node_child_wasm(this.tree[0],e),unmarshalNode(this.tree)}namedChild(e){return marshalNode(this),C._ts_node_named_child_wasm(this.tree[0],e),unmarshalNode(this.tree)}childForFieldId(e){return marshalNode(this),C._ts_node_child_by_field_id_wasm(this.tree[0],e),unmarshalNode(this.tree)}childForFieldName(e){let t=this.tree.language.fields.indexOf(e);return t!==-1?this.childForFieldId(t):null}fieldNameForChild(e){marshalNode(this);let t=C._ts_node_field_name_for_child_wasm(this.tree[0],e);return t?AsciiToString(t):null}childrenForFieldName(e){let t=this.tree.language.fields.indexOf(e);return t!==-1&&t!==0?this.childrenForFieldId(t):[]}childrenForFieldId(e){marshalNode(this),C._ts_node_children_by_field_id_wasm(this.tree[0],e);let t=getValue(TRANSFER_BUFFER,"i32"),n=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32"),s=new Array(t);if(t>0){let o=n;for(let a=0;a<t;a++)s[a]=unmarshalNode(this.tree,o),o+=SIZE_OF_NODE;C._free(n)}return s}firstChildForIndex(e){marshalNode(this);let t=TRANSFER_BUFFER+SIZE_OF_NODE;return setValue(t,e,"i32"),C._ts_node_first_child_for_byte_wasm(this.tree[0]),unmarshalNode(this.tree)}firstNamedChildForIndex(e){marshalNode(this);let t=TRANSFER_BUFFER+SIZE_OF_NODE;return setValue(t,e,"i32"),C._ts_node_first_named_child_for_byte_wasm(this.tree[0]),unmarshalNode(this.tree)}get childCount(){return marshalNode(this),C._ts_node_child_count_wasm(this.tree[0])}get namedChildCount(){return marshalNode(this),C._ts_node_named_child_count_wasm(this.tree[0])}get firstChild(){return this.child(0)}get firstNamedChild(){return this.namedChild(0)}get lastChild(){return this.child(this.childCount-1)}get lastNamedChild(){return this.namedChild(this.namedChildCount-1)}get children(){if(!this._children){marshalNode(this),C._ts_node_children_wasm(this.tree[0]);let e=getValue(TRANSFER_BUFFER,"i32"),t=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32");if(this._children=new Array(e),e>0){let n=t;for(let s=0;s<e;s++)this._children[s]=unmarshalNode(this.tree,n),n+=SIZE_OF_NODE;C._free(t)}}return this._children}get namedChildren(){if(!this._namedChildren){marshalNode(this),C._ts_node_named_children_wasm(this.tree[0]);let e=getValue(TRANSFER_BUFFER,"i32"),t=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32");if(this._namedChildren=new Array(e),e>0){let n=t;for(let s=0;s<e;s++)this._namedChildren[s]=unmarshalNode(this.tree,n),n+=SIZE_OF_NODE;C._free(t)}}return this._namedChildren}descendantsOfType(e,t,n){Array.isArray(e)||(e=[e]),t||(t=ZERO_POINT),n||(n=ZERO_POINT);let s=[],o=this.tree.language.types;for(let h=0,d=o.length;h<d;h++)e.includes(o[h])&&s.push(h);let a=C._malloc(SIZE_OF_INT*s.length);for(let h=0,d=s.length;h<d;h++)setValue(a+h*SIZE_OF_INT,s[h],"i32");marshalNode(this),C._ts_node_descendants_of_type_wasm(this.tree[0],a,s.length,t.row,t.column,n.row,n.column);let l=getValue(TRANSFER_BUFFER,"i32"),c=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32"),u=new Array(l);if(l>0){let h=c;for(let d=0;d<l;d++)u[d]=unmarshalNode(this.tree,h),h+=SIZE_OF_NODE}return C._free(c),C._free(a),u}get nextSibling(){return marshalNode(this),C._ts_node_next_sibling_wasm(this.tree[0]),unmarshalNode(this.tree)}get previousSibling(){return marshalNode(this),C._ts_node_prev_sibling_wasm(this.tree[0]),unmarshalNode(this.tree)}get nextNamedSibling(){return marshalNode(this),C._ts_node_next_named_sibling_wasm(this.tree[0]),unmarshalNode(this.tree)}get previousNamedSibling(){return marshalNode(this),C._ts_node_prev_named_sibling_wasm(this.tree[0]),unmarshalNode(this.tree)}get descendantCount(){return marshalNode(this),C._ts_node_descendant_count_wasm(this.tree[0])}get parent(){return marshalNode(this),C._ts_node_parent_wasm(this.tree[0]),unmarshalNode(this.tree)}descendantForIndex(e,t=e){if(typeof e!="number"||typeof t!="number")throw new Error("Arguments must be numbers");marshalNode(this);let n=TRANSFER_BUFFER+SIZE_OF_NODE;return setValue(n,e,"i32"),setValue(n+SIZE_OF_INT,t,"i32"),C._ts_node_descendant_for_index_wasm(this.tree[0]),unmarshalNode(this.tree)}namedDescendantForIndex(e,t=e){if(typeof e!="number"||typeof t!="number")throw new Error("Arguments must be numbers");marshalNode(this);let n=TRANSFER_BUFFER+SIZE_OF_NODE;return setValue(n,e,"i32"),setValue(n+SIZE_OF_INT,t,"i32"),C._ts_node_named_descendant_for_index_wasm(this.tree[0]),unmarshalNode(this.tree)}descendantForPosition(e,t=e){if(!isPoint(e)||!isPoint(t))throw new Error("Arguments must be {row, column} objects");marshalNode(this);let n=TRANSFER_BUFFER+SIZE_OF_NODE;return marshalPoint(n,e),marshalPoint(n+SIZE_OF_POINT,t),C._ts_node_descendant_for_position_wasm(this.tree[0]),unmarshalNode(this.tree)}namedDescendantForPosition(e,t=e){if(!isPoint(e)||!isPoint(t))throw new Error("Arguments must be {row, column} objects");marshalNode(this);let n=TRANSFER_BUFFER+SIZE_OF_NODE;return marshalPoint(n,e),marshalPoint(n+SIZE_OF_POINT,t),C._ts_node_named_descendant_for_position_wasm(this.tree[0]),unmarshalNode(this.tree)}walk(){return marshalNode(this),C._ts_tree_cursor_new_wasm(this.tree[0]),new TreeCursor(INTERNAL,this.tree)}toString(){marshalNode(this);let e=C._ts_node_to_string_wasm(this.tree[0]),t=AsciiToString(e);return C._free(e),t}}class TreeCursor{constructor(e,t){assertInternal(e),this.tree=t,unmarshalTreeCursor(this)}delete(){marshalTreeCursor(this),C._ts_tree_cursor_delete_wasm(this.tree[0]),this[0]=this[1]=this[2]=0}reset(e){marshalNode(e),marshalTreeCursor(this,TRANSFER_BUFFER+SIZE_OF_NODE),C._ts_tree_cursor_reset_wasm(this.tree[0]),unmarshalTreeCursor(this)}resetTo(e){marshalTreeCursor(this,TRANSFER_BUFFER),marshalTreeCursor(e,TRANSFER_BUFFER+SIZE_OF_CURSOR),C._ts_tree_cursor_reset_to_wasm(this.tree[0],e.tree[0]),unmarshalTreeCursor(this)}get nodeType(){return this.tree.language.types[this.nodeTypeId]||"ERROR"}get nodeTypeId(){return marshalTreeCursor(this),C._ts_tree_cursor_current_node_type_id_wasm(this.tree[0])}get nodeStateId(){return marshalTreeCursor(this),C._ts_tree_cursor_current_node_state_id_wasm(this.tree[0])}get nodeId(){return marshalTreeCursor(this),C._ts_tree_cursor_current_node_id_wasm(this.tree[0])}get nodeIsNamed(){return marshalTreeCursor(this),C._ts_tree_cursor_current_node_is_named_wasm(this.tree[0])===1}get nodeIsMissing(){return marshalTreeCursor(this),C._ts_tree_cursor_current_node_is_missing_wasm(this.tree[0])===1}get nodeText(){marshalTreeCursor(this);let e=C._ts_tree_cursor_start_index_wasm(this.tree[0]),t=C._ts_tree_cursor_end_index_wasm(this.tree[0]);return getText(this.tree,e,t)}get startPosition(){return marshalTreeCursor(this),C._ts_tree_cursor_start_position_wasm(this.tree[0]),unmarshalPoint(TRANSFER_BUFFER)}get endPosition(){return marshalTreeCursor(this),C._ts_tree_cursor_end_position_wasm(this.tree[0]),unmarshalPoint(TRANSFER_BUFFER)}get startIndex(){return marshalTreeCursor(this),C._ts_tree_cursor_start_index_wasm(this.tree[0])}get endIndex(){return marshalTreeCursor(this),C._ts_tree_cursor_end_index_wasm(this.tree[0])}get currentNode(){return marshalTreeCursor(this),C._ts_tree_cursor_current_node_wasm(this.tree[0]),unmarshalNode(this.tree)}get currentFieldId(){return marshalTreeCursor(this),C._ts_tree_cursor_current_field_id_wasm(this.tree[0])}get currentFieldName(){return this.tree.language.fields[this.currentFieldId]}get currentDepth(){return marshalTreeCursor(this),C._ts_tree_cursor_current_depth_wasm(this.tree[0])}get currentDescendantIndex(){return marshalTreeCursor(this),C._ts_tree_cursor_current_descendant_index_wasm(this.tree[0])}gotoFirstChild(){marshalTreeCursor(this);let e=C._ts_tree_cursor_goto_first_child_wasm(this.tree[0]);return unmarshalTreeCursor(this),e===1}gotoLastChild(){marshalTreeCursor(this);let e=C._ts_tree_cursor_goto_last_child_wasm(this.tree[0]);return unmarshalTreeCursor(this),e===1}gotoFirstChildForIndex(e){marshalTreeCursor(this),setValue(TRANSFER_BUFFER+SIZE_OF_CURSOR,e,"i32");let t=C._ts_tree_cursor_goto_first_child_for_index_wasm(this.tree[0]);return unmarshalTreeCursor(this),t===1}gotoFirstChildForPosition(e){marshalTreeCursor(this),marshalPoint(TRANSFER_BUFFER+SIZE_OF_CURSOR,e);let t=C._ts_tree_cursor_goto_first_child_for_position_wasm(this.tree[0]);return unmarshalTreeCursor(this),t===1}gotoNextSibling(){marshalTreeCursor(this);let e=C._ts_tree_cursor_goto_next_sibling_wasm(this.tree[0]);return unmarshalTreeCursor(this),e===1}gotoPreviousSibling(){marshalTreeCursor(this);let e=C._ts_tree_cursor_goto_previous_sibling_wasm(this.tree[0]);return unmarshalTreeCursor(this),e===1}gotoDescendant(e){marshalTreeCursor(this),C._ts_tree_cursor_goto_descendant_wasm(this.tree[0],e),unmarshalTreeCursor(this)}gotoParent(){marshalTreeCursor(this);let e=C._ts_tree_cursor_goto_parent_wasm(this.tree[0]);return unmarshalTreeCursor(this),e===1}}class Language{constructor(e,t){assertInternal(e),this[0]=t,this.types=new Array(C._ts_language_symbol_count(this[0]));for(let n=0,s=this.types.length;n<s;n++)C._ts_language_symbol_type(this[0],n)<2&&(this.types[n]=UTF8ToString(C._ts_language_symbol_name(this[0],n)));this.fields=new Array(C._ts_language_field_count(this[0])+1);for(let n=0,s=this.fields.length;n<s;n++){let o=C._ts_language_field_name_for_id(this[0],n);o!==0?this.fields[n]=UTF8ToString(o):this.fields[n]=null}}get version(){return C._ts_language_version(this[0])}get fieldCount(){return this.fields.length-1}get stateCount(){return C._ts_language_state_count(this[0])}fieldIdForName(e){let t=this.fields.indexOf(e);return t!==-1?t:null}fieldNameForId(e){return this.fields[e]||null}idForNodeType(e,t){let n=lengthBytesUTF8(e),s=C._malloc(n+1);stringToUTF8(e,s,n+1);let o=C._ts_language_symbol_for_name(this[0],s,n,t);return C._free(s),o||null}get nodeTypeCount(){return C._ts_language_symbol_count(this[0])}nodeTypeForId(e){let t=C._ts_language_symbol_name(this[0],e);return t?UTF8ToString(t):null}nodeTypeIsNamed(e){return!!C._ts_language_type_is_named_wasm(this[0],e)}nodeTypeIsVisible(e){return!!C._ts_language_type_is_visible_wasm(this[0],e)}nextState(e,t){return C._ts_language_next_state(this[0],e,t)}lookaheadIterator(e){let t=C._ts_lookahead_iterator_new(this[0],e);return t?new LookaheadIterable(INTERNAL,t,this):null}query(e){let t=lengthBytesUTF8(e),n=C._malloc(t+1);stringToUTF8(e,n,t+1);let s=C._ts_query_new(this[0],n,t,TRANSFER_BUFFER,TRANSFER_BUFFER+SIZE_OF_INT);if(!s){let w=getValue(TRANSFER_BUFFER+SIZE_OF_INT,"i32"),m=getValue(TRANSFER_BUFFER,"i32"),_=UTF8ToString(n,m).length,b=e.substr(_,100).split(`
4
4
  `)[0],v=b.match(QUERY_WORD_REGEX)[0],S;switch(w){case 2:S=new RangeError(`Bad node name '${v}'`);break;case 3:S=new RangeError(`Bad field name '${v}'`);break;case 4:S=new RangeError(`Bad capture name @${v}`);break;case 5:S=new TypeError(`Bad pattern structure at offset ${_}: '${b}'...`),v="";break;default:S=new SyntaxError(`Bad syntax at offset ${_}: '${b}'...`),v="";break}throw S.index=_,S.length=v.length,C._free(n),S}let o=C._ts_query_string_count(s),a=C._ts_query_capture_count(s),l=C._ts_query_pattern_count(s),c=new Array(a),u=new Array(o);for(let w=0;w<a;w++){let m=C._ts_query_capture_name_for_id(s,w,TRANSFER_BUFFER),_=getValue(TRANSFER_BUFFER,"i32");c[w]=UTF8ToString(m,_)}for(let w=0;w<o;w++){let m=C._ts_query_string_value_for_id(s,w,TRANSFER_BUFFER),_=getValue(TRANSFER_BUFFER,"i32");u[w]=UTF8ToString(m,_)}let h=new Array(l),d=new Array(l),f=new Array(l),p=new Array(l),y=new Array(l);for(let w=0;w<l;w++){let m=C._ts_query_predicates_for_pattern(s,w,TRANSFER_BUFFER),_=getValue(TRANSFER_BUFFER,"i32");p[w]=[],y[w]=[];let b=[],v=m;for(let S=0;S<_;S++){let E=getValue(v,"i32");v+=SIZE_OF_INT;let T=getValue(v,"i32");if(v+=SIZE_OF_INT,E===PREDICATE_STEP_TYPE_CAPTURE)b.push({type:"capture",name:c[T]});else if(E===PREDICATE_STEP_TYPE_STRING)b.push({type:"string",value:u[T]});else if(b.length>0){if(b[0].type!=="string")throw new Error("Predicates must begin with a literal value");let A=b[0].value,k=!0,P=!0,U;switch(A){case"any-not-eq?":case"not-eq?":k=!1;case"any-eq?":case"eq?":if(b.length!==3)throw new Error(`Wrong number of arguments to \`#${A}\` predicate. Expected 2, got ${b.length-1}`);if(b[1].type!=="capture")throw new Error(`First argument of \`#${A}\` predicate must be a capture. Got "${b[1].value}"`);if(P=!A.startsWith("any-"),b[2].type==="capture"){let G=b[1].name,j=b[2].name;y[w].push(q=>{let W=[],V=[];for(let I of q)I.name===G&&W.push(I.node),I.name===j&&V.push(I.node);let x=(I,L,O)=>O?I.text===L.text:I.text!==L.text;return P?W.every(I=>V.some(L=>x(I,L,k))):W.some(I=>V.some(L=>x(I,L,k)))})}else{U=b[1].name;let G=b[2].value,j=W=>W.text===G,q=W=>W.text!==G;y[w].push(W=>{let V=[];for(let I of W)I.name===U&&V.push(I.node);let x=k?j:q;return P?V.every(x):V.some(x)})}break;case"any-not-match?":case"not-match?":k=!1;case"any-match?":case"match?":if(b.length!==3)throw new Error(`Wrong number of arguments to \`#${A}\` predicate. Expected 2, got ${b.length-1}.`);if(b[1].type!=="capture")throw new Error(`First argument of \`#${A}\` predicate must be a capture. Got "${b[1].value}".`);if(b[2].type!=="string")throw new Error(`Second argument of \`#${A}\` predicate must be a string. Got @${b[2].value}.`);U=b[1].name;let F=new RegExp(b[2].value);P=!A.startsWith("any-"),y[w].push(G=>{let j=[];for(let W of G)W.name===U&&j.push(W.node.text);let q=(W,V)=>V?F.test(W):!F.test(W);return j.length===0?!k:P?j.every(W=>q(W,k)):j.some(W=>q(W,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(G=>G.type!=="string"))throw new Error('Arguments to `#set!` predicate must be a strings.".');h[w]||(h[w]={}),h[w][b[1].value]=b[2]?b[2].value:null;break;case"is?":case"is-not?":if(b.length<2||b.length>3)throw new Error(`Wrong number of arguments to \`#${A}\` predicate. Expected 1 or 2. Got ${b.length-1}.`);if(b.some(G=>G.type!=="string"))throw new Error(`Arguments to \`#${A}\` predicate must be a strings.".`);let D=A==="is?"?d:f;D[w]||(D[w]={}),D[w][b[1].value]=b[2]?b[2].value:null;break;case"not-any-of?":k=!1;case"any-of?":if(b.length<2)throw new Error(`Wrong number of arguments to \`#${A}\` predicate. Expected at least 1. Got ${b.length-1}.`);if(b[1].type!=="capture")throw new Error(`First argument of \`#${A}\` predicate must be a capture. Got "${b[1].value}".`);for(let G=2;G<b.length;G++)if(b[G].type!=="string")throw new Error(`Arguments to \`#${A}\` predicate must be a strings.".`);U=b[1].name;let H=b.slice(2).map(G=>G.value);y[w].push(G=>{let j=[];for(let q of G)q.name===U&&j.push(q.node.text);return j.length===0?!k:j.every(q=>H.includes(q))===k});break;default:p[w].push({operator:A,operands:b.slice(1)})}b.length=0}}Object.freeze(h[w]),Object.freeze(d[w]),Object.freeze(f[w])}return C._free(n),new Query(INTERNAL,s,c,y,p,Object.freeze(h),Object.freeze(d),Object.freeze(f))}static load(e){let t;if(e instanceof Uint8Array)t=Promise.resolve(e);else{let n=e;if(typeof process<"u"&&process.versions&&process.versions.node){let s=Se("fs");t=Promise.resolve(s.readFileSync(n))}else t=fetch(n).then(s=>s.arrayBuffer().then(o=>{if(s.ok)return new Uint8Array(o);{let a=new TextDecoder("utf-8").decode(o);throw new Error(`Language.load failed with status ${s.status}.
5
5
 
6
6
  ${a}`)}}))}return t.then(n=>loadWebAssemblyModule(n,{loadAsync:!0})).then(n=>{let s=Object.keys(n),o=s.find(l=>LANGUAGE_FUNCTION_REGEX.test(l)&&!l.includes("external_scanner_"));o||console.log(`Couldn't find language function in WASM file. Symbols:
@@ -346,7 +346,7 @@ ${jpe}`}]}],config:{temperature:.2,maxOutputTokens:100},abortSignal:e,maxAttempt
346
346
  `);if(n.length<=e)return n;let s=n.slice(-e);if(s.length>0){let o=s.charCodeAt(0);o>=56320&&o<=57343&&(s=s.slice(1))}return s}g();import{createHash as wme}from"node:crypto";g();g();import{createHash as Qpe}from"node:crypto";function MW(r,e){let t=e.protocol??r.protocol;return typeof r.envKey=="function"?r.envKey(t,e.baseUrl):r.envKey}function eme(r,e){return typeof r.modelNamePrefix=="function"?r.modelNamePrefix(e):r.modelNamePrefix}function IW(r){if(r.ownsModel)return r.ownsModel;if(typeof r.envKey!="string"||typeof r.modelNamePrefix!="string")return;let e=r.envKey,t=r.modelNamePrefix;if(!t)return s=>s.envKey===e;let n=`[${t}] `;return s=>s.envKey===e&&typeof s.name=="string"&&s.name.startsWith(n)}function tme(r){let e={...r.generationConfig??{}},t=Object.keys(e).length>0;return r.enableThinking&&(e.extra_body={...e.extra_body??{},enable_thinking:!0},t=!0),r.contextWindowSize&&(e.contextWindowSize=r.contextWindowSize,t=!0),r.modalities&&Object.values(r.modalities).some(Boolean)&&(e.modalities=r.modalities,t=!0),t?e:void 0}function RW(r){let e={},t=!1;return r?.enableThinking&&(e.extra_body={enable_thinking:!0},t=!0),r?.multimodal&&Object.values(r.multimodal).some(Boolean)&&(e.modalities=r.multimodal,t=!0),r?.contextWindowSize&&r.contextWindowSize>0&&(e.contextWindowSize=r.contextWindowSize,t=!0),r?.maxTokens&&r.maxTokens>0&&(e.samplingParams={max_tokens:r.maxTokens},t=!0),t?e:void 0}function PW(r,e,t,n){let s=tme(r),o=r.displayName??r.id;return{id:r.id,name:e?`[${e}] ${o}`:o,...r.description?{description:r.description}:{},baseUrl:t,envKey:n,...s?{generationConfig:s}:{}}}function OW(r,e){let t=MW(r,e),n=eme(r,e.baseUrl);if(r.models&&!r.modelsEditable)return r.models.map(a=>PW(a,n,e.baseUrl,t));if(r.models&&r.modelsEditable){let a=new Map(r.models.map(l=>[l.id,l]));return e.modelIds.map(l=>{let c=a.get(l);if(c)return PW(c,n,e.baseUrl,t);let u=RW(e.advancedConfig);return{id:l,name:n?`[${n}] ${l}`:l,baseUrl:e.baseUrl,envKey:t,...u?{generationConfig:u}:{}}})}let s=e.advancedConfig,o=a=>n?`[${n}] ${a}`:a;return e.modelIds.map(a=>{let l=RW(s);return{id:a,name:o(a),baseUrl:e.baseUrl,envKey:t,...l?{generationConfig:l}:{}}})}function DW(r){if(r.models){if(r.id.includes("."))throw new Error(`Provider id must not contain '.' (would corrupt providerMetadata.${r.id} dotted writes): ${r.id}`);return r.id}}var LW="providerMetadata";function rme(r,e,t){let n=DW(r);if(n)return{[`${LW}.${n}`]:{version:NW(t),baseUrl:e}}}function nme(r,e){let t=e.protocol??r.protocol,n=MW(r,e),s=e.prebuiltModels??OW(r,e);if(s.length===0)throw new Error(`No models configured for provider "${r.id}". Check model list or provider configuration.`);let o=s[0]?.id,a=e.apiKey?{[n]:e.apiKey}:void 0;return{providerId:r.id,authType:t,...a?{env:a}:{clearEnv:[n]},...o?{modelSelection:{modelId:o}}:{},modelProviders:[{authType:t,models:s,mergeStrategy:"prepend-and-remove-owned",ownsModel:IW(r)}],providerState:rme(r,e.baseUrl,s)}}function NW(r){return Qpe("sha256").update(JSON.stringify(r)).digest("hex")}var sme={openai:"https://api.openai.com/v1",anthropic:"https://api.anthropic.com/v1",gemini:"https://generativelanguage.googleapis.com"};function ime(r){return r===void 0?"":sme[r]??""}function FW(r,e){if(typeof r.baseUrl=="string")return r.baseUrl;if(Array.isArray(r.baseUrl)){let t=r.baseUrl.find(n=>n.url===e);return t?t.url:r.baseUrl[0]?.url??e??""}return e??""}function $W(r){return r.models?.map(e=>e.id)??[]}function ome(r,e){switch(e){case"protocol":return Array.isArray(r.protocolOptions)&&r.protocolOptions.length>1;case"baseUrl":return r.baseUrl===void 0||Array.isArray(r.baseUrl);case"apiKey":return!0;case"models":return!r.models||r.modelsEditable===!0;case"advancedConfig":return r.showAdvancedConfig===!0;default:return!1}}function N0(r,e,t){let n;if(typeof r.envKey=="string")n=r.envKey;else if(typeof r.envKey=="function"&&e){let s=r.protocolOptions?.length?r.protocolOptions:[r.protocol];for(let o of s)try{let a=r.envKey(o,e);if(a===t){n=a;break}}catch(a){let l;try{l=new URL(e).hostname}catch{l="[invalid]"}console.warn(`[providerMatchesCredentials] envKey(${o}, ${l}) threw (${a instanceof Error?a.constructor.name:typeof a}); skipping this protocol`)}}return n!==t?!1:typeof r.baseUrl=="string"?r.baseUrl===e:Array.isArray(r.baseUrl)?r.baseUrl.some(s=>s.url===e):r.baseUrl===void 0&&n!==void 0?!!e:!1}function ame(r,e){let t=FW(r,e);return OW(r,{baseUrl:t,apiKey:"",modelIds:$W(r)})}g();g();var F0="OPENROUTER_API_KEY",UW="https://openrouter.ai/api/v1",$0={id:"openrouter",label:"OpenRouter",description:"Connect with an OpenRouter API key (get one from openrouter.ai/keys)",protocol:"openai",baseUrl:UW,envKey:F0,models:[{id:"z-ai/glm-4.5-air:free",contextWindowSize:128e3},{id:"openai/gpt-oss-120b:free",contextWindowSize:131072}],modelsEditable:!0,modelNamePrefix:"OpenRouter",ownsModel:r=>{if(r.envKey!==F0)return!1;try{let e=new URL(r.baseUrl??"").hostname;return e==="openrouter.ai"||e.endsWith(".openrouter.ai")}catch{return!1}},documentationUrl:"https://openrouter.ai/docs",uiGroup:"third-party"};g();var U0={id:"deepseek",label:"DeepSeek API Key",description:"Quick setup for DeepSeek (deepseek-v4-flash, deepseek-v4-pro)",protocol:"openai",baseUrl:"https://api.deepseek.com",envKey:"DEEPSEEK_API_KEY",models:[{id:"deepseek-v4-pro",contextWindowSize:1e6,enableThinking:!0,modalities:{image:!0,video:!0}},{id:"deepseek-v4-flash",contextWindowSize:1e6}],modelsEditable:!0,modelNamePrefix:"DeepSeek",documentationUrl:"https://api-docs.deepseek.com/zh-cn/",uiGroup:"third-party"};g();var H0={id:"minimax",label:"MiniMax API Key",description:"Quick setup for MiniMax models",protocol:"openai",baseUrl:[{id:"international",label:"International",url:"https://api.minimax.io/v1",documentationUrl:"https://www.minimax.io/platform"},{id:"china",label:"China",url:"https://api.minimaxi.com/v1",documentationUrl:"https://platform.minimaxi.com"}],envKey:"MINIMAX_API_KEY",models:[{id:"MiniMax-M3",contextWindowSize:1e6,modalities:{image:!0,video:!0}},{id:"MiniMax-M2.7",contextWindowSize:204800},{id:"MiniMax-M2.7-highspeed",contextWindowSize:204800},{id:"MiniMax-M2.5",contextWindowSize:196608},{id:"MiniMax-M2.5-highspeed",contextWindowSize:196608}],modelsEditable:!0,modelNamePrefix:"MiniMax",uiGroup:"third-party"};g();var B0={id:"zai",label:"Z.AI API Key",description:"Quick setup for Z.AI models",protocol:"openai",baseUrl:[{id:"standard-api-key",label:"Standard API Key",url:"https://api.z.ai/api/paas/v4",documentationUrl:"https://docs.z.ai/"},{id:"coding-plan",label:"Coding Plan",url:"https://api.z.ai/api/coding/paas/v4",documentationUrl:"https://docs.z.ai/"}],envKey:"ZAI_API_KEY",models:[{id:"GLM-5.1",contextWindowSize:204800,enableThinking:!0},{id:"GLM-5",contextWindowSize:204800},{id:"GLM-5-Turbo",contextWindowSize:204800}],modelsEditable:!0,modelNamePrefix:"Z.AI",uiGroup:"third-party"};g();var j0={id:"modelscope",label:"ModelScope API Key",description:"Quick setup for ModelScope API Inference",protocol:"openai",baseUrl:"https://api-inference.modelscope.cn/v1",envKey:"MODELSCOPE_API_KEY",models:[{id:"deepseek-ai/DeepSeek-V4-Flash",contextWindowSize:1e6,enableThinking:!0},{id:"Matilda/Matilda3.5-397B-A17B",contextWindowSize:1e6,enableThinking:!0},{id:"ZhipuAI/GLM-5.1",contextWindowSize:1e6,enableThinking:!0}],modelsEditable:!0,modelNamePrefix:"ModelScope",documentationUrl:"https://modelscope.cn/docs/model-service/API-Inference/intro",uiGroup:"third-party"};g();import{createHash as lme}from"node:crypto";var Uv="MATILDA_CUSTOM_API_KEY_";function HW(r){let e=r.trim().toUpperCase(),t="",n=!1;for(let a=0;a<e.length;a++){let l=e.charCodeAt(a);l>=65&&l<=90||l>=48&&l<=57?(t+=e[a],n=!1):n||(t+="_",n=!0)}let s=0,o=t.length;for(;s<o&&t.charCodeAt(s)===95;)s++;for(;o>s&&t.charCodeAt(o-1)===95;)o--;return t.slice(s,o)}function cme(r){let e=r.length;for(;e>0&&r.charCodeAt(e-1)===47;)e--;return r.slice(0,e)}function z0(r,e){let t=cme(e.trim()),n=lme("sha256").update(`${r}\0${t}`).digest("hex").slice(0,12).toUpperCase();return`${Uv}${HW(r)}_${HW(e)}_${n}`}var q0={id:"custom-openai-compatible",label:"Custom Provider",description:"Manually connect a local server, proxy, or unsupported provider",protocol:"openai",protocolOptions:["openai","anthropic","gemini"],baseUrl:void 0,envKey:z0,models:void 0,modelNamePrefix:"",showAdvancedConfig:!0,ownsModel:r=>typeof r.envKey=="string"&&r.envKey.startsWith(Uv),uiGroup:"custom"};var km=[_P,U0,H0,B0,j0,$0,q0],ume=km.filter(r=>r.uiGroup==="third-party");function dme(r){return km.find(e=>e.id===r)}function hme(r,e){return km.find(t=>N0(t,r,e))}function fme(){return km.flatMap(r=>typeof r.baseUrl=="string"?[r.baseUrl]:Array.isArray(r.baseUrl)?r.baseUrl.map(e=>e.url):[])}g();var BW=new Set(["NODE_OPTIONS","NODE_PATH","LD_PRELOAD","LD_LIBRARY_PATH","DYLD_INSERT_LIBRARIES","DYLD_LIBRARY_PATH","PATH","HOME","TMPDIR","TMP","TEMP"]);function pme(r,e){return r.id===e.id&&(r.baseUrl??"")===(e.baseUrl??"")}function mme(r,e){let t=r[e.authType]??[],n=e.models;if(e.mergeStrategy==="append")n=[...t,...e.models];else{let s=e.ownsModel,o=t.filter(a=>s?!s(a):!e.models.some(l=>pme(l,a)));n=e.mergeStrategy==="replace-owned"?[...o,...e.models]:[...e.models,...o]}return{...r,[e.authType]:n}}var Hv=class extends Error{step;authType;constructor(e,t,n,s){super(e,s),this.name="ProviderInstallError",this.step=t,this.authType=n}};async function gme(r,e){let{settings:t,reloadModelProviders:n,syncAuthState:s,refreshAuth:o,doRefreshAuth:a=!0}=e,l=new Map,c={...t.getModelProviders()},u="init";try{u="backup",t.backup?.(),u="env";for(let d of r.clearEnv??[]){if(BW.has(d.toUpperCase()))throw new Error(`Install plan must not clear reserved environment variable: ${d}`);l.set(d,process.env[d]),t.setValue(`env.${d}`,void 0),delete process.env[d]}for(let[d,f]of Object.entries(r.env??{})){if(BW.has(d.toUpperCase()))throw new Error(`Install plan must not set reserved environment variable: ${d}`);l.set(d,process.env[d]),t.setValue(`env.${d}`,f),process.env[d]=f}u="modelProviders";let h={...c};for(let d of r.modelProviders??[])h=mme(h,d),t.setValue(`modelProviders.${d.authType}`,h[d.authType]??[]);u="authType",t.setValue("security.auth.selectedType",r.authType),u="legacyCredentials",r.legacyCredentials?.apiKey!=null&&t.setValue("security.auth.apiKey",r.legacyCredentials.apiKey),r.legacyCredentials?.baseUrl!=null&&t.setValue("security.auth.baseUrl",r.legacyCredentials.baseUrl),u="modelSelection",r.modelSelection?.modelId&&t.setValue("model.name",r.modelSelection.modelId),u="providerState";for(let[d,f]of Object.entries(r.providerState??{}))for(let[p,y]of Object.entries(f))t.setValue(`${d}.${p}`,y);return u="persist",t.persist(),u="reloadModelProviders",n?.(h),r.modelSelection?.modelId&&(u="syncAuthState",s?.(r.authType,r.modelSelection.modelId)),a&&o&&(u="refreshAuth",await o(r.authType)),u="cleanupBackup",t.cleanupBackup?.(),{updatedModelProviders:h}}catch(h){try{t.restore?.()}catch(f){console.error("[applyProviderInstallPlan] settings.restore failed during rollback:",f)}try{for(let[f,p]of l)p===void 0?delete process.env[f]:process.env[f]=p}catch(f){console.error("[applyProviderInstallPlan] env rollback failed:",f)}try{n?.(c)}catch(f){console.error("[applyProviderInstallPlan] reloadModelProviders failed during rollback:",f)}let d=h instanceof Error?h.message:String(h);throw new Hv(d,u,r.authType,{cause:h instanceof Error?h:void 0})}}function jW(r){let e=wme("sha256");e.update("matilda-local-history-account-scope:v1");for(let t of r)e.update("\0"),e.update(t);return e.digest("hex")}function zW(r){return!r?.userId||!r.baseUrl?null:jW(["matilda-oauth",bP(r.baseUrl).toLowerCase(),r.userId])}function _me(r){return r?.apiKey?jW(["api-key",String(r.authType??""),String(r.apiKeyEnvKey??""),String(r.baseUrl??""),r.apiKey]):null}function qW(r={}){let e=zW(ov(r));return e||_me(r.contentGeneratorConfig)}function ZJe(r){return zW(r)}var Lt=$("CHAT_RECORDING"),vme=3,Sme=1e5,Cme=5e4,Bv=16e3,Eme=32*1024;function Tme(r){if(typeof r!="object"||r===null||!("fileDiff"in r)||!("fileName"in r)||!("originalContent"in r)||!("newContent"in r))return!1;let e=r,t=e.originalContent;return typeof e.fileDiff=="string"&&typeof e.fileName=="string"&&typeof e.newContent=="string"&&(t===null||typeof t=="string")}function GW(r){return typeof r=="string"?r.length:0}function WW(r,e){if(r.length<=e)return r;let t=`
347
347
  [... truncated for saved session preview; original length: ${r.length} characters ...]
348
348
  `,n=Math.max(0,e-t.length),s=Math.ceil(n*.6),o=n-s;return r.slice(0,s)+t+(o>0?r.slice(r.length-o):"")}function kme(r){let e=GW(r.originalContent);return[`--- ${r.fileName}`,`+++ ${r.fileName}`,"@@ -1 +1 @@",`-Full diff omitted from saved session history; original fileDiff length: ${r.fileDiff.length} characters.`,`+Saved session preview only; originalContent length: ${e} characters, newContent length: ${r.newContent.length} characters.`].join(`
349
- `)}function xme(r){let e=r.fileDiff.length,t=GW(r.originalContent),n=r.newContent.length,s=e+t+n,o=e>Cme,a=t>Bv,l=n>Bv;return s<=Sme&&!o&&!a&&!l?r:{...r,fileDiff:o?kme(r):r.fileDiff,originalContent:r.originalContent!==null&&a?WW(r.originalContent,Bv):r.originalContent,newContent:l?WW(r.newContent,Bv):r.newContent,truncatedForSession:!0,fileDiffLength:e,originalContentLength:t,newContentLength:n,fileDiffTruncated:o,originalContentTruncated:a,newContentTruncated:l}}function Ame(r){let e=r.resultDisplay;if(!Tme(e))return r;let t=xme(e);return t===e?r:{...r,resultDisplay:t}}function Rme(){let r=process.env.MATILDA_DISABLE_AUTO_TITLE;if(!r)return!1;let e=r.trim().toLowerCase();return e!==""&&e!=="0"&&e!=="false"&&e!=="no"&&e!=="off"}var Tm="thought_only_max_tokens",Ho="stream_recovery_snapshot",zc="stream_recovery_partial",nh=class{lastRecordUuid=null;config;turnParentUuids=[];cachedConversationFile;writeChain=Promise.resolve();transcriptWriterPromise;pendingRecords=new Set;transcriptCommitListeners=new Set;currentCustomTitle;currentTitleSource;autoTitleAttempts=0;autoTitleController;lastAttributionSnapshotJson;cachedGitBranch;bytesSinceTitleAnchor=0;constructor(e){if(this.config=e,this.lastRecordUuid=e.getResumedSessionData()?.lastCompletedUuid??null,e.getResumedSessionData())try{let n=e.getSessionService().getSessionTitleInfo(e.getSessionId());this.currentCustomTitle=n.title,this.currentTitleSource=n.source,this.finalize()}catch{}}getCurrentCustomTitle(){return this.currentCustomTitle}getCurrentTitleSource(){return this.currentTitleSource}getSessionId(){return this.config.getSessionId()}resolveConversationFile(){return this.cachedConversationFile?this.cachedConversationFile:(this.cachedConversationFile=this.config.getTranscriptPath(),this.cachedConversationFile)}createBaseRecord(e){let t=this.config.getProjectRoot(),n=qW({channel:this.config.getChannel?.(),contentGeneratorConfig:this.config.getContentGeneratorConfig?.()});return{uuid:bme(),parentUuid:this.lastRecordUuid,sessionId:this.getSessionId(),timestamp:new Date().toISOString(),type:e,cwd:t,version:this.config.getCliVersion()||"unknown",gitBranch:this.getCachedGitBranch(t),...n?{accountScopeId:n}:{}}}getCachedGitBranch(e){return(!this.cachedGitBranch||this.cachedGitBranch.cwd!==e)&&(this.cachedGitBranch={cwd:e,branch:Xd(e)}),this.cachedGitBranch.branch}async getTranscriptWriter(e){let t=this.transcriptWriterPromise??Bc.open(e,this.getSessionId());this.transcriptWriterPromise=t;try{return await t}catch(n){throw this.transcriptWriterPromise===t&&(this.transcriptWriterPromise=void 0),n}}appendRecord(e,t,n){let s;try{s=this.resolveConversationFile()}catch(a){throw Lt.error("Error appending record:",a),a}n?.updateActiveTail!==!1&&(this.lastRecordUuid=e.uuid),this.pendingRecords.add(e);let o=this.writeChain.then(()=>this.getTranscriptWriter(s).then(a=>a.append(e))).then(a=>{for(let l of this.transcriptCommitListeners)try{l({writerEpoch:a.writerEpoch,committedPosition:a.committedPosition,selectedLeafUuid:a.recordUuid})}catch(c){Lt.warn("Transcript commit observer failed:",c)}return a}).catch(a=>{let l=n&&"rollbackParentUuid"in n?n.rollbackParentUuid??null:e.parentUuid;this.lastRecordUuid===e.uuid&&(this.lastRecordUuid=l),this.turnParentUuids=this.turnParentUuids.map(c=>c===e.uuid?l:c);for(let c of this.pendingRecords)c.parentUuid===e.uuid&&(c.parentUuid=l);if(Lt.error("Error appending record (async):",a),t)try{t(a)}catch(c){Lt.error("appendRecord onError callback threw:",c)}throw a}).finally(()=>{this.pendingRecords.delete(e)});return this.writeChain=o.then(()=>{},()=>{}),n?.updateTitleAnchor!==!1&&this.updateTitleAnchorTracking(e),o}updateTitleAnchorTracking(e){if(e.type==="system"&&e.subtype==="custom_title"){this.bytesSinceTitleAnchor=0;return}this.currentCustomTitle&&(this.bytesSinceTitleAnchor+=Buffer.byteLength(JSON.stringify(e),"utf8")+1,this.bytesSinceTitleAnchor>=Eme&&this.reanchorTitle())}reanchorTitle(){if(this.currentCustomTitle)try{let e={...this.createBaseRecord("system"),type:"system",subtype:"custom_title",systemPayload:{customTitle:this.currentCustomTitle,...this.currentTitleSource?{titleSource:this.currentTitleSource}:{}}};this.appendRecord(e,void 0,{updateActiveTail:!1})}catch(e){this.bytesSinceTitleAnchor=0,Lt.error("Error re-anchoring custom title:",e)}}async flush(){await this.writeChain}subscribeToTranscriptCommits(e){return this.transcriptCommitListeners.add(e),()=>{this.transcriptCommitListeners.delete(e)}}readTranscript(e){let t=this.writeChain.then(async()=>{let n=await this.getTranscriptWriter(this.resolveConversationFile());return wW(await n.readRecords(),e)});return this.writeChain=t.then(()=>{},()=>{}),t}async releaseTranscriptOwnership(){await this.flush();let e=this.transcriptWriterPromise;if(this.transcriptWriterPromise=void 0,!e)return;let t=await e.catch(()=>{});t&&await t.close()}resetStoragePaths(){this.cachedConversationFile=void 0}recordUserMessage(e){try{let t={...this.createBaseRecord("user"),message:xs(e)};return this.turnParentUuids.push(t.parentUuid),this.appendRecord(t)}catch(t){throw Lt.error("Error saving user message:",t),t}}recordMidTurnUserMessage(e,t){try{let n={...this.createBaseRecord("user"),subtype:"mid_turn_user_message",message:xs(e),systemPayload:t?{displayText:t}:void 0};this.appendRecord(n)}catch(n){Lt.error("Error saving mid-turn user message:",n)}}recordCronPrompt(e,t){return this.recordNotificationLikeAcknowledged(e,"cron",t)}recordNotification(e,t){this.recordNotificationLike(e,"notification",t)}recordNotificationLike(e,t,n){this.recordNotificationLikeAcknowledged(e,t,n).catch(()=>{})}async recordNotificationLikeAcknowledged(e,t,n){try{let s={...this.createBaseRecord("user"),subtype:t,message:xs(e),systemPayload:n?{displayText:n}:void 0};return this.appendRecord(s)}catch(s){throw Lt.error(`Error saving ${t} record:`,s),s}}async recordAssistantTurn(e){try{let t={...this.createBaseRecord("assistant"),model:e.model};return e.message!==void 0&&(t.message=Hj(e.message)),e.tokens&&(t.usageMetadata=e.tokens),e.completionDisposition!==void 0&&(t.completionDisposition=e.completionDisposition),e.contextWindowSize!==void 0&&(t.contextWindowSize=e.contextWindowSize),await this.appendRecord(t),this.maybeTriggerAutoTitle(),t.uuid}catch(t){throw Lt.error("Error saving assistant turn:",t),t}}recordAssistantTurnDiscarded(e){try{this.appendRecord({...this.createBaseRecord("system"),subtype:"assistant_discarded",systemPayload:{assistantUuid:e}})}catch(t){Lt.error("Error saving assistant discard:",t)}}maybeTriggerAutoTitle(){if(this.currentCustomTitle||this.autoTitleController||this.autoTitleAttempts>=vme||Rme()||!this.config.isInteractive()&&!this.config.getExperimentalZedIntegration()||!this.config.getFastModel())return;this.autoTitleAttempts++;let t=new AbortController;this.autoTitleController=t,(async()=>{try{let n=await AW(this.config,t.signal);if(!n.ok||t.signal.aborted||this.currentTitleSource==="manual")return;try{let o=this.config.getSessionService().getSessionTitleInfo(this.config.getSessionId());if(o.source==="manual"){this.currentCustomTitle=o.title,this.currentTitleSource="manual";return}}catch{}this.recordCustomTitle(n.title,"auto")}catch(n){Lt.warn(`Auto-title generation failed: ${n instanceof Error?n.message:String(n)}`)}finally{this.autoTitleController===t&&(this.autoTitleController=void 0)}})()}recordToolResult(e,t,n){try{let s=this.createToolResultRecord(e,t,n);return this.appendRecord(s),s.uuid}catch(s){Lt.error("Error saving tool result:",s);return}}async recordToolResultCommitted(e,t,n){return this.appendRecord(this.createToolResultRecord(e,t,n))}createToolResultRecord(e,t,n){let s={...this.createBaseRecord("tool_result"),message:xs(e),...n?{supersededToolResultUuid:n}:{}};if(t){let o=Ame(t);if(typeof o.resultDisplay=="object"&&o.resultDisplay!==null&&"type"in o.resultDisplay&&o.resultDisplay.type==="task_execution"){let a=o.resultDisplay;s.toolCallResult={...o,resultDisplay:{...a,toolCalls:[]}}}else s.toolCallResult=o}return s}recordSlashCommand(e){try{let t={...this.createBaseRecord("system"),type:"system",subtype:"slash_command",systemPayload:e};this.appendRecord(t)}catch(t){Lt.error("Error saving slash command record:",t)}}recordGoalState(e){try{this.appendRecord({...this.createBaseRecord("system"),type:"system",subtype:"goal_state",systemPayload:e})}catch(t){Lt.error("Error saving goal state:",t)}}recordChatCompression(e){try{let t={...this.createBaseRecord("system"),type:"system",subtype:"chat_compression",systemPayload:e};this.appendRecord(t)}catch(t){Lt.error("Error saving chat compression record:",t)}}recordUiTelemetryEvent(e){try{let t={...this.createBaseRecord("system"),type:"system",subtype:"ui_telemetry",systemPayload:{uiEvent:e}};this.appendRecord(t)}catch(t){Lt.error("Error saving ui telemetry record:",t)}}async rewindRecording(e,t,n){try{let s=this.lastRecordUuid,o=this.turnParentUuids.length,a=this.lastAttributionSnapshotJson,l=this.turnParentUuids[e]??null,c={...this.createBaseRecord("system"),parentUuid:l,type:"system",subtype:"rewind",systemPayload:{...t,previousLeafUuid:s,selectedParentUuid:l,inheritActiveObligations:!1,...n?.length?{survivingFileHistorySnapshots:n.map(Ov)}:{}}},u=await this.appendRecord(c,void 0,{rollbackParentUuid:s});return this.turnParentUuids=[...this.turnParentUuids.slice(0,e),...this.turnParentUuids.slice(o)],this.lastAttributionSnapshotJson===a&&(this.lastAttributionSnapshotJson=void 0),u}catch(s){throw Lt.error("Error saving rewind record:",s),s}}rebuildTurnBoundaries(e){this.turnParentUuids=[];let t=this.config.getResumedSessionData()?.lastCompletedUuid!==void 0?null:this.lastRecordUuid;for(let n=0;n<e.length;n++){let s=e[n];s.type==="user"&&s.subtype!=="notification"&&s.subtype!=="cron"&&s.subtype!=="mid_turn_user_message"&&this.turnParentUuids.push(t),t=s.uuid}e.length>0&&(this.lastRecordUuid=e[e.length-1].uuid)}titleRecordedCallback;setTitleRecordedCallback(e){this.titleRecordedCallback=e}recordCustomTitle(e,t="manual"){try{let n=this.appendCustomTitle(e,t);return this.applyCustomTitle(e,t),n.then(()=>this.notifyCustomTitle(e,t),()=>{}),!0}catch(n){return Lt.error("Error saving custom title record:",n),!1}}async recordCustomTitleCommitted(e,t="manual",n={}){try{return await this.appendCustomTitle(e,t),this.applyCustomTitle(e,t),n.notifyObservers!==!1&&this.notifyCustomTitle(e,t),!0}catch(s){return Lt.error("Error saving custom title record:",s),!1}}appendCustomTitle(e,t){let n={...this.createBaseRecord("system"),type:"system",subtype:"custom_title",systemPayload:{customTitle:e,titleSource:t}};return this.appendRecord(n)}applyCustomTitle(e,t){this.currentCustomTitle=e,this.currentTitleSource=t}notifyCustomTitle(e,t){try{this.titleRecordedCallback?.(e,t)}catch{}}finalize(){if(this.autoTitleController)try{this.autoTitleController.abort()}catch{}if(this.currentCustomTitle)try{let e={...this.createBaseRecord("system"),type:"system",subtype:"custom_title",systemPayload:{customTitle:this.currentCustomTitle,...this.currentTitleSource?{titleSource:this.currentTitleSource}:{}}};this.appendRecord(e)}catch(e){Lt.error("Error finalizing session metadata:",e)}}recordAtCommand(e){try{let t={...this.createBaseRecord("system"),type:"system",subtype:"at_command",systemPayload:e};this.appendRecord(t)}catch(t){Lt.error("Error saving @-command record:",t)}}recordAttributionSnapshot(e){let t;try{if(this.cachedGitBranch=void 0,t=JSON.stringify(e),t===this.lastAttributionSnapshotJson)return;let n={...this.createBaseRecord("system"),type:"system",subtype:"attribution_snapshot",systemPayload:{snapshot:e}};this.lastAttributionSnapshotJson=t,this.appendRecord(n,()=>{this.lastAttributionSnapshotJson===t&&(this.lastAttributionSnapshotJson=void 0)})}catch(n){t!==void 0&&this.lastAttributionSnapshotJson===t&&(this.lastAttributionSnapshotJson=void 0),Lt.error("Error saving attribution snapshot:",n)}}recordFileHistorySnapshot(e){try{this.appendSerializedFileHistorySnapshotBatch([Ov(e)])}catch(t){Lt.error("Error saving file history snapshot:",t)}}recordFileHistorySnapshotBatch(e){if(e.length!==0)try{let t=e.map(Ov);this.appendSerializedFileHistorySnapshotBatch(t)}catch(t){Lt.error("Error saving file history snapshot batch:",t)}}appendSerializedFileHistorySnapshotBatch(e){try{let t={...this.createBaseRecord("system"),type:"system",subtype:"file_history_snapshot",systemPayload:{snapshots:e}};this.appendRecord(t)}catch(t){Lt.error("Error saving file history snapshot batch:",t)}}};g();g();g();var W0="**",VW="**";function KW(r){let e=r.indexOf(W0);if(e===-1)return{subject:"",description:r};let t=r.indexOf(VW,e+W0.length);if(t===-1)return{subject:"",description:r};let n=r.substring(e+W0.length,t).trim(),s=(r.substring(0,e)+r.substring(t+VW.length)).trim();return{subject:n,description:s}}function YW(r){if(r.candidates&&r.candidates.length>0){let e=r.candidates[0];if(e.content&&e.content.parts&&e.content.parts.length>0)return e.content.parts.filter(t=>t.thought).map(t=>t.text??"").join("")}return null}g();var JW=$("LEAKED_TOOL_MARKUP"),sh=/<\/?(?:arg_(?:key|value)|tool_call)\b/i,XW=Object.freeze(Array.from(new Set([...Object.values(R),"search_web","websearch","read_file","write_file","list_directory","list_dir","run_shell_command","shell","bash","grep_search","grep","glob","todo_write","ask_user_question"])).sort((r,e)=>e.length-r.length));function QW(r){let e=r.trim();if(!e)return null;let t=e.toLowerCase();for(let n of XW)if(t===n)return n;for(let n of XW)if(t.endsWith(n)&&t.length>n.length){let s=t.slice(0,t.length-n.length);if(/^[a-z]+$/i.test(s))return n}return/^[a-z][a-z0-9]*(?:_[a-z0-9]+)+$/.test(t)?t:null}function eG(r){let e={},t=/<arg_key>\s*([A-Za-z_][\w]*)\s*<\/arg_key>\s*<arg_value>([\s\S]*?)<\/arg_value>/gi,n,s=0;for(;(n=t.exec(r))!==null;){s+=1;let o=n[1],a=n[2].trim();if(typeof a=="string"&&(a.startsWith("{")||a.startsWith("[")||a==="true"||a==="false"||/^-?\d+(\.\d+)?$/.test(a)))try{a=JSON.parse(a)}catch{}e[o]=a}return s>0?e:null}var G0=/(?:<tool_call>\s*)?([A-Za-z_][\w]*)\s*((?:<arg_key>\s*[A-Za-z_][\w]*\s*<\/arg_key>\s*<arg_value>(?:(?!<arg_key>|<\/?tool_call>)[\s\S])*?<\/arg_value>\s*)+)<\/tool_call>/gi;function zv(r){let e=[];for(let t of r.matchAll(G0)){let n=t[1],s=QW(n),o=eG(t[2]);s&&o&&e.push({name:s,args:o,rawName:n,start:t.index,end:t.index+t[0].length})}return e}function ZW(r){if(!r||!sh.test(r))return{cleanText:r,recoveredCalls:[],hadMarkup:!1};let e=[],t=[];G0.lastIndex=0;let n;for(;(n=G0.exec(r))!==null;){let o=n[1],a=n[2],l=QW(o),c=eG(a),u=n.index,h=n.index+n[0].length;l&&c?(e.push({name:l,args:c,start:u,end:h,rawName:o}),t.push({start:u,end:h}),JW.debug(`recovered leaked tool call name=${l} raw=${o} keys=${Object.keys(c).join(",")}`)):(t.push({start:u,end:h}),JW.debug(`stripped unrecoverable leaked markup raw=${o} len=${h-u}`))}let s=r;if(t.length>0){let o=[...t].sort((a,l)=>l.start-a.start);for(let a of o)s=s.slice(0,a.start)+s.slice(a.end)}return sh.test(s)&&(s=s.replace(/<\/?tool_call\s*>/gi,"").replace(/<arg_key>\s*[A-Za-z_][\w]*\s*<\/arg_key>/gi,"").replace(/<arg_value>[\s\S]*?(?:<\/arg_value>|$)/gi,"").replace(/<\/?arg_(?:key|value)\b[^>]*>/gi,"")),s=s.replace(/[^\S\n]{2,}/g," ").replace(/[ \t]+\n/g,`
349
+ `)}function xme(r){let e=r.fileDiff.length,t=GW(r.originalContent),n=r.newContent.length,s=e+t+n,o=e>Cme,a=t>Bv,l=n>Bv;return s<=Sme&&!o&&!a&&!l?r:{...r,fileDiff:o?kme(r):r.fileDiff,originalContent:r.originalContent!==null&&a?WW(r.originalContent,Bv):r.originalContent,newContent:l?WW(r.newContent,Bv):r.newContent,truncatedForSession:!0,fileDiffLength:e,originalContentLength:t,newContentLength:n,fileDiffTruncated:o,originalContentTruncated:a,newContentTruncated:l}}function Ame(r){let e=r.resultDisplay;if(!Tme(e))return r;let t=xme(e);return t===e?r:{...r,resultDisplay:t}}function Rme(){let r=process.env.MATILDA_DISABLE_AUTO_TITLE;if(!r)return!1;let e=r.trim().toLowerCase();return e!==""&&e!=="0"&&e!=="false"&&e!=="no"&&e!=="off"}var Tm="thought_only_max_tokens",Ho="stream_recovery_snapshot",zc="stream_recovery_partial",nh=class{lastRecordUuid=null;config;turnParentUuids=[];cachedConversationFile;writeChain=Promise.resolve();transcriptWriterPromise;pendingRecords=new Set;transcriptCommitListeners=new Set;currentCustomTitle;currentTitleSource;autoTitleAttempts=0;autoTitleController;lastAttributionSnapshotJson;cachedGitBranch;bytesSinceTitleAnchor=0;constructor(e){if(this.config=e,this.lastRecordUuid=e.getResumedSessionData()?.lastCompletedUuid??null,e.getResumedSessionData())try{let n=e.getSessionService().getSessionTitleInfo(e.getSessionId());this.currentCustomTitle=n.title,this.currentTitleSource=n.source,this.finalize()}catch{}}getCurrentCustomTitle(){return this.currentCustomTitle}getCurrentTitleSource(){return this.currentTitleSource}getSessionId(){return this.config.getSessionId()}resolveConversationFile(){return this.cachedConversationFile?this.cachedConversationFile:(this.cachedConversationFile=this.config.getTranscriptPath(),this.cachedConversationFile)}createBaseRecord(e){let t=this.config.getProjectRoot(),n=qW({channel:this.config.getChannel?.(),contentGeneratorConfig:this.config.getContentGeneratorConfig?.()});return{uuid:bme(),parentUuid:this.lastRecordUuid,sessionId:this.getSessionId(),timestamp:new Date().toISOString(),type:e,cwd:t,version:this.config.getCliVersion()||"unknown",gitBranch:this.getCachedGitBranch(t),...n?{accountScopeId:n}:{}}}getCachedGitBranch(e){return(!this.cachedGitBranch||this.cachedGitBranch.cwd!==e)&&(this.cachedGitBranch={cwd:e,branch:Xd(e)}),this.cachedGitBranch.branch}async getTranscriptWriter(e){let t=this.transcriptWriterPromise??Bc.open(e,this.getSessionId());this.transcriptWriterPromise=t;try{return await t}catch(n){throw this.transcriptWriterPromise===t&&(this.transcriptWriterPromise=void 0),n}}appendRecord(e,t,n){let s;try{s=this.resolveConversationFile()}catch(a){throw Lt.error("Error appending record:",a),a}n?.updateActiveTail!==!1&&(this.lastRecordUuid=e.uuid),this.pendingRecords.add(e);let o=this.writeChain.then(()=>this.getTranscriptWriter(s).then(a=>a.append(e))).then(a=>{for(let l of this.transcriptCommitListeners)try{l({writerEpoch:a.writerEpoch,committedPosition:a.committedPosition,selectedLeafUuid:a.recordUuid})}catch(c){Lt.warn("Transcript commit observer failed:",c)}return a}).catch(a=>{let l=n&&"rollbackParentUuid"in n?n.rollbackParentUuid??null:e.parentUuid;this.lastRecordUuid===e.uuid&&(this.lastRecordUuid=l),this.turnParentUuids=this.turnParentUuids.map(c=>c===e.uuid?l:c);for(let c of this.pendingRecords)c.parentUuid===e.uuid&&(c.parentUuid=l);if(Lt.error("Error appending record (async):",a),t)try{t(a)}catch(c){Lt.error("appendRecord onError callback threw:",c)}throw a}).finally(()=>{this.pendingRecords.delete(e)});return this.writeChain=o.then(()=>{},()=>{}),n?.updateTitleAnchor!==!1&&this.updateTitleAnchorTracking(e),o}updateTitleAnchorTracking(e){if(e.type==="system"&&e.subtype==="custom_title"){this.bytesSinceTitleAnchor=0;return}this.currentCustomTitle&&(this.bytesSinceTitleAnchor+=Buffer.byteLength(JSON.stringify(e),"utf8")+1,this.bytesSinceTitleAnchor>=Eme&&this.reanchorTitle())}reanchorTitle(){if(this.currentCustomTitle)try{let e={...this.createBaseRecord("system"),type:"system",subtype:"custom_title",systemPayload:{customTitle:this.currentCustomTitle,...this.currentTitleSource?{titleSource:this.currentTitleSource}:{}}};this.appendRecord(e,void 0,{updateActiveTail:!1})}catch(e){this.bytesSinceTitleAnchor=0,Lt.error("Error re-anchoring custom title:",e)}}async flush(){await this.writeChain}subscribeToTranscriptCommits(e){return this.transcriptCommitListeners.add(e),()=>{this.transcriptCommitListeners.delete(e)}}readTranscript(e){let t=this.writeChain.then(async()=>{let n=await this.getTranscriptWriter(this.resolveConversationFile());return wW(await n.readRecords(),e)});return this.writeChain=t.then(()=>{},()=>{}),t}async releaseTranscriptOwnership(){await this.flush();let e=this.transcriptWriterPromise;if(this.transcriptWriterPromise=void 0,!e)return;let t=await e.catch(()=>{});t&&await t.close()}resetStoragePaths(){this.cachedConversationFile=void 0}recordUserMessage(e){try{let t={...this.createBaseRecord("user"),message:xs(e)};return this.turnParentUuids.push(t.parentUuid),this.appendRecord(t)}catch(t){throw Lt.error("Error saving user message:",t),t}}recordMidTurnUserMessage(e,t){try{let n={...this.createBaseRecord("user"),subtype:"mid_turn_user_message",message:xs(e),systemPayload:t?{displayText:t}:void 0};this.appendRecord(n)}catch(n){Lt.error("Error saving mid-turn user message:",n)}}recordCronPrompt(e,t){return this.recordNotificationLikeAcknowledged(e,"cron",t)}recordNotification(e,t){return this.recordNotificationLikeAcknowledged(e,"notification",t)}async recordNotificationLikeAcknowledged(e,t,n){try{let s={...this.createBaseRecord("user"),subtype:t,message:xs(e),systemPayload:n?{displayText:n}:void 0};return this.appendRecord(s)}catch(s){throw Lt.error(`Error saving ${t} record:`,s),s}}async recordAssistantTurn(e){try{let t={...this.createBaseRecord("assistant"),model:e.model};return e.message!==void 0&&(t.message=Hj(e.message)),e.tokens&&(t.usageMetadata=e.tokens),e.completionDisposition!==void 0&&(t.completionDisposition=e.completionDisposition),e.contextWindowSize!==void 0&&(t.contextWindowSize=e.contextWindowSize),await this.appendRecord(t),this.maybeTriggerAutoTitle(),t.uuid}catch(t){throw Lt.error("Error saving assistant turn:",t),t}}recordAssistantTurnDiscarded(e){try{this.appendRecord({...this.createBaseRecord("system"),subtype:"assistant_discarded",systemPayload:{assistantUuid:e}})}catch(t){Lt.error("Error saving assistant discard:",t)}}maybeTriggerAutoTitle(){if(this.currentCustomTitle||this.autoTitleController||this.autoTitleAttempts>=vme||Rme()||!this.config.isInteractive()&&!this.config.getExperimentalZedIntegration()||!this.config.getFastModel())return;this.autoTitleAttempts++;let t=new AbortController;this.autoTitleController=t,(async()=>{try{let n=await AW(this.config,t.signal);if(!n.ok||t.signal.aborted||this.currentTitleSource==="manual")return;try{let o=this.config.getSessionService().getSessionTitleInfo(this.config.getSessionId());if(o.source==="manual"){this.currentCustomTitle=o.title,this.currentTitleSource="manual";return}}catch{}this.recordCustomTitle(n.title,"auto")}catch(n){Lt.warn(`Auto-title generation failed: ${n instanceof Error?n.message:String(n)}`)}finally{this.autoTitleController===t&&(this.autoTitleController=void 0)}})()}recordToolResult(e,t,n){try{let s=this.createToolResultRecord(e,t,n);return this.appendRecord(s),s.uuid}catch(s){Lt.error("Error saving tool result:",s);return}}async recordToolResultCommitted(e,t,n){return this.appendRecord(this.createToolResultRecord(e,t,n))}createToolResultRecord(e,t,n){let s={...this.createBaseRecord("tool_result"),message:xs(e),...n?{supersededToolResultUuid:n}:{}};if(t){let o=Ame(t);if(typeof o.resultDisplay=="object"&&o.resultDisplay!==null&&"type"in o.resultDisplay&&o.resultDisplay.type==="task_execution"){let a=o.resultDisplay;s.toolCallResult={...o,resultDisplay:{...a,toolCalls:[]}}}else s.toolCallResult=o}return s}recordSlashCommand(e){try{let t={...this.createBaseRecord("system"),type:"system",subtype:"slash_command",systemPayload:e};this.appendRecord(t)}catch(t){Lt.error("Error saving slash command record:",t)}}recordGoalState(e){try{this.appendRecord({...this.createBaseRecord("system"),type:"system",subtype:"goal_state",systemPayload:e})}catch(t){Lt.error("Error saving goal state:",t)}}recordChatCompression(e){try{let t={...this.createBaseRecord("system"),type:"system",subtype:"chat_compression",systemPayload:e};this.appendRecord(t)}catch(t){Lt.error("Error saving chat compression record:",t)}}recordUiTelemetryEvent(e){try{let t={...this.createBaseRecord("system"),type:"system",subtype:"ui_telemetry",systemPayload:{uiEvent:e}};this.appendRecord(t)}catch(t){Lt.error("Error saving ui telemetry record:",t)}}async rewindRecording(e,t,n){try{let s=this.lastRecordUuid,o=this.turnParentUuids.length,a=this.lastAttributionSnapshotJson,l=this.turnParentUuids[e]??null,c={...this.createBaseRecord("system"),parentUuid:l,type:"system",subtype:"rewind",systemPayload:{...t,previousLeafUuid:s,selectedParentUuid:l,inheritActiveObligations:!1,...n?.length?{survivingFileHistorySnapshots:n.map(Ov)}:{}}},u=await this.appendRecord(c,void 0,{rollbackParentUuid:s});return this.turnParentUuids=[...this.turnParentUuids.slice(0,e),...this.turnParentUuids.slice(o)],this.lastAttributionSnapshotJson===a&&(this.lastAttributionSnapshotJson=void 0),u}catch(s){throw Lt.error("Error saving rewind record:",s),s}}rebuildTurnBoundaries(e){this.turnParentUuids=[];let t=this.config.getResumedSessionData()?.lastCompletedUuid!==void 0?null:this.lastRecordUuid;for(let n=0;n<e.length;n++){let s=e[n];s.type==="user"&&s.subtype!=="notification"&&s.subtype!=="cron"&&s.subtype!=="mid_turn_user_message"&&this.turnParentUuids.push(t),t=s.uuid}e.length>0&&(this.lastRecordUuid=e[e.length-1].uuid)}titleRecordedCallback;setTitleRecordedCallback(e){this.titleRecordedCallback=e}recordCustomTitle(e,t="manual"){try{let n=this.appendCustomTitle(e,t);return this.applyCustomTitle(e,t),n.then(()=>this.notifyCustomTitle(e,t),()=>{}),!0}catch(n){return Lt.error("Error saving custom title record:",n),!1}}async recordCustomTitleCommitted(e,t="manual",n={}){try{return await this.appendCustomTitle(e,t),this.applyCustomTitle(e,t),n.notifyObservers!==!1&&this.notifyCustomTitle(e,t),!0}catch(s){return Lt.error("Error saving custom title record:",s),!1}}appendCustomTitle(e,t){let n={...this.createBaseRecord("system"),type:"system",subtype:"custom_title",systemPayload:{customTitle:e,titleSource:t}};return this.appendRecord(n)}applyCustomTitle(e,t){this.currentCustomTitle=e,this.currentTitleSource=t}notifyCustomTitle(e,t){try{this.titleRecordedCallback?.(e,t)}catch{}}finalize(){if(this.autoTitleController)try{this.autoTitleController.abort()}catch{}if(this.currentCustomTitle)try{let e={...this.createBaseRecord("system"),type:"system",subtype:"custom_title",systemPayload:{customTitle:this.currentCustomTitle,...this.currentTitleSource?{titleSource:this.currentTitleSource}:{}}};this.appendRecord(e)}catch(e){Lt.error("Error finalizing session metadata:",e)}}recordAtCommand(e){try{let t={...this.createBaseRecord("system"),type:"system",subtype:"at_command",systemPayload:e};this.appendRecord(t)}catch(t){Lt.error("Error saving @-command record:",t)}}recordAttributionSnapshot(e){let t;try{if(this.cachedGitBranch=void 0,t=JSON.stringify(e),t===this.lastAttributionSnapshotJson)return;let n={...this.createBaseRecord("system"),type:"system",subtype:"attribution_snapshot",systemPayload:{snapshot:e}};this.lastAttributionSnapshotJson=t,this.appendRecord(n,()=>{this.lastAttributionSnapshotJson===t&&(this.lastAttributionSnapshotJson=void 0)})}catch(n){t!==void 0&&this.lastAttributionSnapshotJson===t&&(this.lastAttributionSnapshotJson=void 0),Lt.error("Error saving attribution snapshot:",n)}}recordFileHistorySnapshot(e){try{this.appendSerializedFileHistorySnapshotBatch([Ov(e)])}catch(t){Lt.error("Error saving file history snapshot:",t)}}recordFileHistorySnapshotBatch(e){if(e.length!==0)try{let t=e.map(Ov);this.appendSerializedFileHistorySnapshotBatch(t)}catch(t){Lt.error("Error saving file history snapshot batch:",t)}}appendSerializedFileHistorySnapshotBatch(e){try{let t={...this.createBaseRecord("system"),type:"system",subtype:"file_history_snapshot",systemPayload:{snapshots:e}};this.appendRecord(t)}catch(t){Lt.error("Error saving file history snapshot batch:",t)}}};g();g();g();var W0="**",VW="**";function KW(r){let e=r.indexOf(W0);if(e===-1)return{subject:"",description:r};let t=r.indexOf(VW,e+W0.length);if(t===-1)return{subject:"",description:r};let n=r.substring(e+W0.length,t).trim(),s=(r.substring(0,e)+r.substring(t+VW.length)).trim();return{subject:n,description:s}}function YW(r){if(r.candidates&&r.candidates.length>0){let e=r.candidates[0];if(e.content&&e.content.parts&&e.content.parts.length>0)return e.content.parts.filter(t=>t.thought).map(t=>t.text??"").join("")}return null}g();var JW=$("LEAKED_TOOL_MARKUP"),sh=/<\/?(?:arg_(?:key|value)|tool_call)\b/i,XW=Object.freeze(Array.from(new Set([...Object.values(R),"search_web","websearch","read_file","write_file","list_directory","list_dir","run_shell_command","shell","bash","grep_search","grep","glob","todo_write","ask_user_question"])).sort((r,e)=>e.length-r.length));function QW(r){let e=r.trim();if(!e)return null;let t=e.toLowerCase();for(let n of XW)if(t===n)return n;for(let n of XW)if(t.endsWith(n)&&t.length>n.length){let s=t.slice(0,t.length-n.length);if(/^[a-z]+$/i.test(s))return n}return/^[a-z][a-z0-9]*(?:_[a-z0-9]+)+$/.test(t)?t:null}function eG(r){let e={},t=/<arg_key>\s*([A-Za-z_][\w]*)\s*<\/arg_key>\s*<arg_value>([\s\S]*?)<\/arg_value>/gi,n,s=0;for(;(n=t.exec(r))!==null;){s+=1;let o=n[1],a=n[2].trim();if(typeof a=="string"&&(a.startsWith("{")||a.startsWith("[")||a==="true"||a==="false"||/^-?\d+(\.\d+)?$/.test(a)))try{a=JSON.parse(a)}catch{}e[o]=a}return s>0?e:null}var G0=/(?:<tool_call>\s*)?([A-Za-z_][\w]*)\s*((?:<arg_key>\s*[A-Za-z_][\w]*\s*<\/arg_key>\s*<arg_value>(?:(?!<arg_key>|<\/?tool_call>)[\s\S])*?<\/arg_value>\s*)+)<\/tool_call>/gi;function zv(r){let e=[];for(let t of r.matchAll(G0)){let n=t[1],s=QW(n),o=eG(t[2]);s&&o&&e.push({name:s,args:o,rawName:n,start:t.index,end:t.index+t[0].length})}return e}function ZW(r){if(!r||!sh.test(r))return{cleanText:r,recoveredCalls:[],hadMarkup:!1};let e=[],t=[];G0.lastIndex=0;let n;for(;(n=G0.exec(r))!==null;){let o=n[1],a=n[2],l=QW(o),c=eG(a),u=n.index,h=n.index+n[0].length;l&&c?(e.push({name:l,args:c,start:u,end:h,rawName:o}),t.push({start:u,end:h}),JW.debug(`recovered leaked tool call name=${l} raw=${o} keys=${Object.keys(c).join(",")}`)):(t.push({start:u,end:h}),JW.debug(`stripped unrecoverable leaked markup raw=${o} len=${h-u}`))}let s=r;if(t.length>0){let o=[...t].sort((a,l)=>l.start-a.start);for(let a of o)s=s.slice(0,a.start)+s.slice(a.end)}return sh.test(s)&&(s=s.replace(/<\/?tool_call\s*>/gi,"").replace(/<arg_key>\s*[A-Za-z_][\w]*\s*<\/arg_key>/gi,"").replace(/<arg_value>[\s\S]*?(?:<\/arg_value>|$)/gi,"").replace(/<\/?arg_(?:key|value)\b[^>]*>/gi,"")),s=s.replace(/[^\S\n]{2,}/g," ").replace(/[ \t]+\n/g,`
350
350
  `).replace(/\n{3,}/g,`
351
351
 
352
352
  `),{cleanText:s.trimEnd(),recoveredCalls:e.map(({name:o,args:a})=>({name:o,args:a})),hadMarkup:!0}}var jv=class{buffer="";push(e,t=!1){if(this.buffer+=e,!t&&this.hasIncompleteMarkup(this.buffer)){let s=this.incompleteMarkupStart(this.buffer);if(s<=0)return{cleanText:"",recoveredCalls:[],hadMarkup:!1};let o=this.buffer.slice(0,s);return this.buffer=this.buffer.slice(s),ZW(o)}let n=ZW(this.buffer);return this.buffer="",n}reset(){this.buffer=""}hasIncompleteMarkup(e){if(!sh.test(e)&&!/<tool_call\b/i.test(e))return!!/[A-Za-z_][\w]*<\s*(?:a(?:r(?:g(?:_(?:k(?:e(?:y)?)?)?)?)?)?)?$/i.test(e);let t=(e.match(/<arg_key\b/gi)??[]).length,n=(e.match(/<\/arg_key>/gi)??[]).length,s=(e.match(/<arg_value\b/gi)??[]).length,o=(e.match(/<\/arg_value>/gi)??[]).length,a=(e.match(/<tool_call\b/gi)??[]).length,l=(e.match(/<\/tool_call>/gi)??[]).length;return!!(t>n||s>o||a>l||/<(?:\/?(?:arg_(?:key|value)?|tool_call?)?)?$/i.test(e))}incompleteMarkupStart(e){let t=[],n=e.lastIndexOf("<tool_call");n>=0&&t.push(n);let s=e.search(/[A-Za-z_][\w]*\s*<arg_key\b/i);s>=0&&t.push(s);let o=e.lastIndexOf("<arg_key");o>=0&&t.push(o);let a=e.search(/<\s*(?:a(?:r(?:g(?:_(?:k(?:e(?:y)?)?)?)?)?)?)?$/i);return a>=0&&t.push(a),t.length===0?e.length:Math.min(...t)}};var V0=(b=>(b.Content="content",b.ToolCallRequest="tool_call_request",b.ToolCallResponse="tool_call_response",b.ToolCallConfirmation="tool_call_confirmation",b.UserCancelled="user_cancelled",b.Error="error",b.ChatCompressed="chat_compressed",b.Thought="thought",b.MaxSessionTurns="max_session_turns",b.SessionTokenLimitExceeded="session_token_limit_exceeded",b.Finished="finished",b.LoopDetected="loop_detected",b.Citation="citation",b.Retry="retry",b.HookSystemMessage="hook_system_message",b.UserPromptSubmitBlocked="user_prompt_submit_blocked",b.StopHookLoop="stop_hook_loop",b.ActiveGoal="active_goal",b))(V0||{}),qc=(l=>(l[l.COMPRESSED=1]="COMPRESSED",l[l.COMPRESSION_FAILED_INFLATED_TOKEN_COUNT=2]="COMPRESSION_FAILED_INFLATED_TOKEN_COUNT",l[l.COMPRESSION_FAILED_TOKEN_COUNT_ERROR=3]="COMPRESSION_FAILED_TOKEN_COUNT_ERROR",l[l.COMPRESSION_FAILED_SIDE_QUERY=4]="COMPRESSION_FAILED_SIDE_QUERY",l[l.COMPRESSION_FAILED_EMPTY_SUMMARY=5]="COMPRESSION_FAILED_EMPTY_SUMMARY",l[l.NOOP=6]="NOOP",l[l.COMPRESSION_FAILED_OUTPUT_TRUNCATED=7]="COMPRESSION_FAILED_OUTPUT_TRUNCATED",l))(qc||{}),Bo=class{constructor(e,t){this.chat=e;this.prompt_id=t}pendingToolCalls=[];pendingCitations=new Set;finishReason=void 0;currentResponseId;leakedToolMarkupParser=new jv;async*run(e,t,n){try{let s=await this.chat.sendMessageStream(e,{message:t,config:{abortSignal:n}},this.prompt_id);for await(let o of s){if(n?.aborted){yield{type:"user_cancelled"};return}if(o.type==="retry"){this.pendingToolCalls.length=0,this.pendingCitations.clear(),this.finishReason=void 0,o.isContinuation||this.leakedToolMarkupParser.reset(),yield{type:"retry",retryInfo:o.retryInfo,isContinuation:o.isContinuation};continue}if(o.type==="compressed"){yield{type:"chat_compressed",value:o.info};continue}let a=o.value;if(!a)continue;if(av(a)){this.pendingToolCalls.length=0,this.pendingCitations.clear(),this.finishReason=void 0,this.leakedToolMarkupParser.reset(),yield{type:"retry",isContinuation:!1};continue}a.responseId&&(this.currentResponseId=a.responseId);let l=YW(a);l&&(yield{type:"thought",value:KW(l)});let c=Fc(a),u=a.candidates?.[0]?.finishReason;if(c){let d=this.leakedToolMarkupParser.push(c);d.cleanText&&(yield{type:"content",value:d.cleanText})}let h=a.functionCalls??[];for(let d of h){let f=this.handlePendingFunctionCall(d);f&&(yield f)}for(let d of Pme(a))this.pendingCitations.add(d);if(u){if(u===Gr.MAX_TOKENS)for(let d of this.pendingToolCalls)d.wasOutputTruncated=!0;this.pendingCitations.size>0&&(yield{type:"citation",value:`Citations:
@@ -1316,7 +1316,7 @@ Stage 1 flagged this as potentially unsafe. Review carefully \u2014 false positi
1316
1316
  `)}function _4(r,e,t){let n=t.getTool(r),s=e&&typeof e=="object"?e:{},o;if(n)try{o=n.toAutoClassifierInput(s)}catch{o=void 0}return o===""?{}:o&&typeof o=="object"?o:s}var Jm=$("CLASSIFIER"),G_e=1e4,V_e=3e4,K_e={type:"object",required:["shouldBlock"],additionalProperties:!1,properties:{shouldBlock:{type:"boolean"}}},Y_e={type:"object",required:["thinking","shouldBlock","reason"],additionalProperties:!1,properties:{thinking:{type:"string"},shouldBlock:{type:"boolean"},reason:{type:"string"}}};async function S4(r){let e=Date.now(),t,n;try{t=w4(r.messages,r.config.getToolRegistry(),{toolName:r.toolName,toolParams:r.toolParams}),n=m4(r.config)}catch(h){return v4("Classifier prompt construction failed",h,"fast",e,r.config)}let s=n+g4,o=J_e(r.config),a=AbortSignal.any([r.signal,AbortSignal.timeout(o.stage1TimeoutMs)]),l;try{l=await Wt(r.config,{contents:t,schema:K_e,systemInstruction:s,abortSignal:a,purpose:"permission_classifier_stage1",maxAttempts:2,config:{temperature:0,maxOutputTokens:32,thinkingConfig:{includeThoughts:!1}}})}catch(h){if(r.signal.aborted)throw h;return v4("Classifier stage 1 unavailable",h,"fast",e,r.config)}if(!l.shouldBlock)return Jm.debug(`ALLOW stage=fast tool=${r.toolName} durationMs=${Date.now()-e}`),{shouldBlock:!1,reason:"",model:DS(r.config),durationMs:Date.now()-e,stage:"fast"};let c=AbortSignal.any([r.signal,AbortSignal.timeout(o.stage2TimeoutMs)]),u;try{u=await Wt(r.config,{contents:t,schema:Y_e,systemInstruction:n+y4,abortSignal:c,purpose:"permission_classifier_stage2",maxAttempts:2,config:{temperature:0,maxOutputTokens:4096,thinkingConfig:{includeThoughts:o.stage2ThinkingEnabled}}})}catch(h){if(r.signal.aborted)throw h;return Jm.warn(`Stage 2 review unavailable (durationMs=${Date.now()-e}): ${C4(h)}`),{shouldBlock:!0,reason:"Stage 1 flagged this as risky; stage 2 review was unavailable.",unavailable:!0,model:DS(r.config),durationMs:Date.now()-e,stage:"thinking"}}return Jm.debug(`${u.shouldBlock?"BLOCK":"ALLOW"} stage=thinking tool=${r.toolName} durationMs=${Date.now()-e}`),{shouldBlock:u.shouldBlock,reason:u.shouldBlock?X_e(u.reason):"",thinking:u.thinking,model:DS(r.config),durationMs:Date.now()-e,stage:"thinking"}}function J_e(r){let e=r.getAutoModeSettings().classifier;return{stage1TimeoutMs:b4(e?.timeouts?.stage1Ms,G_e),stage2TimeoutMs:b4(e?.timeouts?.stage2Ms,V_e),stage2ThinkingEnabled:e?.thinking?.stage2Enabled===!0}}function b4(r,e){return typeof r=="number"&&Number.isFinite(r)&&r>0&&r<1e3&&Jm.warn(`Classifier timeout ${r}ms below 1000ms floor, using default ${e}ms`),typeof r=="number"&&Number.isFinite(r)&&r>=1e3?r:e}function X_e(r){if(!r)return r;let e=r;for(let t=0;t<8;t++){let n=e.replace(/<[^>]*>/g,"");if(n===e)break;e=n}return e.replace(/\s+/g," ").trim().slice(0,200)}function v4(r,e,t,n,s){let o=vG(e)?"Conversation transcript exceeds classifier context window":`${r} - blocked for safety`;return Jm.warn(`failClosed stage=${t} durationMs=${Date.now()-n} reason="${o}" cause="${C4(e)}"`),{shouldBlock:!0,reason:o,unavailable:!0,model:DS(s),durationMs:Date.now()-n,stage:t}}function C4(r){if(r instanceof Error)return`${r.name}: ${r.message}`;try{return String(r)}catch{return"<unstringifiable error>"}}function DS(r){return r.getFastModel?.()??r.getModel()??"unknown"}g();var LS={maxConsecutiveBlock:3,maxConsecutiveUnavailable:2,maxTotalDenials:20};function E4(r){return r.totalBlock+r.totalUnavailable>=LS.maxTotalDenials}function Xm(){return{consecutiveBlock:0,consecutiveUnavailable:0,totalBlock:0,totalUnavailable:0}}function ru(r){return`consecutiveBlock=${r.consecutiveBlock}, consecutiveUnavailable=${r.consecutiveUnavailable}, totalBlock=${r.totalBlock}, totalUnavailable=${r.totalUnavailable}`}function YM(r){return r==="consecutive_block"||r==="consecutive_unavailable"||r==="total_denial"}function gh(r){return r.consecutiveBlock===0&&r.consecutiveUnavailable===0?r:{...r,consecutiveBlock:0,consecutiveUnavailable:0}}function JM(r){return{consecutiveBlock:r.consecutiveBlock+1,consecutiveUnavailable:0,totalBlock:r.totalBlock+1,totalUnavailable:r.totalUnavailable}}function XM(r){return{consecutiveBlock:0,consecutiveUnavailable:r.consecutiveUnavailable+1,totalBlock:r.totalBlock,totalUnavailable:r.totalUnavailable+1}}function NS(r){return E4(r)?{fallback:!0,reason:"total_denial"}:r.consecutiveBlock>=LS.maxConsecutiveBlock?{fallback:!0,reason:"consecutive_block"}:r.consecutiveUnavailable>=LS.maxConsecutiveUnavailable?{fallback:!0,reason:"consecutive_unavailable"}:{fallback:!1}}function ZM(r){return E4(r)?Xm():r.consecutiveBlock===0&&r.consecutiveUnavailable===0?r:{...r,consecutiveBlock:0,consecutiveUnavailable:0}}function QM(r){return r==="proceed_once"||r==="proceed_always"||r==="proceed_always_project"||r==="proceed_always_user"||r==="modify_with_editor"}function eI(){return Xm()}var Z_e=$("AUTO_MODE"),Q_e=/\b(?:cp|mv|install|rsync|patch|perl|sed|tee|dd|sort|awk|gawk|node|python3?|ruby|php|curl|wget|tar|unzip|cpio)\b/,x4=new Set([R.READ_FILE,R.GREP,R.GLOB,R.LS,R.LSP,R.TOOL_SEARCH,R.TODO_WRITE,R.STRUCTURED_OUTPUT,R.ASK_USER_QUESTION,R.EXIT_PLAN_MODE,R.ENTER_PLAN_MODE,R.CRON_LIST,R.TASK_STOP]);function A4(r){return x4.has(r)}var ebe=new Set([R.EDIT,R.WRITE_FILE]),tbe=new Set([R.EDIT,R.WRITE_FILE,R.NOTEBOOK_EDIT]),rbe=new Set([R.SHELL,R.MONITOR]);function nI(r,e){return!(r!=="auto"||e===R.ASK_USER_QUESTION||e===R.EXIT_PLAN_MODE||e===R.ENTER_PLAN_MODE)}var nbe=Object.freeze([/(^|\/)\.git(?:\/|$)/,/(^|\/)\.husky\//,/(^|\/)package\.json$/,/(^|\/)\.npmrc$/,/(^|\/)(makefile|gnumakefile)$/,/(^|\/)\.?justfile$/,/(^|\/)taskfile\.ya?ml$/,/(^|\/)\.github\/workflows\//]),sbe=Object.freeze([/(^|\/)\.matilda\/settings(?:\.[^/]*)?\.json$/,/(^|\/)(matilda|agents)\.md$/,/(^|\/)\.matilda\/matilda\.local\.md$/,/(^|\/)\.matilda\/rules(?:\/|$)/,/(^|\/)\.matilda\/commands(?:\/|$)/,/(^|\/)\.matilda\/agents(?:\/|$)/,/(^|\/)\.matilda\/skills(?:\/|$)/,/(^|\/)\.matilda\/hooks(?:\/|$)/,/(^|\/)\.mcp\.json$/]);function sI(r){return r.replace(/\\/g,"/").toLowerCase()}function ibe(r){let e=0,t=r.length;for(;e<t&&r[e]==="/";)e++;for(;t>e&&r[t-1]==="/";)t--;return r.slice(e,t)}function obe(r){return[...Ec(),Cc].some(e=>{let t=ibe(sI(e));return t?r===t||r.endsWith(`/${t}`):!1})}var T4,tI;function abe(){let r=process.env.MATILDA_HOME;if(!r)return[];if(T4===r&&tI!==void 0)return tI;let e=new Set([ol.resolve(r)]);(r.startsWith("/")||/^[A-Za-z]:[\\/]/.test(r))&&e.add(r);try{e.add(rI.realpathSync.native(r))}catch{}let t=[...e].map(n=>sI(n).replace(/\/+$/,""));return T4=r,tI=t,t}function lbe(r){for(let e of abe()){let t=`${e}/`;if(!r.startsWith(t))continue;let n=r.slice(t.length);if(/^settings(?:\.[^/]*)?\.json$/.test(n)||/^matilda\.local\.md$/.test(n)||/^\.mcp\.json$/.test(n)||/^(rules|commands|agents|skills|hooks)(?:\/|$)/.test(n))return!0}return!1}function cbe(r){let e=new Set([r]);try{e.add(rI.realpathSync.native(r))}catch{let t=ol.dirname(r);try{e.add(ol.join(rI.realpathSync.native(t),ol.basename(r)))}catch{}}return[...e]}function Zm(r){return cbe(r).some(e=>{let t=sI(e);return obe(t)||lbe(t)||nbe.some(n=>n.test(t))||sbe.some(n=>n.test(t))})}function FS(r,e=process.cwd()){if(tbe.has(r.toolName)&&r.filePath&&Zm(r.filePath))return!0;if(!rbe.has(r.toolName)||!r.command)return!1;let t=r.toolName===R.MONITOR?CS(r.command).safetyCommand:r.command,n=r.cwd??e;return ube(t,n)||dbe(t,n)?!0:sl(t,n).some(s=>s.virtualTool!==R.EDIT&&s.virtualTool!==R.WRITE_FILE?!1:s.cwdUnknown&&s.pathMayDependOnCwd?!0:!!(s.filePath&&Zm(s.filePath)))}function ube(r,e){for(let t=0;t<r.length;t++){if(r[t]!==">")continue;for(;r[t]===">"||r[t]==="|"||r[t]==="&";)t++;for(;r[t]===" "||r[t]===" ";)t++;let n="";for(;t<r.length;){let a=r[t];if(/\s|[;&|]/.test(a))break;n+=a,t++}let s=R4(n);if(!s||s.startsWith("&"))continue;let o=ol.isAbsolute(s)?s:ol.join(e,s);if(Zm(o))return!0}return!1}function dbe(r,e){for(let t of r.split(`
1317
1317
  `))if(Q_e.test(t)&&!(/\b(?:sed|perl)\b/.test(t)&&!/(?:^|\s)(?:-[A-Za-z]*i|--in-place(?:=|\s|$))/.test(t)))for(let n of t.split(/\s+/)){let s=R4(n).replace(/^[({]+|[),;]+$/g,"");for(let o of hbe(s,t))if(/\$[{(A-Za-z_]/.test(o)||pbe(o,e))return!0}return!1}function hbe(r,e){if(!r)return[];let t=fbe(r,e);return t?[t]:r.startsWith("-")?[]:[r]}function fbe(r,e){let t=r.indexOf("=");if(r.startsWith("--directory=")&&/\btar\b/.test(e)&&t>2||r.startsWith("--output=")&&/\bpatch\b/.test(e)&&t>2)return r.slice(t+1);for(let{flag:n,command:s}of[{flag:"-C",command:/\btar\b/},{flag:"-d",command:/\bunzip\b/},{flag:"-D",command:/\bcpio\b/},{flag:"-o",command:/\b(?:curl|sort|patch)\b/},{flag:"-O",command:/\bwget\b/},{flag:"-t",command:/\b(?:cp|mv|install|ln)\b/}])if(s.test(e)&&r.startsWith(n)&&r.length>2)return r.slice(n.length).replace(/^=/,"")}function pbe(r,e){for(let t of r.match(/[A-Za-z0-9_./~-]+/g)??[]){let n=ol.isAbsolute(t)?t:ol.join(e,t);if(Zm(n))return!0}return!1}function R4(r){let e=0,t=r.length;for(;e<t&&(r[e]==="'"||r[e]==='"'||r[e]==="$")&&!(r[e]==="$"&&r[e+1]!=="'");)e++;for(;t>e;){let n=r[t-1];if(n!=="'"&&n!=='"'&&n!==")"&&n!=="}"&&n!=="&")break;t--}return r.slice(e,t)}function P4(r,e){return!ebe.has(r.toolName)||!r.filePath||Zm(r.filePath)?!1:e.getWorkspaceContext().isPathWithinWorkspace(r.filePath)}function $S(r,e,t){switch(r.via){case"fast-path:accept-edits":case"fast-path:allowlist":return e.setAutoModeDenialState(gh(t)),{kind:"approved"};case"classifier":return r.shouldBlock?(e.setAutoModeDenialState(r.unavailable?XM(t):JM(t)),{kind:"blocked",errorMessage:M4(r),reason:r.unavailable?"classifier_unavailable":"classifier_blocked"}):(e.setAutoModeDenialState(gh(t)),{kind:"approved"});case"fallback":return{kind:"fallback",reason:r.reason};default:{let n=r;return Z_e.error(`Auto mode: unrecognised decision.via "${r.via}" \u2014 falling through to manual approval`),{kind:"fallback",reason:"safety_check"}}}}function US(r,e){return r.via==="classifier"&&r.shouldBlock&&e.kind==="blocked"}function HS(r){return r.unavailable?"classifier_unavailable":"classifier_blocked"}var k4="Do not try to complete the denied action through another tool, shell indirection, generated script, alias, symlink, config change, hook, command file, MCP configuration, encoded payload, or equivalent path. If that action is required, stop and ask the user for explicit approval. You may continue with unrelated safe work or a genuinely safer alternative that does not accomplish the denied action.";function M4(r){return r.unavailable?`${r.reason?`Auto mode classifier unavailable (${r.reason}); action blocked for safety`:"Auto mode classifier unavailable; action blocked for safety"}
1318
1318
  ${k4}`:`Blocked by auto mode policy: ${r.reason}
1319
- ${k4}`}async function BS(r){if(!r.pmForcedAsk&&P4(r.ctx,r.config))return{via:"fast-path:accept-edits"};if(!r.pmForcedAsk&&A4(r.ctx.toolName))return{via:"fast-path:allowlist"};if(r.pmForcedAsk)return{via:"fallback",reason:"ask_rule"};if(r.skipClassifierReason)return{via:"fallback",reason:r.skipClassifierReason};let e=await S4({toolName:r.ctx.toolName,toolParams:r.toolParams,messages:r.messages,config:r.config,signal:r.signal});return{via:"classifier",shouldBlock:e.shouldBlock,reason:e.reason,unavailable:e.unavailable===!0,stage:e.stage,durationMs:e.durationMs}}g();g();g();function I4(r,e,t={kind:"default"}){for(let n of r)if(O4(n.value))return{value:n.value,source:n.source};return{value:e,source:t}}function iI(r){for(let e of r)if(O4(e.value))return{value:e.value,source:e.source}}function O4(r){return!(r==null||typeof r=="string"&&r.trim()==="")}function Qm(r){return{kind:"cli",detail:r}}function mbe(r){return{kind:"env",envKey:r}}function yh(r){return{kind:"settings",settingsPath:r}}function wh(r,e,t){return{kind:"modelProviders",authType:r,modelId:e,detail:t}}function oI(r){return{kind:"default",detail:r}}function nu(r){return{kind:"computed",detail:r}}function jS(r,e,t){let n=r[e];return{value:n!==void 0?t?t(n):n:void 0,source:mbe(e)}}function Qn(r,e){return{value:r,source:e}}var _h="MATILDA_API_KEY",gbe="https://matilda.maincode.com/api/v1/code",ybe="matilda-code-1.0";function wbe(r){if(!r)return!0;try{let{hostname:e}=new URL(r);return e==="matilda.maincode.com"||e.endsWith(".matilda.maincode.com")}catch{return!1}}function L4(r,e,t,n){if(n?.generationConfig?.timeout!==void 0)return;let s=r.MATILDA_CODE_API_TIMEOUT_MS;if(s===void 0)return;let o=Number(s);Number.isFinite(o)&&o>0&&(e.timeout=Math.floor(o),t.timeout={kind:"env",envKey:"MATILDA_CODE_API_TIMEOUT_MS"})}function N4(r){let{authType:e,cli:t,settings:n,env:s,modelProvider:o,proxy:a}=r,l=[],c={};if(e==="matilda-oauth")return _be(r,l);let u=e?em[e]:{model:[],apiKey:[],baseUrl:[]},h=[];e&&o&&h.push(Qn(o.id,wh(e,o.id,"model.id"))),t?.model&&h.push(Qn(t.model,Qm("--model"))),e==="openai"&&s[_h]&&!s.OPENAI_MODEL&&!s.MATILDA_MODEL&&h.push(Qn(ybe,{kind:"env",envKey:_h}));for(let S of u.model)h.push(jS(s,S));n?.model&&h.push(Qn(n.model,yh("model.name")));let d=e?vP[e]:"",f=I4(h,d,oI(d));c.model=f.source;let p=[];if(e&&o?.envKey){let S=s[o.envKey];S&&p.push(Qn(S,{kind:"env",envKey:o.envKey,via:wh(e,o.id,"envKey")}))}if(t?.apiKey&&p.push(Qn(t.apiKey,Qm("--openaiApiKey"))),!o?.envKey){let S=s[_h];e==="openai"&&S&&wbe(s.OPENAI_BASE_URL)&&p.push(Qn(S,{kind:"env",envKey:_h}));for(let E of u.apiKey)p.push(jS(s,E))}n?.apiKey&&p.push(Qn(n.apiKey,yh("security.auth.apiKey")));let y=iI(p);y&&(c.apiKey=y.source);let w=[];e&&o?.baseUrl&&w.push(Qn(o.baseUrl,wh(e,o.id,"baseUrl"))),t?.baseUrl&&w.push(Qn(t.baseUrl,Qm("--openaiBaseUrl"))),e==="openai"&&s[_h]&&!s.OPENAI_BASE_URL&&w.push(Qn(gbe,{kind:"env",envKey:_h}));for(let S of u.baseUrl)w.push(jS(s,S));n?.baseUrl&&w.push(Qn(n.baseUrl,yh("security.auth.baseUrl")));let m=iI(w);m&&(c.baseUrl=m.source);let _;e&&o?.envKey&&(_=o.envKey,c.apiKeyEnvKey={...wh(e,o.id,"envKey"),envKey:o.envKey});let b=F4(n?.generationConfig,o?.generationConfig,e,o?.id??f.value,c);L4(s,b,c,o);let v={authType:e,model:f.value||"",apiKey:y?.value,apiKeyEnvKey:_,baseUrl:m?.value,proxy:a,...b};return a&&(c.proxy=nu("Config.getProxy()")),c.authType=nu("provided by caller"),{config:v,sources:c,warnings:l}}function _be(r,e){let{cli:t,settings:n,proxy:s,modelProvider:o}=r,a={},l=new Set(SP),c=t?.model||n?.model,u,h;if(c&&l.has(c))u=c,h=t?.model?Qm("--model"):yh("model.name");else{if(c){let y=c.includes("vl")||c.includes("vision")?" Note: vision-model has been removed since coder-model now supports vision capabilities.":"";e.push(`Warning: Unsupported Matilda OAuth model '${c}', falling back to '${Do}'.${y}`)}u=Do,h=oI(`fallback to '${Do}'`)}a.model=h,a.apiKey=nu("Matilda OAuth dynamic token"),a.authType=nu("provided by caller"),s&&(a.proxy=nu("Config.getProxy()"));let d=F4(n?.generationConfig,o?.generationConfig,"matilda-oauth",u,a);return L4(r.env,d,a,o),{config:{authType:"matilda-oauth",model:u,apiKey:"MATILDA_OAUTH_DYNAMIC_TOKEN",proxy:s,...d},sources:a,warnings:e}}function F4(r,e,t,n,s){let o={};for(let a of Rc)t&&e&&a in e?(o[a]=e[a],s[a]=wh(t,n||"",`generationConfig.${a}`)):r&&a in r&&(o[a]=r[a],s[a]=yh(`model.generationConfig.${a}`));return o.modalities===void 0&&n&&(o.modalities=Q2(n),s.modalities=nu("auto-detected from model")),o}g();g();$4();var Ebe=zS();function Vi(r){if(typeof r!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof r}\``);return r.replace(Ebe,"")}var U4=class{format(e,t,n){let s={};return e!==void 0&&(s.response=Vi(e)),t&&(s.stats=t),n&&(s.error=n),JSON.stringify(s,null,2)}formatError(e,t){let n={type:e.constructor.name,message:Vi(e.message),...t&&{code:t}};return this.format(void 0,void 0,n)}};g();g();import*as bh from"node:path";function H4(r,e,t){let s="command"in e?String(e.command):void 0,o=typeof e.directory=="string"?bh.isAbsolute(e.directory)?e.directory:bh.resolve(t,e.directory):void 0,a=typeof e.file_path=="string"?e.file_path:void 0;a===void 0&&typeof e.notebook_path=="string"&&(a=e.notebook_path),a===void 0&&typeof e.path=="string"&&(a=bh.isAbsolute(e.path)?e.path:bh.resolve(t,e.path));let l;if(typeof e.url=="string")try{l=new URL(e.url).hostname}catch{}let c=typeof e.skill=="string"?e.skill:typeof e.subagent_type=="string"?e.subagent_type:void 0;return{toolName:r,command:s,cwd:o,filePath:a,domain:l,specifier:c}}async function B4(r,e,t){let n=e,s=!1;if(r&&e!=="deny"&&r.hasRelevantRules(t)){let o=await r.evaluate(t);o!=="default"&&(n=o,o==="ask"&&r.hasMatchingAskRule(t)&&(s=!0))}return{finalPermission:n,pmForcedAsk:s}}function j4(r,e){(r.type==="exec"||r.type==="mcp"||r.type==="info")&&!r.permissionRules&&(r.permissionRules=M3(e))}async function z4(r,e,t,n,s){if(r!=="proceed_always"&&r!=="proceed_always_project"&&r!=="proceed_always_user")return;let o=r==="proceed_always_user"?"user":"project",a=e?.permissionRules,c=s?.permissionRules??a??[];if(c.length>0)for(let u of c)t&&await t(o,"allow",u),n?.addPersistentRule(u,"allow")}async function aI(r,e,t,n){let s=await e.getDefaultPermission(),o=r.getPermissionManager?.(),a=H4(t,n,r.getTargetDir?.()??""),{finalPermission:l,pmForcedAsk:c}=await B4(o,s,a),u={finalPermission:l,pmForcedAsk:c,pmCtx:a};if(l==="deny")if(s==="deny")u.denyMessage=`Tool "${t}" is denied: the tool's default permission is 'deny'.`;else{let h=o?.findMatchingDenyRule(a),d=h?` Matching deny rule: "${h}".`:"";u.denyMessage=`Tool "${t}" is denied by permission rules.${d}`}return u}function q4(r,e,t){let n=t===R.ASK_USER_QUESTION;return e==="bogan"&&!n?!1:r==="ask"||r==="default"}function W4(r,e){return e&&r==="allow"?"ask":r}function G4(r,e,t,n,s){return r&&!e&&!t&&!s&&n?.type!=="info"}function V4(r,e){return r==="auto-edit"&&(e?.type==="edit"||e?.type==="info")}g();function Ert(r){return $o(r,{verbose:!0})}g();var K4=10*1024*1024;function Tbe(){let r=process.env.MATILDA_CODE_MAX_INLINE_MEDIA_BYTES;if(r===void 0||r.trim()==="")return K4;let e=Number(r);return Number.isFinite(e)&&e>0?Math.floor(e):K4}function kbe(r){let e=0;if(r.startsWith("data:")){let s=r.indexOf(",");s!==-1&&(e=s+1)}let t=r.length-e;if(t===0)return 0;let n=r.endsWith("==")?2:r.endsWith("=")?1:0;return Math.floor(t*3/4)-n}function Y4(r){return(r/(1024*1024)).toFixed(1)}function xbe(r,e,t){return`[Media omitted: ${Kd(r)} is ~${Y4(e)}MB, exceeding the ${Y4(t)}MB inline limit. Ask the user to resize/compress it, or reference it via an @file path so it can be read from disk.]`}function Art(r,e=Tbe()){let t=r.inlineData?.data;if(!t)return r;let n=kbe(t);if(n<=e)return r;let s=r.inlineData?.mimeType??"application/octet-stream";return{text:xbe(s,n,e)}}g();function Mrt(r,e,t){return JSON.stringify({insight_progress:{stage:r,progress:e,detail:t}})}function Irt(r){return JSON.stringify({insight_ready:{path:r}})}function Ort(r){return JSON.stringify({insight_error:{error:r}})}function Drt(r){try{let e=JSON.parse(r);if(e.insight_progress){let{stage:n,progress:s,detail:o}=e.insight_progress;if(typeof n=="string"&&typeof s=="number")return{type:"insight_progress",stage:n,progress:s,detail:typeof o=="string"?o:void 0}}if(e.insight_ready){let{path:n}=e.insight_ready;if(typeof n=="string")return{type:"insight_ready",path:n}}let t=e.insight_error;if(t&&typeof t.error=="string")return{type:"insight_error",error:t.error}}catch{return null}return null}g();import qS from"node:path";import{promises as Ki}from"node:fs";var Abe="logs.json",Rbe=(t=>(t.USER="user",t.MODEL_SWITCH="model_switch",t))(Rbe||{});function Pbe(r){return encodeURIComponent(r)}function Brt(r){try{return decodeURIComponent(r)}catch{return r.replace(/%([0-9A-F]{2})/g,(t,n)=>String.fromCharCode(parseInt(n,16)))}}var J4=class{constructor(e,t){this.storage=t;this.sessionId=e,this.debugLogger=$("LOGGER")}matildaDir;logFilePath;sessionId;messageId=0;initialized=!1;logs=[];lastLoggedUserEntry=null;writeQueue=Promise.resolve();debugLogger;serialize(e){let t=this.writeQueue.then(()=>e());return this.writeQueue=t.catch(()=>{}),t}async _readLogFile(){if(!this.logFilePath)throw new Error("Log file path not set during read attempt.");try{let e=await Ki.readFile(this.logFilePath,"utf-8"),t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n.sessionId=="string"&&typeof n.messageId=="number"&&typeof n.timestamp=="string"&&typeof n.type=="string"&&typeof n.message=="string"):(this.debugLogger.debug(`Log file at ${this.logFilePath} is not a valid JSON array. Starting with empty logs.`),await this._backupCorruptedLogFile("malformed_array"),[])}catch(e){if(e.code==="ENOENT")return[];if(e instanceof SyntaxError)return this.debugLogger.debug(`Invalid JSON in log file ${this.logFilePath}. Backing up and starting fresh.`,e),await this._backupCorruptedLogFile("invalid_json"),[];throw this.debugLogger.debug(`Failed to read or parse log file ${this.logFilePath}:`,e),e}}async _backupCorruptedLogFile(e){if(!this.logFilePath)return;let t=`${this.logFilePath}.${e}.${Date.now()}.bak`;try{await Ki.rename(this.logFilePath,t),this.debugLogger.debug(`Backed up corrupted log file to ${t}`)}catch{}}async initialize(){if(!this.initialized){this.matildaDir=this.storage.getProjectTempDir(),this.logFilePath=qS.join(this.matildaDir,Abe);try{await Ki.mkdir(this.matildaDir,{recursive:!0});let e=!0;try{await Ki.access(this.logFilePath)}catch{e=!1}this.logs=await this._readLogFile(),!e&&this.logs.length===0&&await Xe(this.logFilePath,"[]",{encoding:"utf-8"});let t=this.logs.filter(n=>n.sessionId===this.sessionId);this.messageId=t.length>0?Math.max(...t.map(n=>n.messageId))+1:0,this.initialized=!0}catch(e){this.debugLogger.error("Failed to initialize logger:",e),this.initialized=!1}}}async _updateLogFile(e){if(!this.logFilePath)throw this.debugLogger.debug("Log file path not set. Cannot persist log entry."),new Error("Log file path not set during update attempt.");let t;try{t=await this._readLogFile()}catch(a){throw this.debugLogger.debug("Critical error reading log file before append:",a),a}let n=t.filter(a=>a.sessionId===e.sessionId),s=n.length>0?Math.max(...n.map(a=>a.messageId))+1:0;if(e.messageId=s,t.some(a=>a.sessionId===e.sessionId&&a.messageId===e.messageId&&a.timestamp===e.timestamp&&a.message===e.message))return this.debugLogger.debug(`Duplicate log entry detected and skipped: session ${e.sessionId}, messageId ${e.messageId}`),this.logs=t,null;t.push(e);try{return await Xe(this.logFilePath,JSON.stringify(t,null,2),{encoding:"utf-8"}),this.logs=t,e}catch(a){throw this.debugLogger.debug("Error writing to log file:",a),a}}async getPreviousUserMessages(){return this.initialized?this.logs.filter(e=>e.type==="user").sort((e,t)=>{let n=new Date(e.timestamp).getTime();return new Date(t.timestamp).getTime()-n}).map(e=>e.message):[]}async logMessage(e,t){if(!this.initialized||this.sessionId===void 0){this.debugLogger.debug("Logger not initialized or session ID missing. Cannot log message.");return}let n={sessionId:this.sessionId,messageId:this.messageId,type:e,message:t,timestamp:new Date().toISOString()};try{let s=await this.serialize(()=>this._updateLogFile(n));s?(this.messageId=s.messageId+1,s.type==="user"&&(this.lastLoggedUserEntry=s)):e==="user"&&(this.lastLoggedUserEntry=n)}catch{e==="user"&&(this.lastLoggedUserEntry=null)}}async removeLastUserMessage(){if(!this.initialized||!this.logFilePath)return!1;let e=this.lastLoggedUserEntry;if(!e)return!1;this.lastLoggedUserEntry=null;let t=a=>a.sessionId===e.sessionId&&a.messageId===e.messageId&&a.timestamp===e.timestamp&&a.message===e.message&&a.type===e.type,n=this.logs.findIndex(t);n>=0&&(this.logs=[...this.logs.slice(0,n),...this.logs.slice(n+1)]);let s=()=>{if(n>=0&&this.logs.findIndex(t)===-1){let a=Math.min(n,this.logs.length);this.logs=[...this.logs.slice(0,a),e,...this.logs.slice(a)]}this.lastLoggedUserEntry===null&&(this.lastLoggedUserEntry=e)},o=this.logFilePath;return this.serialize(async()=>{let a;try{a=await this._readLogFile()}catch(c){return this.debugLogger.debug("Failed to read log file while undoing last user entry:",c),s(),!1}let l=a.findIndex(t);if(l===-1)return this.logs=a,!1;a.splice(l,1);try{return await Xe(o,JSON.stringify(a,null,2),{encoding:"utf-8"}),this.logs=a,e.sessionId===this.sessionId&&this.messageId===e.messageId+1&&(this.messageId=e.messageId),!0}catch(c){return this.debugLogger.debug("Failed to write log file while undoing last user entry:",c),s(),!1}})}_checkpointPath(e){if(!e.length)throw new Error("No checkpoint tag specified.");if(!this.matildaDir)throw new Error("Checkpoint file path not set.");let t=Pbe(e);return qS.join(this.matildaDir,`checkpoint-${t}.json`)}async _getCheckpointPath(e){let t=this._checkpointPath(e);try{return await Ki.access(t),t}catch(s){if(s.code!=="ENOENT")throw s}let n=qS.join(this.matildaDir,`checkpoint-${e}.json`);try{return await Ki.access(n),n}catch(s){if(s.code!=="ENOENT")throw s}return t}async saveCheckpoint(e,t){if(!this.initialized){this.debugLogger.error("Logger not initialized or checkpoint file path not set. Cannot save a checkpoint.");return}let n=this._checkpointPath(t);try{await Xe(n,JSON.stringify(e,null,2),{encoding:"utf-8"})}catch(s){this.debugLogger.error("Error writing to checkpoint file:",s)}}async loadCheckpoint(e){if(!this.initialized)return this.debugLogger.error("Logger not initialized or checkpoint file path not set. Cannot load checkpoint."),[];let t=await this._getCheckpointPath(e);try{let n=await Ki.readFile(t,"utf-8"),s=JSON.parse(n);return Array.isArray(s)?s:(this.debugLogger.warn(`Checkpoint file at ${t} is not a valid JSON array. Returning empty checkpoint.`),[])}catch(n){return n.code==="ENOENT"?[]:(this.debugLogger.error(`Failed to read or parse checkpoint file ${t}:`,n),[])}}async deleteCheckpoint(e){if(!this.initialized||!this.matildaDir)return this.debugLogger.error("Logger not initialized or checkpoint file path not set. Cannot delete checkpoint."),!1;let t=!1,n=this._checkpointPath(e);try{await Ki.unlink(n),t=!0}catch(o){if(o.code!=="ENOENT")throw this.debugLogger.error(`Failed to delete checkpoint file ${n}:`,o),o}let s=qS.join(this.matildaDir,`checkpoint-${e}.json`);if(n!==s)try{await Ki.unlink(s),t=!0}catch(o){if(o.code!=="ENOENT")throw this.debugLogger.error(`Failed to delete checkpoint file ${s}:`,o),o}return t}async checkpointExists(e){if(!this.initialized)throw new Error("Logger not initialized. Cannot check for checkpoint existence.");let t;try{return t=await this._getCheckpointPath(e),await Ki.access(t),!0}catch(n){if(n.code==="ENOENT")return!1;throw this.debugLogger.error(`Failed to check checkpoint existence for ${t??`path for tag "${e}"`}:`,n),n}}close(){this.initialized=!1,this.logFilePath=void 0,this.logs=[],this.lastLoggedUserEntry=null,this.writeQueue=Promise.resolve(),this.sessionId=void 0,this.messageId=0}};g();async function Wrt(r,e,t,n={}){return new Promise((s,o)=>{new vh({config:r,chatRecordingService:r.getChatRecordingService(),outputUpdateHandler:n.outputUpdateHandler,onAllToolCallsComplete:async a=>{n.onAllToolCallsComplete&&await n.onAllToolCallsComplete(a),s(a[0].response)},onToolCallsUpdate:n.onToolCallsUpdate,getPreferredEditor:()=>{},onEditorClose:()=>{}}).schedule(e,t).catch(o)})}g();import{spawn as wK}from"node:child_process";import{StringDecoder as yK}from"node:string_decoder";g();g();g();g();g();function Sh(r){return!!r._zod}function ai(r,e){return Sh(r)?kP(r,e):r.safeParse(e)}function WS(r){if(!r)return;let e;if(Sh(r)?e=r._zod?.def?.shape:e=r.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function X4(r){if(Sh(r)){let o=r._zod?.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}}let t=r._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=r.value;if(n!==void 0)return n}g();var Eh="2025-11-25";var Z4=[Eh,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],al="io.modelcontextprotocol/related-task",VS="2.0",yr=bz(r=>r!==null&&(typeof r=="object"||typeof r=="function")),Q4=Ut([B(),Ze().int()]),e6=B(),nnt=mr({ttl:Ze().optional(),pollInterval:Ze().optional()}),Obe=le({ttl:Ze().optional()}),Dbe=le({taskId:B()}),cI=mr({progressToken:Q4.optional(),[al]:Dbe.optional()}),es=le({_meta:cI.optional()}),tg=es.extend({task:Obe.optional()}),t6=r=>tg.safeParse(r).success,Dr=le({method:B(),params:es.loose().optional()}),Is=le({_meta:cI.optional()}),Os=le({method:B(),params:Is.loose().optional()}),Lr=mr({_meta:cI.optional()}),KS=Ut([B(),Ze().int()]),r6=le({jsonrpc:de(VS),id:KS,...Dr.shape}).strict(),rg=r=>r6.safeParse(r).success,n6=le({jsonrpc:de(VS),...Os.shape}).strict(),s6=r=>n6.safeParse(r).success,uI=le({jsonrpc:de(VS),id:KS,result:Lr}).strict(),su=r=>uI.safeParse(r).success;var be;(function(r){r[r.ConnectionClosed=-32e3]="ConnectionClosed",r[r.RequestTimeout=-32001]="RequestTimeout",r[r.ParseError=-32700]="ParseError",r[r.InvalidRequest=-32600]="InvalidRequest",r[r.MethodNotFound=-32601]="MethodNotFound",r[r.InvalidParams=-32602]="InvalidParams",r[r.InternalError=-32603]="InternalError",r[r.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(be||(be={}));var dI=le({jsonrpc:de(VS),id:KS.optional(),error:le({code:Ze().int(),message:B(),data:rr().optional()})}).strict();var i6=r=>dI.safeParse(r).success;var ll=Ut([r6,n6,uI,dI]),snt=Ut([uI,dI]),iu=Lr.strict(),Lbe=Is.extend({requestId:KS.optional(),reason:B().optional()}),YS=Os.extend({method:de("notifications/cancelled"),params:Lbe}),Nbe=le({src:B(),mimeType:B().optional(),sizes:oe(B()).optional(),theme:Vn(["light","dark"]).optional()}),ng=le({icons:oe(Nbe).optional()}),Ch=le({name:B(),title:B().optional()}),o6=Ch.extend({...Ch.shape,...ng.shape,version:B(),websiteUrl:B().optional(),description:B().optional()}),Fbe=AP(le({applyDefaults:Tt().optional()}),At(B(),rr())),$be=RP(r=>r&&typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===0?{form:{}}:r,AP(le({form:Fbe.optional(),url:yr.optional()}),At(B(),rr()).optional())),Ube=mr({list:yr.optional(),cancel:yr.optional(),requests:mr({sampling:mr({createMessage:yr.optional()}).optional(),elicitation:mr({create:yr.optional()}).optional()}).optional()}),Hbe=mr({list:yr.optional(),cancel:yr.optional(),requests:mr({tools:mr({call:yr.optional()}).optional()}).optional()}),Bbe=le({experimental:At(B(),yr).optional(),sampling:le({context:yr.optional(),tools:yr.optional()}).optional(),elicitation:$be.optional(),roots:le({listChanged:Tt().optional()}).optional(),tasks:Ube.optional(),extensions:At(B(),yr).optional()}),jbe=es.extend({protocolVersion:B(),capabilities:Bbe,clientInfo:o6}),zbe=Dr.extend({method:de("initialize"),params:jbe});var qbe=le({experimental:At(B(),yr).optional(),logging:yr.optional(),completions:yr.optional(),prompts:le({listChanged:Tt().optional()}).optional(),resources:le({subscribe:Tt().optional(),listChanged:Tt().optional()}).optional(),tools:le({listChanged:Tt().optional()}).optional(),tasks:Hbe.optional(),extensions:At(B(),yr).optional()}),hI=Lr.extend({protocolVersion:B(),capabilities:qbe,serverInfo:o6,instructions:B().optional()}),a6=Os.extend({method:de("notifications/initialized"),params:Is.optional()}),l6=r=>a6.safeParse(r).success,JS=Dr.extend({method:de("ping"),params:es.optional()}),Wbe=le({progress:Ze(),total:Zt(Ze()),message:Zt(B())}),Gbe=le({...Is.shape,...Wbe.shape,progressToken:Q4}),XS=Os.extend({method:de("notifications/progress"),params:Gbe}),Vbe=es.extend({cursor:e6.optional()}),sg=Dr.extend({params:Vbe.optional()}),ig=Lr.extend({nextCursor:e6.optional()}),Kbe=Vn(["working","input_required","completed","failed","cancelled"]),og=le({taskId:B(),status:Kbe,ttl:Ut([Ze(),wz()]),createdAt:B(),lastUpdatedAt:B(),pollInterval:Zt(Ze()),statusMessage:Zt(B())}),ou=Lr.extend({task:og}),Ybe=Is.merge(og),ag=Os.extend({method:de("notifications/tasks/status"),params:Ybe}),ZS=Dr.extend({method:de("tasks/get"),params:es.extend({taskId:B()})}),QS=Lr.merge(og),eC=Dr.extend({method:de("tasks/result"),params:es.extend({taskId:B()})}),int=Lr.loose(),tC=sg.extend({method:de("tasks/list")}),rC=ig.extend({tasks:oe(og)}),nC=Dr.extend({method:de("tasks/cancel"),params:es.extend({taskId:B()})}),c6=Lr.merge(og),u6=le({uri:B(),mimeType:Zt(B()),_meta:At(B(),rr()).optional()}),d6=u6.extend({text:B()}),fI=B().refine(r=>{try{return atob(r),!0}catch{return!1}},{message:"Invalid Base64 string"}),h6=u6.extend({blob:fI}),lg=Vn(["user","assistant"]),Th=le({audience:oe(lg).optional(),priority:Ze().min(0).max(1).optional(),lastModified:gz.datetime({offset:!0}).optional()}),f6=le({...Ch.shape,...ng.shape,uri:B(),description:Zt(B()),mimeType:Zt(B()),size:Zt(Ze()),annotations:Th.optional(),_meta:Zt(mr({}))}),Jbe=le({...Ch.shape,...ng.shape,uriTemplate:B(),description:Zt(B()),mimeType:Zt(B()),annotations:Th.optional(),_meta:Zt(mr({}))}),Xbe=sg.extend({method:de("resources/list")}),pI=ig.extend({resources:oe(f6)}),Zbe=sg.extend({method:de("resources/templates/list")}),mI=ig.extend({resourceTemplates:oe(Jbe)}),gI=es.extend({uri:B()}),Qbe=gI,eve=Dr.extend({method:de("resources/read"),params:Qbe}),cg=Lr.extend({contents:oe(Ut([d6,h6]))}),yI=Os.extend({method:de("notifications/resources/list_changed"),params:Is.optional()}),tve=gI,rve=Dr.extend({method:de("resources/subscribe"),params:tve}),nve=gI,sve=Dr.extend({method:de("resources/unsubscribe"),params:nve}),ive=Is.extend({uri:B()}),ove=Os.extend({method:de("notifications/resources/updated"),params:ive}),ave=le({name:B(),description:Zt(B()),required:Zt(Tt())}),lve=le({...Ch.shape,...ng.shape,description:Zt(B()),arguments:Zt(oe(ave)),_meta:Zt(mr({}))}),cve=sg.extend({method:de("prompts/list")}),ug=ig.extend({prompts:oe(lve)}),uve=es.extend({name:B(),arguments:At(B(),B()).optional()}),dve=Dr.extend({method:de("prompts/get"),params:uve}),wI=le({type:de("text"),text:B(),annotations:Th.optional(),_meta:At(B(),rr()).optional()}),_I=le({type:de("image"),data:fI,mimeType:B(),annotations:Th.optional(),_meta:At(B(),rr()).optional()}),bI=le({type:de("audio"),data:fI,mimeType:B(),annotations:Th.optional(),_meta:At(B(),rr()).optional()}),hve=le({type:de("tool_use"),name:B(),id:B(),input:At(B(),rr()),_meta:At(B(),rr()).optional()}),fve=le({type:de("resource"),resource:Ut([d6,h6]),annotations:Th.optional(),_meta:At(B(),rr()).optional()}),pve=f6.extend({type:de("resource_link")}),vI=Ut([wI,_I,bI,pve,fve]),mve=le({role:lg,content:vI}),dg=Lr.extend({description:B().optional(),messages:oe(mve)}),SI=Os.extend({method:de("notifications/prompts/list_changed"),params:Is.optional()}),gve=le({title:B().optional(),readOnlyHint:Tt().optional(),destructiveHint:Tt().optional(),idempotentHint:Tt().optional(),openWorldHint:Tt().optional()}),yve=le({taskSupport:Vn(["required","optional","forbidden"]).optional()}),p6=le({...Ch.shape,...ng.shape,description:B().optional(),inputSchema:le({type:de("object"),properties:At(B(),yr).optional(),required:oe(B()).optional()}).catchall(rr()),outputSchema:le({type:de("object"),properties:At(B(),yr).optional(),required:oe(B()).optional()}).catchall(rr()).optional(),annotations:gve.optional(),execution:yve.optional(),_meta:At(B(),rr()).optional()}),wve=sg.extend({method:de("tools/list")}),hg=ig.extend({tools:oe(p6)}),Go=Lr.extend({content:oe(vI).default([]),structuredContent:At(B(),rr()).optional(),isError:Tt().optional()}),ont=Go.or(Lr.extend({toolResult:rr()})),_ve=tg.extend({name:B(),arguments:At(B(),rr()).optional()}),bve=Dr.extend({method:de("tools/call"),params:_ve}),CI=Os.extend({method:de("notifications/tools/list_changed"),params:Is.optional()}),m6=le({autoRefresh:Tt().default(!0),debounceMs:Ze().int().nonnegative().default(300)}),g6=Vn(["debug","info","notice","warning","error","critical","alert","emergency"]),vve=es.extend({level:g6}),Sve=Dr.extend({method:de("logging/setLevel"),params:vve}),Cve=Is.extend({level:g6,logger:B().optional(),data:rr()}),Eve=Os.extend({method:de("notifications/message"),params:Cve}),Tve=le({name:B().optional()}),kve=le({hints:oe(Tve).optional(),costPriority:Ze().min(0).max(1).optional(),speedPriority:Ze().min(0).max(1).optional(),intelligencePriority:Ze().min(0).max(1).optional()}),xve=le({mode:Vn(["auto","required","none"]).optional()}),Ave=le({type:de("tool_result"),toolUseId:B().describe("The unique identifier for the corresponding tool call."),content:oe(vI).default([]),structuredContent:le({}).loose().optional(),isError:Tt().optional(),_meta:At(B(),rr()).optional()}),Rve=xP("type",[wI,_I,bI]),GS=xP("type",[wI,_I,bI,hve,Ave]),Pve=le({role:lg,content:Ut([GS,oe(GS)]),_meta:At(B(),rr()).optional()}),Mve=tg.extend({messages:oe(Pve),modelPreferences:kve.optional(),systemPrompt:B().optional(),includeContext:Vn(["none","thisServer","allServers"]).optional(),temperature:Ze().optional(),maxTokens:Ze().int(),stopSequences:oe(B()).optional(),metadata:yr.optional(),tools:oe(p6).optional(),toolChoice:xve.optional()}),EI=Dr.extend({method:de("sampling/createMessage"),params:Mve}),TI=Lr.extend({model:B(),stopReason:Zt(Vn(["endTurn","stopSequence","maxTokens"]).or(B())),role:lg,content:Rve}),kI=Lr.extend({model:B(),stopReason:Zt(Vn(["endTurn","stopSequence","maxTokens","toolUse"]).or(B())),role:lg,content:Ut([GS,oe(GS)])}),Ive=le({type:de("boolean"),title:B().optional(),description:B().optional(),default:Tt().optional()}),Ove=le({type:de("string"),title:B().optional(),description:B().optional(),minLength:Ze().optional(),maxLength:Ze().optional(),format:Vn(["email","uri","date","date-time"]).optional(),default:B().optional()}),Dve=le({type:Vn(["number","integer"]),title:B().optional(),description:B().optional(),minimum:Ze().optional(),maximum:Ze().optional(),default:Ze().optional()}),Lve=le({type:de("string"),title:B().optional(),description:B().optional(),enum:oe(B()),default:B().optional()}),Nve=le({type:de("string"),title:B().optional(),description:B().optional(),oneOf:oe(le({const:B(),title:B()})),default:B().optional()}),Fve=le({type:de("string"),title:B().optional(),description:B().optional(),enum:oe(B()),enumNames:oe(B()).optional(),default:B().optional()}),$ve=Ut([Lve,Nve]),Uve=le({type:de("array"),title:B().optional(),description:B().optional(),minItems:Ze().optional(),maxItems:Ze().optional(),items:le({type:de("string"),enum:oe(B())}),default:oe(B()).optional()}),Hve=le({type:de("array"),title:B().optional(),description:B().optional(),minItems:Ze().optional(),maxItems:Ze().optional(),items:le({anyOf:oe(le({const:B(),title:B()}))}),default:oe(B()).optional()}),Bve=Ut([Uve,Hve]),jve=Ut([Fve,$ve,Bve]),zve=Ut([jve,Ive,Ove,Dve]),qve=tg.extend({mode:de("form").optional(),message:B(),requestedSchema:le({type:de("object"),properties:At(B(),zve),required:oe(B()).optional()})}),Wve=tg.extend({mode:de("url"),message:B(),elicitationId:B(),url:B().url()}),Gve=Ut([qve,Wve]),xI=Dr.extend({method:de("elicitation/create"),params:Gve}),Vve=Is.extend({elicitationId:B()}),Kve=Os.extend({method:de("notifications/elicitation/complete"),params:Vve}),AI=Lr.extend({action:Vn(["accept","decline","cancel"]),content:RP(r=>r===null?void 0:r,At(B(),Ut([B(),Ze(),Tt(),oe(B())])).optional())}),Yve=le({type:de("ref/resource"),uri:B()});var Jve=le({type:de("ref/prompt"),name:B()}),Xve=es.extend({ref:Ut([Jve,Yve]),argument:le({name:B(),value:B()}),context:le({arguments:At(B(),B()).optional()}).optional()}),Zve=Dr.extend({method:de("completion/complete"),params:Xve});var RI=Lr.extend({completion:mr({values:oe(B()).max(100),total:Zt(Ze().int()),hasMore:Zt(Tt())})}),Qve=le({uri:B().startsWith("file://"),name:B().optional(),_meta:At(B(),rr()).optional()}),sC=Dr.extend({method:de("roots/list"),params:es.optional()}),eSe=Lr.extend({roots:oe(Qve)}),tSe=Os.extend({method:de("notifications/roots/list_changed"),params:Is.optional()}),ant=Ut([JS,zbe,Zve,Sve,dve,cve,Xbe,Zbe,eve,rve,sve,bve,wve,ZS,eC,tC,nC]),lnt=Ut([YS,XS,a6,tSe,ag]),cnt=Ut([iu,TI,kI,AI,eSe,QS,rC,ou]),unt=Ut([JS,EI,xI,sC,ZS,eC,tC,nC]),dnt=Ut([YS,XS,Eve,ove,yI,CI,SI,ag,Kve]),hnt=Ut([iu,hI,RI,dg,ug,pI,mI,cg,Go,hg,QS,rC,ou]),we=class r extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,t,n){if(e===be.UrlElicitationRequired&&n){let s=n;if(s.elicitations)return new lI(s.elicitations,t)}return new r(e,t,n)}},lI=class extends we{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(be.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};g();function cl(r){return r==="completed"||r==="failed"||r==="cancelled"}g();g();g();var rSe=Symbol("Let zodToJsonSchema decide on which parser to use");g();g();g();g();g();g();g();g();g();g();g();g();g();g();g();g();g();g();g();g();var cst=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");g();g();g();g();g();g();g();g();g();g();g();g();g();g();g();g();g();function PI(r){let t=WS(r)?.method;if(!t)throw new Error("Schema is missing a method literal");let n=X4(t);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function MI(r,e){let t=ai(r,e);if(!t.success)throw t.error;return t.data}var lSe=6e4,iC=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(YS,t=>{this._oncancel(t)}),this.setNotificationHandler(XS,t=>{this._onprogress(t)}),this.setRequestHandler(JS,t=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(ZS,async(t,n)=>{let s=await this._taskStore.getTask(t.params.taskId,n.sessionId);if(!s)throw new we(be.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(eC,async(t,n)=>{let s=async()=>{let o=t.params.taskId;if(this._taskMessageQueue){let l;for(;l=await this._taskMessageQueue.dequeue(o,n.sessionId);){if(l.type==="response"||l.type==="error"){let c=l.message,u=c.id,h=this._requestResolvers.get(u);if(h)if(this._requestResolvers.delete(u),l.type==="response")h(c);else{let d=c,f=new we(d.error.code,d.error.message,d.error.data);h(f)}else{let d=l.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(l.message,{relatedRequestId:n.requestId})}}let a=await this._taskStore.getTask(o,n.sessionId);if(!a)throw new we(be.InvalidParams,`Task not found: ${o}`);if(!cl(a.status))return await this._waitForTaskUpdate(o,n.signal),await s();if(cl(a.status)){let l=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...l,_meta:{...l._meta,[al]:{taskId:o}}}}return await s()};return await s()}),this.setRequestHandler(tC,async(t,n)=>{try{let{tasks:s,nextCursor:o}=await this._taskStore.listTasks(t.params?.cursor,n.sessionId);return{tasks:s,nextCursor:o,_meta:{}}}catch(s){throw new we(be.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(nC,async(t,n)=>{try{let s=await this._taskStore.getTask(t.params.taskId,n.sessionId);if(!s)throw new we(be.InvalidParams,`Task not found: ${t.params.taskId}`);if(cl(s.status))throw new we(be.InvalidParams,`Cannot cancel task in terminal status: ${s.status}`);await this._taskStore.updateTaskStatus(t.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(t.params.taskId);let o=await this._taskStore.getTask(t.params.taskId,n.sessionId);if(!o)throw new we(be.InvalidParams,`Task not found after cancellation: ${t.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof we?s:new we(be.InvalidRequest,`Failed to cancel task: ${s instanceof Error?s.message:String(s)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,s,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:o,onTimeout:s})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),we.fromError(be.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=o=>{n?.(o),this._onerror(o)};let s=this._transport?.onmessage;this._transport.onmessage=(o,a)=>{s?.(o,a),su(o)||i6(o)?this._onresponse(o):rg(o)?this._onrequest(o,a):s6(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let t=we.fromError(be.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,t){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,s=this._transport,o=e.params?._meta?.[al]?.taskId;if(n===void 0){let h={jsonrpc:"2.0",id:e.id,error:{code:be.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:h,timestamp:Date.now()},s?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):s?.send(h).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let l=t6(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,s?.sessionId):void 0,u={signal:a.signal,sessionId:s?.sessionId,_meta:e.params?._meta,sendNotification:async h=>{if(a.signal.aborted)return;let d={relatedRequestId:e.id};o&&(d.relatedTask={taskId:o}),await this.notification(h,d)},sendRequest:async(h,d,f)=>{if(a.signal.aborted)throw new we(be.ConnectionClosed,"Request was cancelled");let p={...f,relatedRequestId:e.id};o&&!p.relatedTask&&(p.relatedTask={taskId:o});let y=p.relatedTask?.taskId??o;return y&&c&&await c.updateTaskStatus(y,"input_required"),await this.request(h,d,p)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:o,taskStore:c,taskRequestedTtl:l?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{l&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async h=>{if(a.signal.aborted)return;let d={result:h,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:d,timestamp:Date.now()},s?.sessionId):await s?.send(d)},async h=>{if(a.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(h.code)?h.code:be.InternalError,message:h.message??"Internal error",...h.data!==void 0&&{data:h.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:d,timestamp:Date.now()},s?.sessionId):await s?.send(d)}).catch(h=>this._onerror(new Error(`Failed to send response: ${h}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===a&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,s=Number(t),o=this._progressHandlers.get(s);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(s),l=this._timeoutInfo.get(s);if(l&&a&&l.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(c){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),a(c);return}o(n)}_onresponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);if(n){if(this._requestResolvers.delete(t),su(e))n(e);else{let a=new we(e.error.code,e.error.message,e.error.data);n(a)}return}let s=this._responseHandlers.get(t);if(s===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let o=!1;if(su(e)&&e.result&&typeof e.result=="object"){let a=e.result;if(a.task&&typeof a.task=="object"){let l=a.task;typeof l.taskId=="string"&&(o=!0,this._taskProgressTokens.set(l.taskId,t))}}if(o||this._progressHandlers.delete(t),su(e))s(e);else{let a=we.fromError(e.error.code,e.error.message,e.error.data);s(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,n){let{task:s}=n??{};if(!s){try{yield{type:"result",result:await this.request(e,t,n)}}catch(a){yield{type:"error",error:a instanceof we?a:new we(be.InternalError,String(a))}}return}let o;try{let a=await this.request(e,ou,n);if(a.task)o=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new we(be.InternalError,"Task creation did not return a task");for(;;){let l=await this.getTask({taskId:o},n);if(yield{type:"taskStatus",task:l},cl(l.status)){l.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},t,n)}:l.status==="failed"?yield{type:"error",error:new we(be.InternalError,`Task ${o} failed`)}:l.status==="cancelled"&&(yield{type:"error",error:new we(be.InternalError,`Task ${o} was cancelled`)});return}if(l.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},t,n)};return}let c=l.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof we?a:new we(be.InternalError,String(a))}}}request(e,t,n){let{relatedRequestId:s,resumptionToken:o,onresumptiontoken:a,task:l,relatedTask:c}=n??{};return new Promise((u,h)=>{let d=b=>{h(b)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),l&&this.assertTaskCapability(e.method)}catch(b){d(b);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:f}}),l&&(p.params={...p.params,task:l}),c&&(p.params={...p.params,_meta:{...p.params?._meta||{},[al]:c}});let y=b=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(b)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:a}).catch(S=>this._onerror(new Error(`Failed to send cancellation: ${S}`)));let v=b instanceof we?b:new we(be.RequestTimeout,String(b));h(v)};this._responseHandlers.set(f,b=>{if(!n?.signal?.aborted){if(b instanceof Error)return h(b);try{let v=ai(t,b.result);v.success?u(v.data):h(v.error)}catch(v){h(v)}}}),n?.signal?.addEventListener("abort",()=>{y(n?.signal?.reason)});let w=n?.timeout??lSe,m=()=>y(we.fromError(be.RequestTimeout,"Request timed out",{timeout:w}));this._setupTimeout(f,w,n?.maxTotalTimeout,m,n?.resetTimeoutOnProgress??!1);let _=c?.taskId;if(_){let b=v=>{let S=this._responseHandlers.get(f);S?S(v):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,b),this._enqueueTaskMessage(_,{type:"request",message:p,timestamp:Date.now()}).catch(v=>{this._cleanupTimeout(f),h(v)})}else this._transport.send(p,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:a}).catch(b=>{this._cleanupTimeout(f),h(b)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},QS,t)}async getTaskResult(e,t,n){return this.request({method:"tasks/result",params:e},t,n)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},rC,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},c6,t)}async notification(e,t){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=t?.relatedTask?.taskId;if(n){let l={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[al]:t.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:l,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let l={...e,jsonrpc:"2.0"};t?.relatedTask&&(l={...l,params:{...l.params,_meta:{...l.params?._meta||{},[al]:t.relatedTask}}}),this._transport?.send(l,t).catch(c=>this._onerror(c))});return}let a={...e,jsonrpc:"2.0"};t?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[al]:t.relatedTask}}}),await this._transport.send(a,t)}setRequestHandler(e,t){let n=PI(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,o)=>{let a=MI(e,s);return Promise.resolve(t(a,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let n=PI(e);this._notificationHandlers.set(n,s=>{let o=MI(e,s);return Promise.resolve(t(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let s=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n,s)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let s of n)if(s.type==="request"&&rg(s.message)){let o=s.message.id,a=this._requestResolvers.get(o);a?(a(new we(be.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=this._options?.defaultTaskPollInterval??1e3;try{let s=await this._taskStore?.getTask(e);s?.pollInterval&&(n=s.pollInterval)}catch{}return new Promise((s,o)=>{if(t.aborted){o(new we(be.InvalidRequest,"Request cancelled"));return}let a=setTimeout(s,n);t.addEventListener("abort",()=>{clearTimeout(a),o(new we(be.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async s=>{if(!e)throw new Error("No request provided");return await n.createTask(s,e.id,{method:e.method,params:e.params},t)},getTask:async s=>{let o=await n.getTask(s,t);if(!o)throw new we(be.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(s,o,a)=>{await n.storeTaskResult(s,o,a,t);let l=await n.getTask(s,t);if(l){let c=ag.parse({method:"notifications/tasks/status",params:l});await this.notification(c),cl(l.status)&&this._cleanupTaskProgressHandler(s)}},getTaskResult:s=>n.getTaskResult(s,t),updateTaskStatus:async(s,o,a)=>{let l=await n.getTask(s,t);if(!l)throw new we(be.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(cl(l.status))throw new we(be.InvalidParams,`Cannot update task "${s}" from terminal status "${l.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(s,o,a,t);let c=await n.getTask(s,t);if(c){let u=ag.parse({method:"notifications/tasks/status",params:c});await this.notification(u),cl(c.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>n.listTasks(s,t)}}};function y6(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function w6(r,e){let t={...r};for(let n in e){let s=n,o=e[s];if(o===void 0)continue;let a=t[s];y6(a)&&y6(o)?t[s]={...a,...o}:t[s]=o}return t}g();var O8=Ve(I8(),1),D8=Ve(She(),1);function sxe(){let r=new O8.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,D8.default)(r),r}var NC=class{constructor(e){this._ajv=e??sxe()}getValidator(e){let t="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>t(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}};g();var FC=class{constructor(e){this._client=e}async*callToolStream(e,t=Go,n){let s=this._client,o={...n,task:n?.task??(s.isToolTask(e.name)?{}:void 0)},a=s.requestStream({method:"tools/call",params:e},t,o),l=s.getToolOutputValidator(e.name);for await(let c of a){if(c.type==="result"&&l){let u=c.result;if(!u.structuredContent&&!u.isError){yield{type:"error",error:new we(be.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(u.structuredContent)try{let h=l(u.structuredContent);if(!h.valid){yield{type:"error",error:new we(be.InvalidParams,`Structured content does not match the tool's output schema: ${h.errorMessage}`)};return}}catch(h){if(h instanceof we){yield{type:"error",error:h};return}yield{type:"error",error:new we(be.InvalidParams,`Failed to validate structured content: ${h instanceof Error?h.message:String(h)}`)};return}}yield c}}async getTask(e,t){return this._client.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._client.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._client.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._client.cancelTask({taskId:e},t)}requestStream(e,t,n){return this._client.requestStream(e,t,n)}};g();function L8(r,e,t){if(!r)throw new Error(`${t} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!r.tools?.call)throw new Error(`${t} does not support task creation for tools/call (required for ${e})`);break;default:break}}function N8(r,e,t){if(!r)throw new Error(`${t} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!r.sampling?.createMessage)throw new Error(`${t} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!r.elicitation?.create)throw new Error(`${t} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}function $C(r,e){if(!(!r||e===null||typeof e!="object")){if(r.type==="object"&&r.properties&&typeof r.properties=="object"){let t=e,n=r.properties;for(let s of Object.keys(n)){let o=n[s];t[s]===void 0&&Object.prototype.hasOwnProperty.call(o,"default")&&(t[s]=o.default),t[s]!==void 0&&$C(o,t[s])}}if(Array.isArray(r.anyOf))for(let t of r.anyOf)typeof t!="boolean"&&$C(t,e);if(Array.isArray(r.oneOf))for(let t of r.oneOf)typeof t!="boolean"&&$C(t,e)}}function ixe(r){if(!r)return{supportsFormMode:!1,supportsUrlMode:!1};let e=r.form!==void 0,t=r.url!==void 0;return{supportsFormMode:e||!e&&!t,supportsUrlMode:t}}var yl=class extends iC{constructor(e,t){super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=t?.capabilities??{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new NC,t?.listChanged&&(this._pendingListChangedConfig=t.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",CI,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",SI,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",yI,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new FC(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=w6(this._capabilities,e)}setRequestHandler(e,t){let s=WS(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o;if(Sh(s)){let l=s;o=l._zod?.def?.value??l.value}else{let l=s;o=l._def?.value??l.value}if(typeof o!="string")throw new Error("Schema method literal must be a string");let a=o;if(a==="elicitation/create"){let l=async(c,u)=>{let h=ai(xI,c);if(!h.success){let b=h.error instanceof Error?h.error.message:String(h.error);throw new we(be.InvalidParams,`Invalid elicitation request: ${b}`)}let{params:d}=h.data;d.mode=d.mode??"form";let{supportsFormMode:f,supportsUrlMode:p}=ixe(this._capabilities.elicitation);if(d.mode==="form"&&!f)throw new we(be.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!p)throw new we(be.InvalidParams,"Client does not support URL-mode elicitation requests");let y=await Promise.resolve(t(c,u));if(d.task){let b=ai(ou,y);if(!b.success){let v=b.error instanceof Error?b.error.message:String(b.error);throw new we(be.InvalidParams,`Invalid task creation result: ${v}`)}return b.data}let w=ai(AI,y);if(!w.success){let b=w.error instanceof Error?w.error.message:String(w.error);throw new we(be.InvalidParams,`Invalid elicitation result: ${b}`)}let m=w.data,_=d.mode==="form"?d.requestedSchema:void 0;if(d.mode==="form"&&m.action==="accept"&&m.content&&_&&this._capabilities.elicitation?.form?.applyDefaults)try{$C(_,m.content)}catch{}return m};return super.setRequestHandler(e,l)}if(a==="sampling/createMessage"){let l=async(c,u)=>{let h=ai(EI,c);if(!h.success){let m=h.error instanceof Error?h.error.message:String(h.error);throw new we(be.InvalidParams,`Invalid sampling request: ${m}`)}let{params:d}=h.data,f=await Promise.resolve(t(c,u));if(d.task){let m=ai(ou,f);if(!m.success){let _=m.error instanceof Error?m.error.message:String(m.error);throw new we(be.InvalidParams,`Invalid task creation result: ${_}`)}return m.data}let y=d.tools||d.toolChoice?kI:TI,w=ai(y,f);if(!w.success){let m=w.error instanceof Error?w.error.message:String(w.error);throw new we(be.InvalidParams,`Invalid sampling result: ${m}`)}return w.data};return super.setRequestHandler(e,l)}return super.setRequestHandler(e,t)}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:Eh,capabilities:this._capabilities,clientInfo:this._clientInfo}},hI,t);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!Z4.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`);break;case"ping":break}}assertTaskCapability(e){L8(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&N8(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},iu,e)}async complete(e,t){return this.request({method:"completion/complete",params:e},RI,t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},iu,t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},dg,t)}async listPrompts(e,t){return this.request({method:"prompts/list",params:e},ug,t)}async listResources(e,t){return this.request({method:"resources/list",params:e},pI,t)}async listResourceTemplates(e,t){return this.request({method:"resources/templates/list",params:e},mI,t)}async readResource(e,t){return this.request({method:"resources/read",params:e},cg,t)}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},iu,t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},iu,t)}async callTool(e,t=Go,n){if(this.isToolTaskRequired(e.name))throw new we(be.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let s=await this.request({method:"tools/call",params:e},t,n),o=this.getToolOutputValidator(e.name);if(o){if(!s.structuredContent&&!s.isError)throw new we(be.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(s.structuredContent)try{let a=o(s.structuredContent);if(!a.valid)throw new we(be.InvalidParams,`Structured content does not match the tool's output schema: ${a.errorMessage}`)}catch(a){throw a instanceof we?a:new we(be.InvalidParams,`Failed to validate structured content: ${a instanceof Error?a.message:String(a)}`)}}return s}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let t of e){if(t.outputSchema){let s=this._jsonSchemaValidator.getValidator(t.outputSchema);this._cachedToolOutputValidators.set(t.name,s)}let n=t.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(t.name),n==="required"&&this._cachedRequiredTaskTools.add(t.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){let n=await this.request({method:"tools/list",params:e},hg,t);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,t,n,s){let o=m6.safeParse(n);if(!o.success)throw new Error(`Invalid ${e} listChanged options: ${o.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:a,debounceMs:l}=o.data,{onChanged:c}=n,u=async()=>{if(!a){c(null,null);return}try{let d=await s();c(null,d)}catch(d){let f=d instanceof Error?d:new Error(String(d));c(f,null)}},h=()=>{if(l){let d=this._listChangedDebounceTimers.get(e);d&&clearTimeout(d);let f=setTimeout(u,l);this._listChangedDebounceTimers.set(e,f)}else u()};this.setNotificationHandler(t,h)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};g();g();g();var UC=class extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function uD(r){}function HC(r){if(typeof r=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:e=uD,onError:t=uD,onRetry:n=uD,onComment:s}=r,o="",a=!0,l,c="",u="";function h(w){let m=a?w.replace(/^\xEF\xBB\xBF/,""):w,[_,b]=oxe(`${o}${m}`);for(let v of _)d(v);o=b,a=!1}function d(w){if(w===""){p();return}if(w.startsWith(":")){s&&s(w.slice(w.startsWith(": ")?2:1));return}let m=w.indexOf(":");if(m!==-1){let _=w.slice(0,m),b=w[m+1]===" "?2:1,v=w.slice(m+b);f(_,v,w);return}f(w,"",w)}function f(w,m,_){switch(w){case"event":u=m;break;case"data":c=`${c}${m}
1319
+ ${k4}`}async function BS(r){if(!r.pmForcedAsk&&P4(r.ctx,r.config))return{via:"fast-path:accept-edits"};if(!r.pmForcedAsk&&A4(r.ctx.toolName))return{via:"fast-path:allowlist"};if(r.pmForcedAsk)return{via:"fallback",reason:"ask_rule"};if(r.skipClassifierReason)return{via:"fallback",reason:r.skipClassifierReason};let e=await S4({toolName:r.ctx.toolName,toolParams:r.toolParams,messages:r.messages,config:r.config,signal:r.signal});return{via:"classifier",shouldBlock:e.shouldBlock,reason:e.reason,unavailable:e.unavailable===!0,stage:e.stage,durationMs:e.durationMs}}g();g();g();function I4(r,e,t={kind:"default"}){for(let n of r)if(O4(n.value))return{value:n.value,source:n.source};return{value:e,source:t}}function iI(r){for(let e of r)if(O4(e.value))return{value:e.value,source:e.source}}function O4(r){return!(r==null||typeof r=="string"&&r.trim()==="")}function Qm(r){return{kind:"cli",detail:r}}function mbe(r){return{kind:"env",envKey:r}}function yh(r){return{kind:"settings",settingsPath:r}}function wh(r,e,t){return{kind:"modelProviders",authType:r,modelId:e,detail:t}}function oI(r){return{kind:"default",detail:r}}function nu(r){return{kind:"computed",detail:r}}function jS(r,e,t){let n=r[e];return{value:n!==void 0?t?t(n):n:void 0,source:mbe(e)}}function Qn(r,e){return{value:r,source:e}}var _h="MATILDA_API_KEY",gbe="https://matilda.maincode.com/api/v1/code",ybe="matilda-code-1.0";function wbe(r){if(!r)return!0;try{let{hostname:e}=new URL(r);return e==="matilda.maincode.com"||e.endsWith(".matilda.maincode.com")}catch{return!1}}function L4(r,e,t,n){if(n?.generationConfig?.timeout!==void 0)return;let s=r.MATILDA_CODE_API_TIMEOUT_MS;if(s===void 0)return;let o=Number(s);Number.isFinite(o)&&o>0&&(e.timeout=Math.floor(o),t.timeout={kind:"env",envKey:"MATILDA_CODE_API_TIMEOUT_MS"})}function N4(r){let{authType:e,cli:t,settings:n,env:s,modelProvider:o,proxy:a}=r,l=[],c={};if(e==="matilda-oauth")return _be(r,l);let u=e?em[e]:{model:[],apiKey:[],baseUrl:[]},h=[];e&&o&&h.push(Qn(o.id,wh(e,o.id,"model.id"))),t?.model&&h.push(Qn(t.model,Qm("--model"))),e==="openai"&&s[_h]&&!s.OPENAI_MODEL&&!s.MATILDA_MODEL&&h.push(Qn(ybe,{kind:"env",envKey:_h}));for(let S of u.model)h.push(jS(s,S));n?.model&&h.push(Qn(n.model,yh("model.name")));let d=e?vP[e]:"",f=I4(h,d,oI(d));c.model=f.source;let p=[];if(e&&o?.envKey){let S=s[o.envKey];S&&p.push(Qn(S,{kind:"env",envKey:o.envKey,via:wh(e,o.id,"envKey")}))}if(t?.apiKey&&p.push(Qn(t.apiKey,Qm("--openaiApiKey"))),!o?.envKey){let S=s[_h];e==="openai"&&S&&wbe(s.OPENAI_BASE_URL)&&p.push(Qn(S,{kind:"env",envKey:_h}));for(let E of u.apiKey)p.push(jS(s,E))}n?.apiKey&&p.push(Qn(n.apiKey,yh("security.auth.apiKey")));let y=iI(p);y&&(c.apiKey=y.source);let w=[];e&&o?.baseUrl&&w.push(Qn(o.baseUrl,wh(e,o.id,"baseUrl"))),t?.baseUrl&&w.push(Qn(t.baseUrl,Qm("--openaiBaseUrl"))),e==="openai"&&s[_h]&&!s.OPENAI_BASE_URL&&w.push(Qn(gbe,{kind:"env",envKey:_h}));for(let S of u.baseUrl)w.push(jS(s,S));n?.baseUrl&&w.push(Qn(n.baseUrl,yh("security.auth.baseUrl")));let m=iI(w);m&&(c.baseUrl=m.source);let _;e&&o?.envKey&&(_=o.envKey,c.apiKeyEnvKey={...wh(e,o.id,"envKey"),envKey:o.envKey});let b=F4(n?.generationConfig,o?.generationConfig,e,o?.id??f.value,c);L4(s,b,c,o);let v={authType:e,model:f.value||"",apiKey:y?.value,apiKeyEnvKey:_,baseUrl:m?.value,proxy:a,...b};return a&&(c.proxy=nu("Config.getProxy()")),c.authType=nu("provided by caller"),{config:v,sources:c,warnings:l}}function _be(r,e){let{cli:t,settings:n,proxy:s,modelProvider:o}=r,a={},l=new Set(SP),c=t?.model||n?.model,u,h;if(c&&l.has(c))u=c,h=t?.model?Qm("--model"):yh("model.name");else{if(c){let y=c.includes("vl")||c.includes("vision")?" Note: vision-model has been removed since coder-model now supports vision capabilities.":"";e.push(`Warning: Unsupported Matilda OAuth model '${c}', falling back to '${Do}'.${y}`)}u=Do,h=oI(`fallback to '${Do}'`)}a.model=h,a.apiKey=nu("Matilda OAuth dynamic token"),a.authType=nu("provided by caller"),s&&(a.proxy=nu("Config.getProxy()"));let d=F4(n?.generationConfig,o?.generationConfig,"matilda-oauth",u,a);return L4(r.env,d,a,o),{config:{authType:"matilda-oauth",model:u,apiKey:"MATILDA_OAUTH_DYNAMIC_TOKEN",proxy:s,...d},sources:a,warnings:e}}function F4(r,e,t,n,s){let o={};for(let a of Rc)t&&e&&a in e?(o[a]=e[a],s[a]=wh(t,n||"",`generationConfig.${a}`)):r&&a in r&&(o[a]=r[a],s[a]=yh(`model.generationConfig.${a}`));return o.modalities===void 0&&n&&(o.modalities=Q2(n),s.modalities=nu("auto-detected from model")),o}g();g();$4();var Ebe=zS();function Vi(r){if(typeof r!="string")throw new TypeError(`Expected a \`string\`, got \`${typeof r}\``);return r.replace(Ebe,"")}var U4=class{format(e,t,n){let s={};return e!==void 0&&(s.response=Vi(e)),t&&(s.stats=t),n&&(s.error=n),JSON.stringify(s,null,2)}formatError(e,t){let n={type:e.constructor.name,message:Vi(e.message),...t&&{code:t}};return this.format(void 0,void 0,n)}};g();g();import*as bh from"node:path";function H4(r,e,t){let s="command"in e?String(e.command):void 0,o=typeof e.directory=="string"?bh.isAbsolute(e.directory)?e.directory:bh.resolve(t,e.directory):void 0,a=typeof e.file_path=="string"?e.file_path:void 0;a===void 0&&typeof e.notebook_path=="string"&&(a=e.notebook_path),a===void 0&&typeof e.path=="string"&&(a=bh.isAbsolute(e.path)?e.path:bh.resolve(t,e.path));let l;if(typeof e.url=="string")try{l=new URL(e.url).hostname}catch{}let c=typeof e.skill=="string"?e.skill:typeof e.subagent_type=="string"?e.subagent_type:void 0;return{toolName:r,command:s,cwd:o,filePath:a,domain:l,specifier:c}}async function B4(r,e,t){let n=e,s=!1;if(r&&e!=="deny"&&r.hasRelevantRules(t)){let o=await r.evaluate(t);o!=="default"&&(n=o,o==="ask"&&r.hasMatchingAskRule(t)&&(s=!0))}return{finalPermission:n,pmForcedAsk:s}}function j4(r,e){(r.type==="exec"||r.type==="mcp"||r.type==="info")&&!r.permissionRules&&(r.permissionRules=M3(e))}async function z4(r,e,t,n,s){if(r!=="proceed_always"&&r!=="proceed_always_project"&&r!=="proceed_always_user")return;let o=r==="proceed_always_user"?"user":"project",a=e?.permissionRules,c=s?.permissionRules??a??[];if(c.length>0)for(let u of c)t&&await t(o,"allow",u),n?.addPersistentRule(u,"allow")}async function aI(r,e,t,n){let s=await e.getDefaultPermission(),o=r.getPermissionManager?.(),a=H4(t,n,r.getTargetDir?.()??""),{finalPermission:l,pmForcedAsk:c}=await B4(o,s,a),u={finalPermission:l,pmForcedAsk:c,pmCtx:a};if(l==="deny")if(s==="deny")u.denyMessage=`Tool "${t}" is denied: the tool's default permission is 'deny'.`;else{let h=o?.findMatchingDenyRule(a),d=h?` Matching deny rule: "${h}".`:"";u.denyMessage=`Tool "${t}" is denied by permission rules.${d}`}return u}function q4(r,e,t){let n=t===R.ASK_USER_QUESTION;return e==="bogan"&&!n?!1:r==="ask"||r==="default"}function W4(r,e){return e&&r==="allow"?"ask":r}function G4(r,e,t,n,s){return r&&!e&&!t&&!s&&n?.type!=="info"}function V4(r,e){return r==="auto-edit"&&(e?.type==="edit"||e?.type==="info")}g();function Ert(r){return $o(r,{verbose:!0})}g();var K4=10*1024*1024;function Tbe(){let r=process.env.MATILDA_CODE_MAX_INLINE_MEDIA_BYTES;if(r===void 0||r.trim()==="")return K4;let e=Number(r);return Number.isFinite(e)&&e>0?Math.floor(e):K4}function kbe(r){let e=0;if(r.startsWith("data:")){let s=r.indexOf(",");s!==-1&&(e=s+1)}let t=r.length-e;if(t===0)return 0;let n=r.endsWith("==")?2:r.endsWith("=")?1:0;return Math.floor(t*3/4)-n}function Y4(r){return(r/(1024*1024)).toFixed(1)}function xbe(r,e,t){return`[Media omitted: ${Kd(r)} is ~${Y4(e)}MB, exceeding the ${Y4(t)}MB inline limit. Ask the user to resize/compress it, or reference it via an @file path so it can be read from disk.]`}function Art(r,e=Tbe()){let t=r.inlineData?.data;if(!t)return r;let n=kbe(t);if(n<=e)return r;let s=r.inlineData?.mimeType??"application/octet-stream";return{text:xbe(s,n,e)}}g();function Mrt(r,e,t){return JSON.stringify({insight_progress:{stage:r,progress:e,detail:t}})}function Irt(r){return JSON.stringify({insight_ready:{path:r}})}function Ort(r){return JSON.stringify({insight_error:{error:r}})}function Drt(r){try{let e=JSON.parse(r);if(e.insight_progress){let{stage:n,progress:s,detail:o}=e.insight_progress;if(typeof n=="string"&&typeof s=="number")return{type:"insight_progress",stage:n,progress:s,detail:typeof o=="string"?o:void 0}}if(e.insight_ready){let{path:n}=e.insight_ready;if(typeof n=="string")return{type:"insight_ready",path:n}}let t=e.insight_error;if(t&&typeof t.error=="string")return{type:"insight_error",error:t.error}}catch{return null}return null}g();import qS from"node:path";import{promises as Ki}from"node:fs";var Abe="logs.json",Rbe=(t=>(t.USER="user",t.MODEL_SWITCH="model_switch",t))(Rbe||{});function Pbe(r){return encodeURIComponent(r)}function Brt(r){try{return decodeURIComponent(r)}catch{return r.replace(/%([0-9A-F]{2})/g,(t,n)=>String.fromCharCode(parseInt(n,16)))}}var J4=class{constructor(e,t){this.storage=t;this.sessionId=e,this.debugLogger=$("LOGGER")}matildaDir;logFilePath;sessionId;messageId=0;initialized=!1;logs=[];lastLoggedUserEntry=null;writeQueue=Promise.resolve();debugLogger;serialize(e){let t=this.writeQueue.then(()=>e());return this.writeQueue=t.catch(()=>{}),t}async _readLogFile(){if(!this.logFilePath)throw new Error("Log file path not set during read attempt.");try{let e=await Ki.readFile(this.logFilePath,"utf-8"),t=JSON.parse(e);return Array.isArray(t)?t.filter(n=>typeof n.sessionId=="string"&&typeof n.messageId=="number"&&typeof n.timestamp=="string"&&typeof n.type=="string"&&typeof n.message=="string"):(this.debugLogger.debug(`Log file at ${this.logFilePath} is not a valid JSON array. Starting with empty logs.`),await this._backupCorruptedLogFile("malformed_array"),[])}catch(e){if(e.code==="ENOENT")return[];if(e instanceof SyntaxError)return this.debugLogger.debug(`Invalid JSON in log file ${this.logFilePath}. Backing up and starting fresh.`,e),await this._backupCorruptedLogFile("invalid_json"),[];throw this.debugLogger.debug(`Failed to read or parse log file ${this.logFilePath}:`,e),e}}async _backupCorruptedLogFile(e){if(!this.logFilePath)return;let t=`${this.logFilePath}.${e}.${Date.now()}.bak`;try{await Ki.rename(this.logFilePath,t),this.debugLogger.debug(`Backed up corrupted log file to ${t}`)}catch{}}async initialize(){if(!this.initialized){this.matildaDir=this.storage.getProjectTempDir(),this.logFilePath=qS.join(this.matildaDir,Abe);try{await Ki.mkdir(this.matildaDir,{recursive:!0});let e=!0;try{await Ki.access(this.logFilePath)}catch{e=!1}this.logs=await this._readLogFile(),!e&&this.logs.length===0&&await Xe(this.logFilePath,"[]",{encoding:"utf-8"});let t=this.logs.filter(n=>n.sessionId===this.sessionId);this.messageId=t.length>0?Math.max(...t.map(n=>n.messageId))+1:0,this.initialized=!0}catch(e){this.debugLogger.error("Failed to initialize logger:",e),this.initialized=!1}}}async _updateLogFile(e){if(!this.logFilePath)throw this.debugLogger.debug("Log file path not set. Cannot persist log entry."),new Error("Log file path not set during update attempt.");let t;try{t=await this._readLogFile()}catch(a){throw this.debugLogger.debug("Critical error reading log file before append:",a),a}let n=t.filter(a=>a.sessionId===e.sessionId),s=n.length>0?Math.max(...n.map(a=>a.messageId))+1:0;if(e.messageId=s,t.some(a=>a.sessionId===e.sessionId&&a.messageId===e.messageId&&a.timestamp===e.timestamp&&a.message===e.message))return this.debugLogger.debug(`Duplicate log entry detected and skipped: session ${e.sessionId}, messageId ${e.messageId}`),this.logs=t,null;t.push(e);try{return await Xe(this.logFilePath,JSON.stringify(t,null,2),{encoding:"utf-8"}),this.logs=t,e}catch(a){throw this.debugLogger.debug("Error writing to log file:",a),a}}async getPreviousUserMessages(){return this.initialized?this.logs.filter(e=>e.type==="user").sort((e,t)=>{let n=new Date(e.timestamp).getTime();return new Date(t.timestamp).getTime()-n}).map(e=>e.message):[]}async logMessage(e,t){if(!this.initialized||this.sessionId===void 0){this.debugLogger.debug("Logger not initialized or session ID missing. Cannot log message.");return}let n={sessionId:this.sessionId,messageId:this.messageId,type:e,message:t,timestamp:new Date().toISOString()};try{let s=await this.serialize(()=>this._updateLogFile(n));s?(this.messageId=s.messageId+1,s.type==="user"&&(this.lastLoggedUserEntry=s)):e==="user"&&(this.lastLoggedUserEntry=n)}catch{e==="user"&&(this.lastLoggedUserEntry=null)}}async removeLastUserMessage(){if(!this.initialized||!this.logFilePath)return!1;let e=this.lastLoggedUserEntry;if(!e)return!1;this.lastLoggedUserEntry=null;let t=a=>a.sessionId===e.sessionId&&a.messageId===e.messageId&&a.timestamp===e.timestamp&&a.message===e.message&&a.type===e.type,n=this.logs.findIndex(t);n>=0&&(this.logs=[...this.logs.slice(0,n),...this.logs.slice(n+1)]);let s=()=>{if(n>=0&&this.logs.findIndex(t)===-1){let a=Math.min(n,this.logs.length);this.logs=[...this.logs.slice(0,a),e,...this.logs.slice(a)]}this.lastLoggedUserEntry===null&&(this.lastLoggedUserEntry=e)},o=this.logFilePath;return this.serialize(async()=>{let a;try{a=await this._readLogFile()}catch(c){return this.debugLogger.debug("Failed to read log file while undoing last user entry:",c),s(),!1}let l=a.findIndex(t);if(l===-1)return this.logs=a,!1;a.splice(l,1);try{return await Xe(o,JSON.stringify(a,null,2),{encoding:"utf-8"}),this.logs=a,e.sessionId===this.sessionId&&this.messageId===e.messageId+1&&(this.messageId=e.messageId),!0}catch(c){return this.debugLogger.debug("Failed to write log file while undoing last user entry:",c),s(),!1}})}_checkpointPath(e){if(!e.length)throw new Error("No checkpoint tag specified.");if(!this.matildaDir)throw new Error("Checkpoint file path not set.");let t=Pbe(e);return qS.join(this.matildaDir,`checkpoint-${t}.json`)}async _getCheckpointPath(e){let t=this._checkpointPath(e);try{return await Ki.access(t),t}catch(s){if(s.code!=="ENOENT")throw s}let n=qS.join(this.matildaDir,`checkpoint-${e}.json`);try{return await Ki.access(n),n}catch(s){if(s.code!=="ENOENT")throw s}return t}async saveCheckpoint(e,t){if(!this.initialized){this.debugLogger.error("Logger not initialized or checkpoint file path not set. Cannot save a checkpoint.");return}let n=this._checkpointPath(t);try{await Xe(n,JSON.stringify(e,null,2),{encoding:"utf-8"})}catch(s){this.debugLogger.error("Error writing to checkpoint file:",s)}}async loadCheckpoint(e){if(!this.initialized)return this.debugLogger.error("Logger not initialized or checkpoint file path not set. Cannot load checkpoint."),[];let t=await this._getCheckpointPath(e);try{let n=await Ki.readFile(t,"utf-8"),s=JSON.parse(n);return Array.isArray(s)?s:(this.debugLogger.warn(`Checkpoint file at ${t} is not a valid JSON array. Returning empty checkpoint.`),[])}catch(n){return n.code==="ENOENT"?[]:(this.debugLogger.error(`Failed to read or parse checkpoint file ${t}:`,n),[])}}async deleteCheckpoint(e){if(!this.initialized||!this.matildaDir)return this.debugLogger.error("Logger not initialized or checkpoint file path not set. Cannot delete checkpoint."),!1;let t=!1,n=this._checkpointPath(e);try{await Ki.unlink(n),t=!0}catch(o){if(o.code!=="ENOENT")throw this.debugLogger.error(`Failed to delete checkpoint file ${n}:`,o),o}let s=qS.join(this.matildaDir,`checkpoint-${e}.json`);if(n!==s)try{await Ki.unlink(s),t=!0}catch(o){if(o.code!=="ENOENT")throw this.debugLogger.error(`Failed to delete checkpoint file ${s}:`,o),o}return t}async checkpointExists(e){if(!this.initialized)throw new Error("Logger not initialized. Cannot check for checkpoint existence.");let t;try{return t=await this._getCheckpointPath(e),await Ki.access(t),!0}catch(n){if(n.code==="ENOENT")return!1;throw this.debugLogger.error(`Failed to check checkpoint existence for ${t??`path for tag "${e}"`}:`,n),n}}close(){this.initialized=!1,this.logFilePath=void 0,this.logs=[],this.lastLoggedUserEntry=null,this.writeQueue=Promise.resolve(),this.sessionId=void 0,this.messageId=0}};g();async function Wrt(r,e,t,n={}){return new Promise((s,o)=>{new vh({config:r,chatRecordingService:r.getChatRecordingService(),outputUpdateHandler:n.outputUpdateHandler,onAllToolCallsComplete:async a=>{n.onAllToolCallsComplete&&await n.onAllToolCallsComplete(a),s(a[0].response)},onToolCallsUpdate:n.onToolCallsUpdate,onToolCallsCompleteError:o,getPreferredEditor:()=>{},onEditorClose:()=>{}}).schedule(e,t).catch(o)})}g();import{spawn as wK}from"node:child_process";import{StringDecoder as yK}from"node:string_decoder";g();g();g();g();g();function Sh(r){return!!r._zod}function ai(r,e){return Sh(r)?kP(r,e):r.safeParse(e)}function WS(r){if(!r)return;let e;if(Sh(r)?e=r._zod?.def?.shape:e=r.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function X4(r){if(Sh(r)){let o=r._zod?.def;if(o){if(o.value!==void 0)return o.value;if(Array.isArray(o.values)&&o.values.length>0)return o.values[0]}}let t=r._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=r.value;if(n!==void 0)return n}g();var Eh="2025-11-25";var Z4=[Eh,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],al="io.modelcontextprotocol/related-task",VS="2.0",yr=bz(r=>r!==null&&(typeof r=="object"||typeof r=="function")),Q4=Ut([B(),Ze().int()]),e6=B(),nnt=mr({ttl:Ze().optional(),pollInterval:Ze().optional()}),Obe=le({ttl:Ze().optional()}),Dbe=le({taskId:B()}),cI=mr({progressToken:Q4.optional(),[al]:Dbe.optional()}),es=le({_meta:cI.optional()}),tg=es.extend({task:Obe.optional()}),t6=r=>tg.safeParse(r).success,Dr=le({method:B(),params:es.loose().optional()}),Is=le({_meta:cI.optional()}),Os=le({method:B(),params:Is.loose().optional()}),Lr=mr({_meta:cI.optional()}),KS=Ut([B(),Ze().int()]),r6=le({jsonrpc:de(VS),id:KS,...Dr.shape}).strict(),rg=r=>r6.safeParse(r).success,n6=le({jsonrpc:de(VS),...Os.shape}).strict(),s6=r=>n6.safeParse(r).success,uI=le({jsonrpc:de(VS),id:KS,result:Lr}).strict(),su=r=>uI.safeParse(r).success;var be;(function(r){r[r.ConnectionClosed=-32e3]="ConnectionClosed",r[r.RequestTimeout=-32001]="RequestTimeout",r[r.ParseError=-32700]="ParseError",r[r.InvalidRequest=-32600]="InvalidRequest",r[r.MethodNotFound=-32601]="MethodNotFound",r[r.InvalidParams=-32602]="InvalidParams",r[r.InternalError=-32603]="InternalError",r[r.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(be||(be={}));var dI=le({jsonrpc:de(VS),id:KS.optional(),error:le({code:Ze().int(),message:B(),data:rr().optional()})}).strict();var i6=r=>dI.safeParse(r).success;var ll=Ut([r6,n6,uI,dI]),snt=Ut([uI,dI]),iu=Lr.strict(),Lbe=Is.extend({requestId:KS.optional(),reason:B().optional()}),YS=Os.extend({method:de("notifications/cancelled"),params:Lbe}),Nbe=le({src:B(),mimeType:B().optional(),sizes:oe(B()).optional(),theme:Vn(["light","dark"]).optional()}),ng=le({icons:oe(Nbe).optional()}),Ch=le({name:B(),title:B().optional()}),o6=Ch.extend({...Ch.shape,...ng.shape,version:B(),websiteUrl:B().optional(),description:B().optional()}),Fbe=AP(le({applyDefaults:Tt().optional()}),At(B(),rr())),$be=RP(r=>r&&typeof r=="object"&&!Array.isArray(r)&&Object.keys(r).length===0?{form:{}}:r,AP(le({form:Fbe.optional(),url:yr.optional()}),At(B(),rr()).optional())),Ube=mr({list:yr.optional(),cancel:yr.optional(),requests:mr({sampling:mr({createMessage:yr.optional()}).optional(),elicitation:mr({create:yr.optional()}).optional()}).optional()}),Hbe=mr({list:yr.optional(),cancel:yr.optional(),requests:mr({tools:mr({call:yr.optional()}).optional()}).optional()}),Bbe=le({experimental:At(B(),yr).optional(),sampling:le({context:yr.optional(),tools:yr.optional()}).optional(),elicitation:$be.optional(),roots:le({listChanged:Tt().optional()}).optional(),tasks:Ube.optional(),extensions:At(B(),yr).optional()}),jbe=es.extend({protocolVersion:B(),capabilities:Bbe,clientInfo:o6}),zbe=Dr.extend({method:de("initialize"),params:jbe});var qbe=le({experimental:At(B(),yr).optional(),logging:yr.optional(),completions:yr.optional(),prompts:le({listChanged:Tt().optional()}).optional(),resources:le({subscribe:Tt().optional(),listChanged:Tt().optional()}).optional(),tools:le({listChanged:Tt().optional()}).optional(),tasks:Hbe.optional(),extensions:At(B(),yr).optional()}),hI=Lr.extend({protocolVersion:B(),capabilities:qbe,serverInfo:o6,instructions:B().optional()}),a6=Os.extend({method:de("notifications/initialized"),params:Is.optional()}),l6=r=>a6.safeParse(r).success,JS=Dr.extend({method:de("ping"),params:es.optional()}),Wbe=le({progress:Ze(),total:Zt(Ze()),message:Zt(B())}),Gbe=le({...Is.shape,...Wbe.shape,progressToken:Q4}),XS=Os.extend({method:de("notifications/progress"),params:Gbe}),Vbe=es.extend({cursor:e6.optional()}),sg=Dr.extend({params:Vbe.optional()}),ig=Lr.extend({nextCursor:e6.optional()}),Kbe=Vn(["working","input_required","completed","failed","cancelled"]),og=le({taskId:B(),status:Kbe,ttl:Ut([Ze(),wz()]),createdAt:B(),lastUpdatedAt:B(),pollInterval:Zt(Ze()),statusMessage:Zt(B())}),ou=Lr.extend({task:og}),Ybe=Is.merge(og),ag=Os.extend({method:de("notifications/tasks/status"),params:Ybe}),ZS=Dr.extend({method:de("tasks/get"),params:es.extend({taskId:B()})}),QS=Lr.merge(og),eC=Dr.extend({method:de("tasks/result"),params:es.extend({taskId:B()})}),int=Lr.loose(),tC=sg.extend({method:de("tasks/list")}),rC=ig.extend({tasks:oe(og)}),nC=Dr.extend({method:de("tasks/cancel"),params:es.extend({taskId:B()})}),c6=Lr.merge(og),u6=le({uri:B(),mimeType:Zt(B()),_meta:At(B(),rr()).optional()}),d6=u6.extend({text:B()}),fI=B().refine(r=>{try{return atob(r),!0}catch{return!1}},{message:"Invalid Base64 string"}),h6=u6.extend({blob:fI}),lg=Vn(["user","assistant"]),Th=le({audience:oe(lg).optional(),priority:Ze().min(0).max(1).optional(),lastModified:gz.datetime({offset:!0}).optional()}),f6=le({...Ch.shape,...ng.shape,uri:B(),description:Zt(B()),mimeType:Zt(B()),size:Zt(Ze()),annotations:Th.optional(),_meta:Zt(mr({}))}),Jbe=le({...Ch.shape,...ng.shape,uriTemplate:B(),description:Zt(B()),mimeType:Zt(B()),annotations:Th.optional(),_meta:Zt(mr({}))}),Xbe=sg.extend({method:de("resources/list")}),pI=ig.extend({resources:oe(f6)}),Zbe=sg.extend({method:de("resources/templates/list")}),mI=ig.extend({resourceTemplates:oe(Jbe)}),gI=es.extend({uri:B()}),Qbe=gI,eve=Dr.extend({method:de("resources/read"),params:Qbe}),cg=Lr.extend({contents:oe(Ut([d6,h6]))}),yI=Os.extend({method:de("notifications/resources/list_changed"),params:Is.optional()}),tve=gI,rve=Dr.extend({method:de("resources/subscribe"),params:tve}),nve=gI,sve=Dr.extend({method:de("resources/unsubscribe"),params:nve}),ive=Is.extend({uri:B()}),ove=Os.extend({method:de("notifications/resources/updated"),params:ive}),ave=le({name:B(),description:Zt(B()),required:Zt(Tt())}),lve=le({...Ch.shape,...ng.shape,description:Zt(B()),arguments:Zt(oe(ave)),_meta:Zt(mr({}))}),cve=sg.extend({method:de("prompts/list")}),ug=ig.extend({prompts:oe(lve)}),uve=es.extend({name:B(),arguments:At(B(),B()).optional()}),dve=Dr.extend({method:de("prompts/get"),params:uve}),wI=le({type:de("text"),text:B(),annotations:Th.optional(),_meta:At(B(),rr()).optional()}),_I=le({type:de("image"),data:fI,mimeType:B(),annotations:Th.optional(),_meta:At(B(),rr()).optional()}),bI=le({type:de("audio"),data:fI,mimeType:B(),annotations:Th.optional(),_meta:At(B(),rr()).optional()}),hve=le({type:de("tool_use"),name:B(),id:B(),input:At(B(),rr()),_meta:At(B(),rr()).optional()}),fve=le({type:de("resource"),resource:Ut([d6,h6]),annotations:Th.optional(),_meta:At(B(),rr()).optional()}),pve=f6.extend({type:de("resource_link")}),vI=Ut([wI,_I,bI,pve,fve]),mve=le({role:lg,content:vI}),dg=Lr.extend({description:B().optional(),messages:oe(mve)}),SI=Os.extend({method:de("notifications/prompts/list_changed"),params:Is.optional()}),gve=le({title:B().optional(),readOnlyHint:Tt().optional(),destructiveHint:Tt().optional(),idempotentHint:Tt().optional(),openWorldHint:Tt().optional()}),yve=le({taskSupport:Vn(["required","optional","forbidden"]).optional()}),p6=le({...Ch.shape,...ng.shape,description:B().optional(),inputSchema:le({type:de("object"),properties:At(B(),yr).optional(),required:oe(B()).optional()}).catchall(rr()),outputSchema:le({type:de("object"),properties:At(B(),yr).optional(),required:oe(B()).optional()}).catchall(rr()).optional(),annotations:gve.optional(),execution:yve.optional(),_meta:At(B(),rr()).optional()}),wve=sg.extend({method:de("tools/list")}),hg=ig.extend({tools:oe(p6)}),Go=Lr.extend({content:oe(vI).default([]),structuredContent:At(B(),rr()).optional(),isError:Tt().optional()}),ont=Go.or(Lr.extend({toolResult:rr()})),_ve=tg.extend({name:B(),arguments:At(B(),rr()).optional()}),bve=Dr.extend({method:de("tools/call"),params:_ve}),CI=Os.extend({method:de("notifications/tools/list_changed"),params:Is.optional()}),m6=le({autoRefresh:Tt().default(!0),debounceMs:Ze().int().nonnegative().default(300)}),g6=Vn(["debug","info","notice","warning","error","critical","alert","emergency"]),vve=es.extend({level:g6}),Sve=Dr.extend({method:de("logging/setLevel"),params:vve}),Cve=Is.extend({level:g6,logger:B().optional(),data:rr()}),Eve=Os.extend({method:de("notifications/message"),params:Cve}),Tve=le({name:B().optional()}),kve=le({hints:oe(Tve).optional(),costPriority:Ze().min(0).max(1).optional(),speedPriority:Ze().min(0).max(1).optional(),intelligencePriority:Ze().min(0).max(1).optional()}),xve=le({mode:Vn(["auto","required","none"]).optional()}),Ave=le({type:de("tool_result"),toolUseId:B().describe("The unique identifier for the corresponding tool call."),content:oe(vI).default([]),structuredContent:le({}).loose().optional(),isError:Tt().optional(),_meta:At(B(),rr()).optional()}),Rve=xP("type",[wI,_I,bI]),GS=xP("type",[wI,_I,bI,hve,Ave]),Pve=le({role:lg,content:Ut([GS,oe(GS)]),_meta:At(B(),rr()).optional()}),Mve=tg.extend({messages:oe(Pve),modelPreferences:kve.optional(),systemPrompt:B().optional(),includeContext:Vn(["none","thisServer","allServers"]).optional(),temperature:Ze().optional(),maxTokens:Ze().int(),stopSequences:oe(B()).optional(),metadata:yr.optional(),tools:oe(p6).optional(),toolChoice:xve.optional()}),EI=Dr.extend({method:de("sampling/createMessage"),params:Mve}),TI=Lr.extend({model:B(),stopReason:Zt(Vn(["endTurn","stopSequence","maxTokens"]).or(B())),role:lg,content:Rve}),kI=Lr.extend({model:B(),stopReason:Zt(Vn(["endTurn","stopSequence","maxTokens","toolUse"]).or(B())),role:lg,content:Ut([GS,oe(GS)])}),Ive=le({type:de("boolean"),title:B().optional(),description:B().optional(),default:Tt().optional()}),Ove=le({type:de("string"),title:B().optional(),description:B().optional(),minLength:Ze().optional(),maxLength:Ze().optional(),format:Vn(["email","uri","date","date-time"]).optional(),default:B().optional()}),Dve=le({type:Vn(["number","integer"]),title:B().optional(),description:B().optional(),minimum:Ze().optional(),maximum:Ze().optional(),default:Ze().optional()}),Lve=le({type:de("string"),title:B().optional(),description:B().optional(),enum:oe(B()),default:B().optional()}),Nve=le({type:de("string"),title:B().optional(),description:B().optional(),oneOf:oe(le({const:B(),title:B()})),default:B().optional()}),Fve=le({type:de("string"),title:B().optional(),description:B().optional(),enum:oe(B()),enumNames:oe(B()).optional(),default:B().optional()}),$ve=Ut([Lve,Nve]),Uve=le({type:de("array"),title:B().optional(),description:B().optional(),minItems:Ze().optional(),maxItems:Ze().optional(),items:le({type:de("string"),enum:oe(B())}),default:oe(B()).optional()}),Hve=le({type:de("array"),title:B().optional(),description:B().optional(),minItems:Ze().optional(),maxItems:Ze().optional(),items:le({anyOf:oe(le({const:B(),title:B()}))}),default:oe(B()).optional()}),Bve=Ut([Uve,Hve]),jve=Ut([Fve,$ve,Bve]),zve=Ut([jve,Ive,Ove,Dve]),qve=tg.extend({mode:de("form").optional(),message:B(),requestedSchema:le({type:de("object"),properties:At(B(),zve),required:oe(B()).optional()})}),Wve=tg.extend({mode:de("url"),message:B(),elicitationId:B(),url:B().url()}),Gve=Ut([qve,Wve]),xI=Dr.extend({method:de("elicitation/create"),params:Gve}),Vve=Is.extend({elicitationId:B()}),Kve=Os.extend({method:de("notifications/elicitation/complete"),params:Vve}),AI=Lr.extend({action:Vn(["accept","decline","cancel"]),content:RP(r=>r===null?void 0:r,At(B(),Ut([B(),Ze(),Tt(),oe(B())])).optional())}),Yve=le({type:de("ref/resource"),uri:B()});var Jve=le({type:de("ref/prompt"),name:B()}),Xve=es.extend({ref:Ut([Jve,Yve]),argument:le({name:B(),value:B()}),context:le({arguments:At(B(),B()).optional()}).optional()}),Zve=Dr.extend({method:de("completion/complete"),params:Xve});var RI=Lr.extend({completion:mr({values:oe(B()).max(100),total:Zt(Ze().int()),hasMore:Zt(Tt())})}),Qve=le({uri:B().startsWith("file://"),name:B().optional(),_meta:At(B(),rr()).optional()}),sC=Dr.extend({method:de("roots/list"),params:es.optional()}),eSe=Lr.extend({roots:oe(Qve)}),tSe=Os.extend({method:de("notifications/roots/list_changed"),params:Is.optional()}),ant=Ut([JS,zbe,Zve,Sve,dve,cve,Xbe,Zbe,eve,rve,sve,bve,wve,ZS,eC,tC,nC]),lnt=Ut([YS,XS,a6,tSe,ag]),cnt=Ut([iu,TI,kI,AI,eSe,QS,rC,ou]),unt=Ut([JS,EI,xI,sC,ZS,eC,tC,nC]),dnt=Ut([YS,XS,Eve,ove,yI,CI,SI,ag,Kve]),hnt=Ut([iu,hI,RI,dg,ug,pI,mI,cg,Go,hg,QS,rC,ou]),we=class r extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,t,n){if(e===be.UrlElicitationRequired&&n){let s=n;if(s.elicitations)return new lI(s.elicitations,t)}return new r(e,t,n)}},lI=class extends we{constructor(e,t=`URL elicitation${e.length>1?"s":""} required`){super(be.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};g();function cl(r){return r==="completed"||r==="failed"||r==="cancelled"}g();g();g();var rSe=Symbol("Let zodToJsonSchema decide on which parser to use");g();g();g();g();g();g();g();g();g();g();g();g();g();g();g();g();g();g();g();g();var cst=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");g();g();g();g();g();g();g();g();g();g();g();g();g();g();g();g();g();function PI(r){let t=WS(r)?.method;if(!t)throw new Error("Schema is missing a method literal");let n=X4(t);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function MI(r,e){let t=ai(r,e);if(!t.success)throw t.error;return t.data}var lSe=6e4,iC=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(YS,t=>{this._oncancel(t)}),this.setNotificationHandler(XS,t=>{this._onprogress(t)}),this.setRequestHandler(JS,t=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(ZS,async(t,n)=>{let s=await this._taskStore.getTask(t.params.taskId,n.sessionId);if(!s)throw new we(be.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(eC,async(t,n)=>{let s=async()=>{let o=t.params.taskId;if(this._taskMessageQueue){let l;for(;l=await this._taskMessageQueue.dequeue(o,n.sessionId);){if(l.type==="response"||l.type==="error"){let c=l.message,u=c.id,h=this._requestResolvers.get(u);if(h)if(this._requestResolvers.delete(u),l.type==="response")h(c);else{let d=c,f=new we(d.error.code,d.error.message,d.error.data);h(f)}else{let d=l.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(l.message,{relatedRequestId:n.requestId})}}let a=await this._taskStore.getTask(o,n.sessionId);if(!a)throw new we(be.InvalidParams,`Task not found: ${o}`);if(!cl(a.status))return await this._waitForTaskUpdate(o,n.signal),await s();if(cl(a.status)){let l=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...l,_meta:{...l._meta,[al]:{taskId:o}}}}return await s()};return await s()}),this.setRequestHandler(tC,async(t,n)=>{try{let{tasks:s,nextCursor:o}=await this._taskStore.listTasks(t.params?.cursor,n.sessionId);return{tasks:s,nextCursor:o,_meta:{}}}catch(s){throw new we(be.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(nC,async(t,n)=>{try{let s=await this._taskStore.getTask(t.params.taskId,n.sessionId);if(!s)throw new we(be.InvalidParams,`Task not found: ${t.params.taskId}`);if(cl(s.status))throw new we(be.InvalidParams,`Cannot cancel task in terminal status: ${s.status}`);await this._taskStore.updateTaskStatus(t.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(t.params.taskId);let o=await this._taskStore.getTask(t.params.taskId,n.sessionId);if(!o)throw new we(be.InvalidParams,`Task not found after cancellation: ${t.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof we?s:new we(be.InvalidRequest,`Failed to cancel task: ${s instanceof Error?s.message:String(s)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,s,o=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(s,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:o,onTimeout:s})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),we.fromError(be.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=o=>{n?.(o),this._onerror(o)};let s=this._transport?.onmessage;this._transport.onmessage=(o,a)=>{s?.(o,a),su(o)||i6(o)?this._onresponse(o):rg(o)?this._onrequest(o,a):s6(o)?this._onnotification(o):this._onerror(new Error(`Unknown message type: ${JSON.stringify(o)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let t=we.fromError(be.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(t)}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,t){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,s=this._transport,o=e.params?._meta?.[al]?.taskId;if(n===void 0){let h={jsonrpc:"2.0",id:e.id,error:{code:be.MethodNotFound,message:"Method not found"}};o&&this._taskMessageQueue?this._enqueueTaskMessage(o,{type:"error",message:h,timestamp:Date.now()},s?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):s?.send(h).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let a=new AbortController;this._requestHandlerAbortControllers.set(e.id,a);let l=t6(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,s?.sessionId):void 0,u={signal:a.signal,sessionId:s?.sessionId,_meta:e.params?._meta,sendNotification:async h=>{if(a.signal.aborted)return;let d={relatedRequestId:e.id};o&&(d.relatedTask={taskId:o}),await this.notification(h,d)},sendRequest:async(h,d,f)=>{if(a.signal.aborted)throw new we(be.ConnectionClosed,"Request was cancelled");let p={...f,relatedRequestId:e.id};o&&!p.relatedTask&&(p.relatedTask={taskId:o});let y=p.relatedTask?.taskId??o;return y&&c&&await c.updateTaskStatus(y,"input_required"),await this.request(h,d,p)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:o,taskStore:c,taskRequestedTtl:l?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};Promise.resolve().then(()=>{l&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async h=>{if(a.signal.aborted)return;let d={result:h,jsonrpc:"2.0",id:e.id};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"response",message:d,timestamp:Date.now()},s?.sessionId):await s?.send(d)},async h=>{if(a.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(h.code)?h.code:be.InternalError,message:h.message??"Internal error",...h.data!==void 0&&{data:h.data}}};o&&this._taskMessageQueue?await this._enqueueTaskMessage(o,{type:"error",message:d,timestamp:Date.now()},s?.sessionId):await s?.send(d)}).catch(h=>this._onerror(new Error(`Failed to send response: ${h}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===a&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,s=Number(t),o=this._progressHandlers.get(s);if(!o){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(s),l=this._timeoutInfo.get(s);if(l&&a&&l.resetTimeoutOnProgress)try{this._resetTimeout(s)}catch(c){this._responseHandlers.delete(s),this._progressHandlers.delete(s),this._cleanupTimeout(s),a(c);return}o(n)}_onresponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);if(n){if(this._requestResolvers.delete(t),su(e))n(e);else{let a=new we(e.error.code,e.error.message,e.error.data);n(a)}return}let s=this._responseHandlers.get(t);if(s===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let o=!1;if(su(e)&&e.result&&typeof e.result=="object"){let a=e.result;if(a.task&&typeof a.task=="object"){let l=a.task;typeof l.taskId=="string"&&(o=!0,this._taskProgressTokens.set(l.taskId,t))}}if(o||this._progressHandlers.delete(t),su(e))s(e);else{let a=we.fromError(e.error.code,e.error.message,e.error.data);s(a)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,n){let{task:s}=n??{};if(!s){try{yield{type:"result",result:await this.request(e,t,n)}}catch(a){yield{type:"error",error:a instanceof we?a:new we(be.InternalError,String(a))}}return}let o;try{let a=await this.request(e,ou,n);if(a.task)o=a.task.taskId,yield{type:"taskCreated",task:a.task};else throw new we(be.InternalError,"Task creation did not return a task");for(;;){let l=await this.getTask({taskId:o},n);if(yield{type:"taskStatus",task:l},cl(l.status)){l.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},t,n)}:l.status==="failed"?yield{type:"error",error:new we(be.InternalError,`Task ${o} failed`)}:l.status==="cancelled"&&(yield{type:"error",error:new we(be.InternalError,`Task ${o} was cancelled`)});return}if(l.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:o},t,n)};return}let c=l.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(a){yield{type:"error",error:a instanceof we?a:new we(be.InternalError,String(a))}}}request(e,t,n){let{relatedRequestId:s,resumptionToken:o,onresumptiontoken:a,task:l,relatedTask:c}=n??{};return new Promise((u,h)=>{let d=b=>{h(b)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),l&&this.assertTaskCapability(e.method)}catch(b){d(b);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,p={...e,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),p.params={...e.params,_meta:{...e.params?._meta||{},progressToken:f}}),l&&(p.params={...p.params,task:l}),c&&(p.params={...p.params,_meta:{...p.params?._meta||{},[al]:c}});let y=b=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(b)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:a}).catch(S=>this._onerror(new Error(`Failed to send cancellation: ${S}`)));let v=b instanceof we?b:new we(be.RequestTimeout,String(b));h(v)};this._responseHandlers.set(f,b=>{if(!n?.signal?.aborted){if(b instanceof Error)return h(b);try{let v=ai(t,b.result);v.success?u(v.data):h(v.error)}catch(v){h(v)}}}),n?.signal?.addEventListener("abort",()=>{y(n?.signal?.reason)});let w=n?.timeout??lSe,m=()=>y(we.fromError(be.RequestTimeout,"Request timed out",{timeout:w}));this._setupTimeout(f,w,n?.maxTotalTimeout,m,n?.resetTimeoutOnProgress??!1);let _=c?.taskId;if(_){let b=v=>{let S=this._responseHandlers.get(f);S?S(v):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,b),this._enqueueTaskMessage(_,{type:"request",message:p,timestamp:Date.now()}).catch(v=>{this._cleanupTimeout(f),h(v)})}else this._transport.send(p,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:a}).catch(b=>{this._cleanupTimeout(f),h(b)})})}async getTask(e,t){return this.request({method:"tasks/get",params:e},QS,t)}async getTaskResult(e,t,n){return this.request({method:"tasks/result",params:e},t,n)}async listTasks(e,t){return this.request({method:"tasks/list",params:e},rC,t)}async cancelTask(e,t){return this.request({method:"tasks/cancel",params:e},c6,t)}async notification(e,t){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=t?.relatedTask?.taskId;if(n){let l={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[al]:t.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:l,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let l={...e,jsonrpc:"2.0"};t?.relatedTask&&(l={...l,params:{...l.params,_meta:{...l.params?._meta||{},[al]:t.relatedTask}}}),this._transport?.send(l,t).catch(c=>this._onerror(c))});return}let a={...e,jsonrpc:"2.0"};t?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[al]:t.relatedTask}}}),await this._transport.send(a,t)}setRequestHandler(e,t){let n=PI(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,o)=>{let a=MI(e,s);return Promise.resolve(t(a,o))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let n=PI(e);this._notificationHandlers.set(n,s=>{let o=MI(e,s);return Promise.resolve(t(o))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let s=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n,s)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let s of n)if(s.type==="request"&&rg(s.message)){let o=s.message.id,a=this._requestResolvers.get(o);a?(a(new we(be.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(o)):this._onerror(new Error(`Resolver missing for request ${o} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=this._options?.defaultTaskPollInterval??1e3;try{let s=await this._taskStore?.getTask(e);s?.pollInterval&&(n=s.pollInterval)}catch{}return new Promise((s,o)=>{if(t.aborted){o(new we(be.InvalidRequest,"Request cancelled"));return}let a=setTimeout(s,n);t.addEventListener("abort",()=>{clearTimeout(a),o(new we(be.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,t){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async s=>{if(!e)throw new Error("No request provided");return await n.createTask(s,e.id,{method:e.method,params:e.params},t)},getTask:async s=>{let o=await n.getTask(s,t);if(!o)throw new we(be.InvalidParams,"Failed to retrieve task: Task not found");return o},storeTaskResult:async(s,o,a)=>{await n.storeTaskResult(s,o,a,t);let l=await n.getTask(s,t);if(l){let c=ag.parse({method:"notifications/tasks/status",params:l});await this.notification(c),cl(l.status)&&this._cleanupTaskProgressHandler(s)}},getTaskResult:s=>n.getTaskResult(s,t),updateTaskStatus:async(s,o,a)=>{let l=await n.getTask(s,t);if(!l)throw new we(be.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(cl(l.status))throw new we(be.InvalidParams,`Cannot update task "${s}" from terminal status "${l.status}" to "${o}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(s,o,a,t);let c=await n.getTask(s,t);if(c){let u=ag.parse({method:"notifications/tasks/status",params:c});await this.notification(u),cl(c.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>n.listTasks(s,t)}}};function y6(r){return r!==null&&typeof r=="object"&&!Array.isArray(r)}function w6(r,e){let t={...r};for(let n in e){let s=n,o=e[s];if(o===void 0)continue;let a=t[s];y6(a)&&y6(o)?t[s]={...a,...o}:t[s]=o}return t}g();var O8=Ve(I8(),1),D8=Ve(She(),1);function sxe(){let r=new O8.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,D8.default)(r),r}var NC=class{constructor(e){this._ajv=e??sxe()}getValidator(e){let t="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>t(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}};g();var FC=class{constructor(e){this._client=e}async*callToolStream(e,t=Go,n){let s=this._client,o={...n,task:n?.task??(s.isToolTask(e.name)?{}:void 0)},a=s.requestStream({method:"tools/call",params:e},t,o),l=s.getToolOutputValidator(e.name);for await(let c of a){if(c.type==="result"&&l){let u=c.result;if(!u.structuredContent&&!u.isError){yield{type:"error",error:new we(be.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`)};return}if(u.structuredContent)try{let h=l(u.structuredContent);if(!h.valid){yield{type:"error",error:new we(be.InvalidParams,`Structured content does not match the tool's output schema: ${h.errorMessage}`)};return}}catch(h){if(h instanceof we){yield{type:"error",error:h};return}yield{type:"error",error:new we(be.InvalidParams,`Failed to validate structured content: ${h instanceof Error?h.message:String(h)}`)};return}}yield c}}async getTask(e,t){return this._client.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._client.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._client.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._client.cancelTask({taskId:e},t)}requestStream(e,t,n){return this._client.requestStream(e,t,n)}};g();function L8(r,e,t){if(!r)throw new Error(`${t} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!r.tools?.call)throw new Error(`${t} does not support task creation for tools/call (required for ${e})`);break;default:break}}function N8(r,e,t){if(!r)throw new Error(`${t} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!r.sampling?.createMessage)throw new Error(`${t} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!r.elicitation?.create)throw new Error(`${t} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}function $C(r,e){if(!(!r||e===null||typeof e!="object")){if(r.type==="object"&&r.properties&&typeof r.properties=="object"){let t=e,n=r.properties;for(let s of Object.keys(n)){let o=n[s];t[s]===void 0&&Object.prototype.hasOwnProperty.call(o,"default")&&(t[s]=o.default),t[s]!==void 0&&$C(o,t[s])}}if(Array.isArray(r.anyOf))for(let t of r.anyOf)typeof t!="boolean"&&$C(t,e);if(Array.isArray(r.oneOf))for(let t of r.oneOf)typeof t!="boolean"&&$C(t,e)}}function ixe(r){if(!r)return{supportsFormMode:!1,supportsUrlMode:!1};let e=r.form!==void 0,t=r.url!==void 0;return{supportsFormMode:e||!e&&!t,supportsUrlMode:t}}var yl=class extends iC{constructor(e,t){super(t),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._cachedKnownTaskTools=new Set,this._cachedRequiredTaskTools=new Set,this._listChangedDebounceTimers=new Map,this._capabilities=t?.capabilities??{},this._jsonSchemaValidator=t?.jsonSchemaValidator??new NC,t?.listChanged&&(this._pendingListChangedConfig=t.listChanged)}_setupListChangedHandlers(e){e.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",CI,e.tools,async()=>(await this.listTools()).tools),e.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",SI,e.prompts,async()=>(await this.listPrompts()).prompts),e.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",yI,e.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new FC(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=w6(this._capabilities,e)}setRequestHandler(e,t){let s=WS(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o;if(Sh(s)){let l=s;o=l._zod?.def?.value??l.value}else{let l=s;o=l._def?.value??l.value}if(typeof o!="string")throw new Error("Schema method literal must be a string");let a=o;if(a==="elicitation/create"){let l=async(c,u)=>{let h=ai(xI,c);if(!h.success){let b=h.error instanceof Error?h.error.message:String(h.error);throw new we(be.InvalidParams,`Invalid elicitation request: ${b}`)}let{params:d}=h.data;d.mode=d.mode??"form";let{supportsFormMode:f,supportsUrlMode:p}=ixe(this._capabilities.elicitation);if(d.mode==="form"&&!f)throw new we(be.InvalidParams,"Client does not support form-mode elicitation requests");if(d.mode==="url"&&!p)throw new we(be.InvalidParams,"Client does not support URL-mode elicitation requests");let y=await Promise.resolve(t(c,u));if(d.task){let b=ai(ou,y);if(!b.success){let v=b.error instanceof Error?b.error.message:String(b.error);throw new we(be.InvalidParams,`Invalid task creation result: ${v}`)}return b.data}let w=ai(AI,y);if(!w.success){let b=w.error instanceof Error?w.error.message:String(w.error);throw new we(be.InvalidParams,`Invalid elicitation result: ${b}`)}let m=w.data,_=d.mode==="form"?d.requestedSchema:void 0;if(d.mode==="form"&&m.action==="accept"&&m.content&&_&&this._capabilities.elicitation?.form?.applyDefaults)try{$C(_,m.content)}catch{}return m};return super.setRequestHandler(e,l)}if(a==="sampling/createMessage"){let l=async(c,u)=>{let h=ai(EI,c);if(!h.success){let m=h.error instanceof Error?h.error.message:String(h.error);throw new we(be.InvalidParams,`Invalid sampling request: ${m}`)}let{params:d}=h.data,f=await Promise.resolve(t(c,u));if(d.task){let m=ai(ou,f);if(!m.success){let _=m.error instanceof Error?m.error.message:String(m.error);throw new we(be.InvalidParams,`Invalid task creation result: ${_}`)}return m.data}let y=d.tools||d.toolChoice?kI:TI,w=ai(y,f);if(!w.success){let m=w.error instanceof Error?w.error.message:String(w.error);throw new we(be.InvalidParams,`Invalid sampling result: ${m}`)}return w.data};return super.setRequestHandler(e,l)}return super.setRequestHandler(e,t)}assertCapability(e,t){if(!this._serverCapabilities?.[e])throw new Error(`Server does not support ${e} (required for ${t})`)}async connect(e,t){if(await super.connect(e),e.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:Eh,capabilities:this._capabilities,clientInfo:this._clientInfo}},hI,t);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!Z4.includes(n.protocolVersion))throw new Error(`Server's protocol version is not supported: ${n.protocolVersion}`);this._serverCapabilities=n.capabilities,this._serverVersion=n.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(n.protocolVersion),this._instructions=n.instructions,await this.notification({method:"notifications/initialized"}),this._pendingListChangedConfig&&(this._setupListChangedHandlers(this._pendingListChangedConfig),this._pendingListChangedConfig=void 0)}catch(n){throw this.close(),n}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){switch(e){case"logging/setLevel":if(!this._serverCapabilities?.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._serverCapabilities?.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!this._serverCapabilities?.resources)throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._serverCapabilities?.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!this._serverCapabilities?.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/roots/list_changed":if(!this._capabilities.roots?.listChanged)throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Client does not support tasks capability (required for ${e})`);break;case"ping":break}}assertTaskCapability(e){L8(this._serverCapabilities?.tasks?.requests,e,"Server")}assertTaskHandlerCapability(e){this._capabilities&&N8(this._capabilities.tasks?.requests,e,"Client")}async ping(e){return this.request({method:"ping"},iu,e)}async complete(e,t){return this.request({method:"completion/complete",params:e},RI,t)}async setLoggingLevel(e,t){return this.request({method:"logging/setLevel",params:{level:e}},iu,t)}async getPrompt(e,t){return this.request({method:"prompts/get",params:e},dg,t)}async listPrompts(e,t){return this.request({method:"prompts/list",params:e},ug,t)}async listResources(e,t){return this.request({method:"resources/list",params:e},pI,t)}async listResourceTemplates(e,t){return this.request({method:"resources/templates/list",params:e},mI,t)}async readResource(e,t){return this.request({method:"resources/read",params:e},cg,t)}async subscribeResource(e,t){return this.request({method:"resources/subscribe",params:e},iu,t)}async unsubscribeResource(e,t){return this.request({method:"resources/unsubscribe",params:e},iu,t)}async callTool(e,t=Go,n){if(this.isToolTaskRequired(e.name))throw new we(be.InvalidRequest,`Tool "${e.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);let s=await this.request({method:"tools/call",params:e},t,n),o=this.getToolOutputValidator(e.name);if(o){if(!s.structuredContent&&!s.isError)throw new we(be.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(s.structuredContent)try{let a=o(s.structuredContent);if(!a.valid)throw new we(be.InvalidParams,`Structured content does not match the tool's output schema: ${a.errorMessage}`)}catch(a){throw a instanceof we?a:new we(be.InvalidParams,`Failed to validate structured content: ${a instanceof Error?a.message:String(a)}`)}}return s}isToolTask(e){return this._serverCapabilities?.tasks?.requests?.tools?.call?this._cachedKnownTaskTools.has(e):!1}isToolTaskRequired(e){return this._cachedRequiredTaskTools.has(e)}cacheToolMetadata(e){this._cachedToolOutputValidators.clear(),this._cachedKnownTaskTools.clear(),this._cachedRequiredTaskTools.clear();for(let t of e){if(t.outputSchema){let s=this._jsonSchemaValidator.getValidator(t.outputSchema);this._cachedToolOutputValidators.set(t.name,s)}let n=t.execution?.taskSupport;(n==="required"||n==="optional")&&this._cachedKnownTaskTools.add(t.name),n==="required"&&this._cachedRequiredTaskTools.add(t.name)}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,t){let n=await this.request({method:"tools/list",params:e},hg,t);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(e,t,n,s){let o=m6.safeParse(n);if(!o.success)throw new Error(`Invalid ${e} listChanged options: ${o.error.message}`);if(typeof n.onChanged!="function")throw new Error(`Invalid ${e} listChanged options: onChanged must be a function`);let{autoRefresh:a,debounceMs:l}=o.data,{onChanged:c}=n,u=async()=>{if(!a){c(null,null);return}try{let d=await s();c(null,d)}catch(d){let f=d instanceof Error?d:new Error(String(d));c(f,null)}},h=()=>{if(l){let d=this._listChangedDebounceTimers.get(e);d&&clearTimeout(d);let f=setTimeout(u,l);this._listChangedDebounceTimers.set(e,f)}else u()};this.setNotificationHandler(t,h)}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};g();g();g();var UC=class extends Error{constructor(e,t){super(e),this.name="ParseError",this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function uD(r){}function HC(r){if(typeof r=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:e=uD,onError:t=uD,onRetry:n=uD,onComment:s}=r,o="",a=!0,l,c="",u="";function h(w){let m=a?w.replace(/^\xEF\xBB\xBF/,""):w,[_,b]=oxe(`${o}${m}`);for(let v of _)d(v);o=b,a=!1}function d(w){if(w===""){p();return}if(w.startsWith(":")){s&&s(w.slice(w.startsWith(": ")?2:1));return}let m=w.indexOf(":");if(m!==-1){let _=w.slice(0,m),b=w[m+1]===" "?2:1,v=w.slice(m+b);f(_,v,w);return}f(w,"",w)}function f(w,m,_){switch(w){case"event":u=m;break;case"data":c=`${c}${m}
1320
1320
  `;break;case"id":l=m.includes("\0")?void 0:m;break;case"retry":/^\d+$/.test(m)?n(parseInt(m,10)):t(new UC(`Invalid \`retry\` value: "${m}"`,{type:"invalid-retry",value:m,line:_}));break;default:t(new UC(`Unknown field "${w.length>20?`${w.slice(0,20)}\u2026`:w}"`,{type:"unknown-field",field:w,value:m,line:_}));break}}function p(){c.length>0&&e({id:l,event:u||void 0,data:c.endsWith(`
1321
1321
  `)?c.slice(0,-1):c}),l=void 0,c="",u=""}function y(w={}){o&&w.consume&&d(o),a=!0,l=void 0,c="",u="",o=""}return{feed:h,reset:y}}function oxe(r){let e=[],t="",n=0;for(;n<r.length;){let s=r.indexOf("\r",n),o=r.indexOf(`
1322
1322
  `,n),a=-1;if(s!==-1&&o!==-1?a=Math.min(s,o):s!==-1?a=s:o!==-1&&(a=o),a===-1){t=r.slice(n);break}else{let l=r.slice(n,a);e.push(l),n=a+1,r[n-1]==="\r"&&r[n]===`
@@ -1981,7 +1981,7 @@ ${u}`);let h=e.model??this.getModel();bs.debug(`Prompt hook using model: ${h}`);
1981
1981
 
1982
1982
  \u26A0\uFE0F RETRY LOOP DETECTED: This tool call has failed validation multiple times with the same error. STOP retrying the same approach. Re-examine the tool schema and parameter requirements, then try a fundamentally different approach. If you cannot resolve the validation error, explain the issue to the user instead of retrying.`,Er=(r,e,t)=>({callId:r.callId,error:e,responseParts:[{functionResponse:{id:r.callId,name:r.name,response:{error:e.message}}}],resultDisplay:e.message,errorType:t,contentLength:e.message.length});function V6e(r){return{response_parts:r.responseParts.map(Lue),result_display:r.resultDisplay,error:r.error?.message,error_type:r.errorType,content_length:r.contentLength}}function Lue(r){let e=r.inlineData?{...r,inlineData:{mimeType:r.inlineData.mimeType,data:"<binary omitted>"}}:r;return e.functionResponse?.parts?{...e,functionResponse:{...e.functionResponse,parts:e.functionResponse.parts.map(Lue)}}:e}function K6e(r){return{tool_name:r.request.name,tool_input:r.request.args,tool_use_id:r.request.callId,status:r.status,tool_response:V6e(r.response)}}function Y6e(r,e){if(!r.functionResponse)return yt.warn("appendContextToResponsePart: no functionResponse on part, additionalContext dropped"),r;let t=r.functionResponse.response??{},n=t.output,s=t.error,o=Object.prototype.hasOwnProperty.call(t,"output"),a=typeof n=="string"||o&&typeof s!="string",l=a?"output":"error",c=a?typeof n=="string"?n:JSON.stringify(n):typeof s=="string"?s:JSON.stringify(t);return{...r,functionResponse:{...r.functionResponse,response:{...t,[l]:`${c}
1983
1983
 
1984
- ${e}`}}}}function J6e(r,e){if(!e||r.responseParts.length===0)return r;let t=[...r.responseParts],n=t.length-1,s=Y6e(t[n],e);return s===t[n]?r:(t[n]=s,{...r,responseParts:t,contentLength:r.contentLength!==void 0?r.contentLength+e.length+2:void 0})}function X6e(r,e){if(!e||r.length===0)return r;let t=[...r],n=t.length-1;return t[n]={...t[n],response:J6e(t[n].response,e)},t}function Z6e(r,e){if(r.length===0)return r;let t=[...r],n=t[t.length-1];return t[t.length-1]={status:"error",request:n.request,tool:n.tool,response:Er(n.request,new Error(e),"execution_denied"),durationMs:n.durationMs,outcome:void 0},t}function Q6e(r){if(vd(r.request.name)===R.AGENT)return!0;if(r.tool.kind==="execute"){let e=r.request.args.command;if(typeof e!="string")return!1;try{return eu(gr(e))}catch{return!1}}return $j.has(r.tool.kind)}function eVe(r){return r.reduce((e,t)=>{let n=Q6e(t),s=e[e.length-1];return n&&s?.concurrent?s.calls.push(t):e.push({concurrent:n,calls:[t]}),e},[])}var vh=class{toolRegistry;toolCalls=[];outputUpdateHandler;onAllToolCallsComplete;onToolCallsUpdate;getPreferredEditor;config;onEditorClose;chatRecordingService;recordedToolResults=new Map;isFinalizingToolCalls=!1;isScheduling=!1;validationRetryCounts=new Map;autoModeFallbackCallIds=new Set;toolSpans=new Map;blockedSpans=new Map;callIdToBatch=new Map;callIdToPostToolBatchSignal=new Map;requestQueue=[];constructor(e){this.config=e.config,this.toolRegistry=e.config.getToolRegistry(),this.outputUpdateHandler=e.outputUpdateHandler,this.onAllToolCallsComplete=e.onAllToolCallsComplete,this.onToolCallsUpdate=e.onToolCallsUpdate,this.getPreferredEditor=e.getPreferredEditor,this.onEditorClose=e.onEditorClose,this.chatRecordingService=e.chatRecordingService}get memoryMonitor(){return this.config.getMemoryPressureMonitor?.()}setStatusInternal(e,t,n){this.toolCalls=this.toolCalls.map(s=>{if(s.request.callId!==e||s.status==="success"||s.status==="error"||s.status==="cancelled")return s;let o=s.startTime,a=s.tool,l=s.invocation,c=s.outcome;switch(t){case"success":{this.clearRetryCountsForTool(s.request.name);let u=o?Date.now()-o:void 0;return{request:s.request,tool:a,invocation:l,status:"success",response:n,durationMs:u,outcome:c}}case"error":{let u=o?Date.now()-o:void 0;return{request:s.request,status:"error",tool:a,response:n,durationMs:u,outcome:c}}case"awaiting_approval":return{request:s.request,tool:a,status:"awaiting_approval",confirmationDetails:n,startTime:o,outcome:c,invocation:l};case"scheduled":return{request:s.request,tool:a,status:"scheduled",startTime:o,outcome:c,invocation:l};case"cancelled":{let u=o?Date.now()-o:void 0,h;if(s.status==="awaiting_approval"){let f=s;f.confirmationDetails.type==="edit"?h={fileDiff:f.confirmationDetails.fileDiff,fileName:f.confirmationDetails.fileName,originalContent:f.confirmationDetails.originalContent,newContent:f.confirmationDetails.newContent}:f.confirmationDetails.type==="plan"&&(h={type:"plan_summary",message:"Plan was rejected. Remaining in plan mode.",plan:f.confirmationDetails.plan,rejected:!0})}else if(s.status==="executing"){let f=s;f.liveOutput!==void 0&&(h=f.liveOutput)}let d=`[Operation Cancelled] Reason: ${n}`;return{request:s.request,tool:a,invocation:l,status:"cancelled",response:{callId:s.request.callId,responseParts:[{functionResponse:{id:s.request.callId,name:s.request.name,response:{error:d}}}],resultDisplay:h,error:void 0,errorType:void 0,contentLength:d.length},durationMs:u,outcome:c}}case"validating":return{request:s.request,tool:a,status:"validating",startTime:o,outcome:c,invocation:l};case"executing":return{request:s.request,tool:a,status:"executing",startTime:o,executionStartTime:Date.now(),outcome:c,invocation:l};default:return t}}),this.notifyToolCallsUpdate(),this.checkAndNotifyCompletion().catch(s=>{yt.warn(`setStatusInternal completion notification failed: ${s instanceof Error?s.message:String(s)}`)})}setArgsInternal(e,t){this.toolCalls=this.toolCalls.map(n=>{if(n.request.callId!==e||n.status==="error")return n;let s=this.buildInvocation(n.tool,t,e,n.request.prompt_id);if(s instanceof Error){let o=Er(n.request,s,"invalid_tool_params");return{request:{...n.request,args:t},status:"error",tool:n.tool,response:o}}return{...n,request:{...n.request,args:t},invocation:s}})}isRunning(){return this.isFinalizingToolCalls||this.toolCalls.some(e=>e.status==="executing"||e.status==="awaiting_approval")}finalizeToolSpan(e){let t=this.toolSpans.get(e);t&&(this.toolSpans.delete(e),n2(t),this.releaseBatchListenerIfDrained(e))}finalizeBlockedSpan(e,t,n){let s=this.blockedSpans.get(e);s&&(this.blockedSpans.delete(e),o2(s,{decision:t,source:n}))}releaseBatchListenerIfDrained(e){let t=this.callIdToBatch.get(e);if(t){this.callIdToBatch.delete(e),t.callIds.delete(e);for(let n of t.callIds)if(this.toolSpans.has(n)||this.blockedSpans.has(n))return;t.signal.removeEventListener("abort",t.onAbort)}}getBlockedSource(){return this.config.getIdeMode?.()?"ide":"cli"}drainSpansForBatch(e){let t=Array.from(e);setTimeout(()=>{for(let n of t)try{this.blockedSpans.has(n)&&this.finalizeBlockedSpan(n,"aborted","system");let s=this.toolSpans.get(n);s&&(bc(s),this.finalizeToolSpan(n)),this.callIdToPostToolBatchSignal.delete(n),this.autoModeFallbackCallIds.delete(n)}catch(s){yt.warn(`drainSpansForBatch: failed to drain ${n}: ${s instanceof Error?s.message:String(s)}`)}},0)}postToolUseFailureEndMeta=e=>e.hookError?{success:!1,error:e.hookError}:{success:!0,hasAdditionalContext:!!e.additionalContext};async withHookSpan(e,t,n){let s=a2(e),o={success:!1};try{let a=await t();return o=n(a),a}catch(a){throw o={success:!1,error:a instanceof Error?a.message:String(a)},a}finally{l2(s,o)}}buildInvocation(e,t,n,s){try{let o=e.build(structuredClone(t));if(n){let a=o;typeof a.setCallId=="function"&&a.setCallId(n)}if(s){let a=o;typeof a.setPromptId=="function"&&a.setPromptId(s)}return o}catch(o){return o instanceof Error?o:new Error(String(o))}}async getToolNotFoundMessage(e,t=3){let n=await this.toolRegistry.ensureTool(R.SKILL);if(n&&"getAvailableSkillNames"in n&&n.getAvailableSkillNames().includes(e))return`"${e}" is a skill name, not a tool name. To use this skill, invoke the "${R.SKILL}" tool with parameter: skill: "${e}"`;let s=this.getToolSuggestion(e,t);return`Tool "${e}" not found in registry. Tools must use the exact names that are registered.${s}`}getToolSuggestion(e,t=3){let s=this.toolRegistry.getAllToolNames().map(l=>({name:l,distance:Mue.default.get(e,l)}));s.sort((l,c)=>l.distance-c.distance);let o=s.slice(0,t);if(o.length===0)return"";let a=o.map(l=>`"${l.name}"`).join(", ");return o.length>1?` Did you mean one of: ${a}?`:` Did you mean ${a}?`}schedule(e,t){return this.isRunning()||this.isScheduling?new Promise((n,s)=>{let o=()=>{let a=this.requestQueue.findIndex(l=>l.request===e);a>-1&&(this.requestQueue.splice(a,1),s(new Error("Tool call cancelled while in queue.")))};t.addEventListener("abort",o,{once:!0}),this.requestQueue.push({request:e,signal:t,resolve:()=>{t.removeEventListener("abort",o),n()},reject:a=>{t.removeEventListener("abort",o),s(a)}})}):this._schedule(e,t)}clearRetryCountsForTool(e){let t=`${e}:`;for(let n of this.validationRetryCounts.keys())n.startsWith(t)&&this.validationRetryCounts.delete(n)}async _schedule(e,t){this.isScheduling=!0;try{if(this.isRunning())throw new Error("Cannot schedule new tool calls while other tool calls are actively running (executing or awaiting approval).");let n=S6e(Array.isArray(e)?e:[e]);if(this.validationRetryCounts.size>0){let a=new Set(n.map(l=>l.name));for(let l of[...this.validationRetryCounts.keys()]){let c=l.indexOf(":"),u=c===-1?l:l.slice(0,c);a.has(u)||this.validationRetryCounts.delete(l)}}let s=[];for(let a of n){let l=vd(a.name),c=this.config.getPermissionManager?.();if(c&&!await c.isToolEnabled(l)){let d=c.findMatchingDenyRule({toolName:l}),f=d?` Matching deny rule: "${d}".`:"",p=`Matilda requires permission to use "${a.name}", but that permission was declined.${f}`;s.push({status:"error",request:a,response:Er(a,new Error(p),"execution_denied"),durationMs:0});continue}if(!c){let d=this.config.getPermissionsDeny?.()??void 0;if(d&&d.length>0){let f=l.toLowerCase().trim(),p=d.find(y=>y.toLowerCase().trim()===f);if(p){let y=`Matilda requires permission to use ${p}, but that permission was declined.`;s.push({status:"error",request:a,response:Er(a,new Error(y),"execution_denied"),durationMs:0});continue}}}let u=await this.toolRegistry.ensureTool(l);if(!u){let d=await this.getToolNotFoundMessage(a.name);s.push({status:"error",request:a,response:Er(a,new Error(d),"tool_not_registered"),durationMs:0});continue}if(a.wasOutputTruncated&&u.kind==="edit"){let d=new Error(H6e);s.push({status:"error",request:a,tool:u,response:Er(a,d,"output_truncated"),durationMs:0});continue}let h=this.buildInvocation(u,a.args,a.callId,a.prompt_id);if(h instanceof Error){let d=a.wasOutputTruncated?new Error(`${h.message} ${U6e}`):h,f=`${a.name}:${h.message}`,p=(this.validationRetryCounts.get(f)??0)+1;for(let w of this.validationRetryCounts.keys())w.startsWith(`${a.name}:`)&&w!==f&&this.validationRetryCounts.delete(w);this.validationRetryCounts.set(f,p);let y=p>=W6e?new Error(`${h.message}${G6e}`):d;s.push({status:"error",request:a,tool:u,response:Er(a,y,"invalid_tool_params"),durationMs:0});continue}this.clearRetryCountsForTool(a.name),s.push({status:"validating",request:a,tool:u,invocation:h,startTime:Date.now()})}this.toolCalls=this.toolCalls.concat(s),this.notifyToolCallsUpdate();let o={signal:t,onAbort:()=>this.drainSpansForBatch(o.callIds),callIds:new Set};t.addEventListener("abort",o.onAbort,{once:!0});for(let a of s){if(a.status!=="validating")continue;let{request:l,invocation:c}=a,u=vd(l.name),h=VR(u,{"tool.call_id":l.callId,call_id:l.callId,tool_name:u});this.toolSpans.set(l.callId,h),o.callIds.add(l.callId),this.callIdToBatch.set(l.callId,o),this.callIdToPostToolBatchSignal.set(l.callId,t);try{if(t.aborted){this.setStatusInternal(l.callId,"cancelled","Tool call cancelled by user."),bc(h),this.finalizeToolSpan(l.callId);continue}let d=c.params,f=await aI(this.config,c,u,d),{finalPermission:p,pmForcedAsk:y,pmCtx:w,denyMessage:m}=f,_=this.config.getApprovalMode(),b=_==="plan",v=u===R.EXIT_PLAN_MODE,S=u===R.ENTER_PLAN_MODE,E=_==="auto"&&FS(w,this.config.getCwd()),T=W4(p,E);if(p==="allow"&&E&&yt.info(`Auto mode: L4 allow overridden by protected-write guard for ${u}`),p==="allow"&&!E){_==="auto"&&this.config.setAutoModeDenialState(gh(this.config.getAutoModeDenialState())),this.setToolCallOutcome(l.callId,"proceed_always"),this.setStatusInternal(l.callId,"scheduled");continue}if(p==="deny"){this.setStatusInternal(l.callId,"error",Er(l,new Error(m??`Tool "${l.name}" is denied.`),"execution_denied")),vs(h,Sue,Cue),this.finalizeToolSpan(l.callId);continue}if(nI(_,u)){let P=this.config.getAutoModeDenialState(),U=NS(P),F=this.config.getGeminiClient?.()?.getHistoryTail(40,!1)??[],D=await BS({ctx:w,pmForcedAsk:y,toolParams:d,messages:F,config:this.config,signal:t,skipClassifierReason:U.fallback?U.reason:void 0}),H=$S(D,this.config,P);if(!this.config.getDisableAllHooks()&&US(D,H))try{await this.config.getHookSystem?.()?.firePermissionDeniedEvent(u,d,l.callId,HS(D),t)}catch(G){yt.warn(`PermissionDenied hook failed for tool ${l.callId}: ${G instanceof Error?G.message:String(G)}`)}switch(H.kind){case"approved":this.setToolCallOutcome(l.callId,"proceed_always"),this.setStatusInternal(l.callId,"scheduled");continue;case"blocked":yt.warn(`Auto mode blocked (${H.reason}): tool=${u}, `+ru(P)),this.setStatusInternal(l.callId,"error",Er(l,new Error(H.errorMessage),"execution_denied"));continue;case"fallback":YM(H.reason)&&(this.autoModeFallbackCallIds.add(l.callId),yt.warn(`Auto mode fallback to manual approval (${H.reason}): `+ru(P)));break;default:{let G=H}}}let A=u===R.ASK_USER_QUESTION,k;if(!q4(T,_,u))this.setToolCallOutcome(l.callId,"proceed_always"),this.setStatusInternal(l.callId,"scheduled");else{if(k=await c.getConfirmationDetails(t),j4(k,w),G4(b,v,A,k,S)){this.setStatusInternal(l.callId,"error",{callId:l.callId,responseParts:Rue(l.name,l.callId,Vv()),resultDisplay:"Plan mode blocked a non-read-only tool call.",error:void 0,errorType:void 0}),vs(h,P6e,N6e),this.finalizeToolSpan(l.callId);continue}if(V4(_,k)){this.setToolCallOutcome(l.callId,"proceed_always"),this.setStatusInternal(l.callId,"scheduled");continue}if(!this.config.isInteractive()&&!this.config.getExperimentalZedIntegration()&&this.config.getInputFormat()!=="stream-json"){let j=`Matilda requires permission to use "${l.name}", but that permission was declined (non-interactive mode cannot prompt for confirmation).`;this.setStatusInternal(l.callId,"error",Er(l,new Error(j),"execution_denied")),vs(h,M6e,F6e),this.finalizeToolSpan(l.callId);continue}let U=this.config.getMessageBus(),F=!this.config.getDisableAllHooks();if(F&&U){let j=String(this.config.getApprovalMode()),q=await xM(U,u,l.args||{},j);if(q.hasDecision){if(q.shouldAllow)q.updatedInput&&typeof l.args=="object"&&this.setArgsInternal(l.callId,q.updatedInput),await k.onConfirm("proceed_once"),this.recordAutoModeFallbackResolution(l.callId,"proceed_once"),this.setToolCallOutcome(l.callId,"proceed_once"),this.setStatusInternal(l.callId,"scheduled");else{let W=q.denyMessage?{cancelMessage:q.denyMessage}:void 0;await k.onConfirm("cancel",W),this.recordAutoModeFallbackResolution(l.callId,"cancel"),this.setToolCallOutcome(l.callId,"cancel"),this.setStatusInternal(l.callId,"error",Er(l,new Error(q.denyMessage||`Permission denied by hook for "${l.name}"`),"execution_denied")),vs(h,R6e,L6e),this.finalizeToolSpan(l.callId)}continue}}if(this.config.getShouldAvoidPermissionPrompts?.()){let j=`Tool "${l.name}" requires permission, but background agents cannot prompt for confirmation. The tool call was denied.`;this.setStatusInternal(l.callId,"error",Er(l,new Error(j),"execution_denied")),vs(h,I6e,$6e),this.finalizeToolSpan(l.callId);continue}if(t.aborted){this.setStatusInternal(l.callId,"cancelled","Tool call cancelled by user."),bc(h),this.finalizeToolSpan(l.callId);continue}this.openIdeDiffIfEnabled(k,l.callId,t);let D=k.onConfirm,H={...k,...y?{hideAlwaysAllow:!0}:{},onConfirm:(j,q)=>this.handleConfirmationResponse(l.callId,D,j,t,q)};this.setStatusInternal(l.callId,"awaiting_approval",H);let G=i2(h,{tool_name:u,call_id:l.callId});this.blockedSpans.set(l.callId,G),F&&U&&Um(U,`Matilda needs your permission to use ${l.name}`,"permission_prompt","Permission needed").catch(j=>{yt.warn(`Permission prompt notification hook failed: ${j instanceof Error?j.message:String(j)}`)})}}catch(d){if(t.aborted){this.setStatusInternal(l.callId,"cancelled","Tool call cancelled by user."),this.finalizeBlockedSpan(l.callId,"aborted","system"),bc(h),this.finalizeToolSpan(l.callId);continue}let f=d?.errorType;this.setStatusInternal(l.callId,"error",Er(l,d instanceof Error?d:new Error(String(d)),f??"unhandled_exception")),this.finalizeBlockedSpan(l.callId,"error","system"),vs(h,yR,d instanceof Error?d.message:String(d)),this.finalizeToolSpan(l.callId)}}await this.attemptExecutionOfScheduledCalls(t),this.checkAndNotifyCompletion().catch(a=>{yt.warn(`_schedule completion notification failed: ${a instanceof Error?a.message:String(a)}`)}),o.callIds.size===0&&t.removeEventListener("abort",o.onAbort)}finally{this.isScheduling=!1}}async handleConfirmationResponse(e,t,n,s,o){let a=this.toolCalls.find(l=>l.request.callId===e&&l.status==="awaiting_approval");if(a){try{await this._handleConfirmationResponseInner(e,a,t,n,s,o)}catch(l){let c=s.aborted;this.finalizeBlockedSpan(e,c?"aborted":"error","system");let u=this.toolSpans.get(e);throw u&&(c?bc(u):vs(u,yR,l instanceof Error?l.message:String(l))),this.finalizeToolSpan(e),yt.warn(`handleConfirmationResponse failed for ${e}: ${l instanceof Error?l.message:String(l)}`),l}await this.attemptExecutionOfScheduledCalls(s)}}async _handleConfirmationResponseInner(e,t,n,s,o,a){if(await n(s,a),(s==="proceed_always"||s==="proceed_always_project"||s==="proceed_always_user")&&(await z4(s,t.confirmationDetails,this.config.getOnPersistPermissionRule?.(),this.config.getPermissionManager?.(),a),await this.autoApproveCompatiblePendingTools(o,e)),this.setToolCallOutcome(e,s),this.recordAutoModeFallbackResolution(e,s),s==="cancel"||o.aborted){let l=a?.cancelMessage||"User did not allow tool call";this.setStatusInternal(e,"cancelled",l);let c=this.toolSpans.get(e);c&&bc(c);let u=s==="cancel";this.finalizeBlockedSpan(e,u?"cancel":"aborted",u?this.getBlockedSource():"system"),this.finalizeToolSpan(e)}else if(s==="modify_with_editor"){let l=t;if(nL(l.tool)){let c=l.tool.getModifyContext(o),u=this.getPreferredEditor();if(!u){yt.warn(`ModifyWithEditor requested for ${e} but no editor available \u2014 tool stays in awaiting_approval; user can recover via Cancel/Proceed`);let p=this.toolSpans.get(e);if(p)try{p.setAttributes({"matilda-code.tool.modify_with_editor_unavailable":!0})}catch{}return}this.setStatusInternal(e,"awaiting_approval",{...l.confirmationDetails,isModifying:!0});let h={...l.request.args};for(let p of Rd)typeof h[p]=="string"&&(h[p]=Xs(String(h[p]).trim()));let{updatedParams:d,updatedDiff:f}=await VK(h,c,u,o,this.onEditorClose);this.setArgsInternal(e,d),this.setStatusInternal(e,"awaiting_approval",{...l.confirmationDetails,fileDiff:f,isModifying:!1})}}else{a?.newContent&&t&&await this._applyInlineModify(t,a,o),this.setStatusInternal(e,"scheduled");let l=s==="proceed_once"?"proceed_once":"proceed_always";this.finalizeBlockedSpan(e,l,this.getBlockedSource())}}recordAutoModeFallbackResolution(e,t){let n=this.autoModeFallbackCallIds.delete(e);if(this.config.getApprovalMode()==="auto"&&n&&QM(t)){let s=this.config.getAutoModeDenialState(),o=ZM(s);if(o===s){yt.warn("Auto mode denial counters already clear after fallback approval: "+ru(s));return}yt.warn(`Auto mode denial counters reset after fallback approval: ${ru(s)} -> ${ru(o)}`),this.config.setAutoModeDenialState(o)}}async openIdeDiffIfEnabled(e,t,n){if(e.type!=="edit"||!this.config.getIdeMode())return;let s;try{let a=await AT.getInstance();if(!a.isDiffingEnabled())return;s=await a.openDiff(e.filePath,e.newContent)}catch(a){n.aborted||yt.warn(`IDE diff open failed for ${t}: ${a instanceof Error?a.message:String(a)}`);return}if(this.toolCalls.find(a=>a.request.callId===t&&a.status==="awaiting_approval"))if(s.status==="accepted"){let a=s.content!=null&&s.content!==e.newContent;await this.handleConfirmationResponse(t,e.onConfirm,"proceed_once",n,a?{newContent:s.content}:void 0)}else await this.handleConfirmationResponse(t,e.onConfirm,"cancel",n)}async _applyInlineModify(e,t,n){let s=e.confirmationDetails;if(s.type!=="edit"||!nL(e.tool)||!t.newContent)return;let o=s.originalContent??"",l=e.tool.getModifyContext(n).createUpdatedParams(o,t.newContent,e.request.args),c=zd(s.filePath,o,t.newContent,"Current","Proposed");this.setArgsInternal(e.request.callId,l),this.setStatusInternal(e.request.callId,"awaiting_approval",{...s,fileDiff:c})}async attemptExecutionOfScheduledCalls(e){if(this.toolCalls.every(n=>n.status==="scheduled"||n.status==="cancelled"||n.status==="success"||n.status==="error")){let n=this.toolCalls.filter(o=>o.status==="scheduled"),s=eVe(n);for(let o of s)if(o.concurrent&&o.calls.length>1)await this.runConcurrently(o.calls,e);else for(let a of o.calls)await this.executeSingleToolCall(a,e)}}async runConcurrently(e,t){let n=parseInt(process.env.MATILDA_CODE_MAX_TOOL_CONCURRENCY||"",10),s=Number.isFinite(n)&&n>=1?n:10,o=new Set;for(let a of e){let l=this.executeSingleToolCall(a,t).finally(()=>{o.delete(l)});o.add(l),o.size>=s&&await Promise.race(o)}await Promise.all(o)}async executeSingleToolCall(e,t){if(e.status!=="scheduled")return;let n=e,{callId:s,name:o}=n.request,a=this.toolSpans.get(s);if(!a){let l=vd(o);a=VR(l,{"tool.call_id":s,call_id:s,tool_name:l}),this.toolSpans.set(s,a)}try{await r2(a,()=>this._executeToolCallBody(n,t,a))}catch(l){let c=l instanceof Error?l.message:String(l);throw vs(a,yR,c),this.setStatusInternal(s,"error",Er(n.request,l instanceof Error?l:new Error(c),"unhandled_exception")),l}finally{this.finalizeToolSpan(s),this.memoryMonitor?.scheduleCheck()}}async _executeToolCallBody(e,t,n){let{callId:s,name:o}=e.request,a=vd(o),l=e.invocation,c=e.request.args;for(let m of Rd)typeof c[m]=="string"&&(c[m]=Xs(String(c[m]).trim()));this.config.getTelemetryIncludeSensitiveSpanAttributes?.()&&Qj(this.config,n,o,Ba(c)??"{}");let u=CM(),h=this.config.getMessageBus(),d=!this.config.getDisableAllHooks();if(d&&h){let m=this.config.getApprovalMode(),_=await this.withHookSpan({hookEvent:"PreToolUse",toolName:a,toolUseId:u},()=>EM(h,a,c,u,m),b=>b.hookError?{success:!1,error:b.hookError,shouldProceed:!0}:{success:!0,shouldProceed:b.shouldProceed,blockType:b.shouldProceed?void 0:b.blockType,hasAdditionalContext:!!b.additionalContext});if(!_.shouldProceed){let b=_.blockReason||"Tool execution blocked by hook",v=Er(e.request,new Error(b),"execution_denied");za(this.config,n,o,`BLOCKED: ${b}`),this.setStatusInternal(s,"error",v),vs(n,T6e,O6e);return}}this.setStatusInternal(s,"executing");let f=e.tool.canUpdateOutput?m=>{this.outputUpdateHandler&&this.outputUpdateHandler(s,m),this.toolCalls=this.toolCalls.map(_=>_.request.callId===s&&_.status==="executing"?{..._,liveOutput:m}:_),this.notifyToolCallsUpdate()}:void 0,p=this.config.getShellExecutionConfig(),y=s2(),w=Jv(this.config,`Matilda is executing tool ${a}`);try{let m;if(l instanceof Pb){let v=E=>{this.toolCalls=this.toolCalls.map(T=>T.request.callId===s&&T.status==="executing"?{...T,pid:E}:T),this.notifyToolCallsUpdate()},S=E=>{this.toolCalls=this.toolCalls.map(T=>T.request.callId===s&&T.status==="executing"?{...T,promoteAbortController:E}:T),this.notifyToolCallsUpdate()};m=l.execute(t,f,p,v,S)}else m=l.execute(t,f,p);let _=await m,b=t.aborted;if(KR(y,{success:_.error===void 0&&!b,error:b?kue:_.error?Eue:void 0,cancelled:b}),b){let v="User cancelled tool execution.";if(d&&h){let S=await this.withHookSpan({hookEvent:"PostToolUseFailure",toolName:a,toolUseId:u,isInterrupt:!0},()=>wR(h,u,a,c,v,!0,this.config.getApprovalMode()),this.postToolUseFailureEndMeta);S.additionalContext&&(v+=`
1984
+ ${e}`}}}}function J6e(r,e){if(!e||r.responseParts.length===0)return r;let t=[...r.responseParts],n=t.length-1,s=Y6e(t[n],e);return s===t[n]?r:(t[n]=s,{...r,responseParts:t,contentLength:r.contentLength!==void 0?r.contentLength+e.length+2:void 0})}function X6e(r,e){if(!e||r.length===0)return r;let t=[...r],n=t.length-1;return t[n]={...t[n],response:J6e(t[n].response,e)},t}function Z6e(r,e){if(r.length===0)return r;let t=[...r],n=t[t.length-1];return t[t.length-1]={status:"error",request:n.request,tool:n.tool,response:Er(n.request,new Error(e),"execution_denied"),durationMs:n.durationMs,outcome:void 0},t}function Q6e(r){if(vd(r.request.name)===R.AGENT)return!0;if(r.tool.kind==="execute"){let e=r.request.args.command;if(typeof e!="string")return!1;try{return eu(gr(e))}catch{return!1}}return $j.has(r.tool.kind)}function eVe(r){return r.reduce((e,t)=>{let n=Q6e(t),s=e[e.length-1];return n&&s?.concurrent?s.calls.push(t):e.push({concurrent:n,calls:[t]}),e},[])}var vh=class{toolRegistry;toolCalls=[];outputUpdateHandler;onAllToolCallsComplete;onToolCallsCompleteError;onToolCallsUpdate;getPreferredEditor;config;onEditorClose;chatRecordingService;recordedToolResults=new Map;toolResultWriteChain=Promise.resolve();isFinalizingToolCalls=!1;isScheduling=!1;validationRetryCounts=new Map;autoModeFallbackCallIds=new Set;toolSpans=new Map;blockedSpans=new Map;callIdToBatch=new Map;callIdToPostToolBatchSignal=new Map;requestQueue=[];constructor(e){this.config=e.config,this.toolRegistry=e.config.getToolRegistry(),this.outputUpdateHandler=e.outputUpdateHandler,this.onAllToolCallsComplete=e.onAllToolCallsComplete,this.onToolCallsCompleteError=e.onToolCallsCompleteError,this.onToolCallsUpdate=e.onToolCallsUpdate,this.getPreferredEditor=e.getPreferredEditor,this.onEditorClose=e.onEditorClose,this.chatRecordingService=e.chatRecordingService}get memoryMonitor(){return this.config.getMemoryPressureMonitor?.()}setStatusInternal(e,t,n){this.toolCalls=this.toolCalls.map(s=>{if(s.request.callId!==e||s.status==="success"||s.status==="error"||s.status==="cancelled")return s;let o=s.startTime,a=s.tool,l=s.invocation,c=s.outcome;switch(t){case"success":{this.clearRetryCountsForTool(s.request.name);let u=o?Date.now()-o:void 0;return{request:s.request,tool:a,invocation:l,status:"success",response:n,durationMs:u,outcome:c}}case"error":{let u=o?Date.now()-o:void 0;return{request:s.request,status:"error",tool:a,response:n,durationMs:u,outcome:c}}case"awaiting_approval":return{request:s.request,tool:a,status:"awaiting_approval",confirmationDetails:n,startTime:o,outcome:c,invocation:l};case"scheduled":return{request:s.request,tool:a,status:"scheduled",startTime:o,outcome:c,invocation:l};case"cancelled":{let u=o?Date.now()-o:void 0,h;if(s.status==="awaiting_approval"){let f=s;f.confirmationDetails.type==="edit"?h={fileDiff:f.confirmationDetails.fileDiff,fileName:f.confirmationDetails.fileName,originalContent:f.confirmationDetails.originalContent,newContent:f.confirmationDetails.newContent}:f.confirmationDetails.type==="plan"&&(h={type:"plan_summary",message:"Plan was rejected. Remaining in plan mode.",plan:f.confirmationDetails.plan,rejected:!0})}else if(s.status==="executing"){let f=s;f.liveOutput!==void 0&&(h=f.liveOutput)}let d=`[Operation Cancelled] Reason: ${n}`;return{request:s.request,tool:a,invocation:l,status:"cancelled",response:{callId:s.request.callId,responseParts:[{functionResponse:{id:s.request.callId,name:s.request.name,response:{error:d}}}],resultDisplay:h,error:void 0,errorType:void 0,contentLength:d.length},durationMs:u,outcome:c}}case"validating":return{request:s.request,tool:a,status:"validating",startTime:o,outcome:c,invocation:l};case"executing":return{request:s.request,tool:a,status:"executing",startTime:o,executionStartTime:Date.now(),outcome:c,invocation:l};default:return t}}),this.notifyToolCallsUpdate(),this.checkAndNotifyCompletion().catch(s=>{yt.warn(`setStatusInternal completion notification failed: ${s instanceof Error?s.message:String(s)}`)})}setArgsInternal(e,t){this.toolCalls=this.toolCalls.map(n=>{if(n.request.callId!==e||n.status==="error")return n;let s=this.buildInvocation(n.tool,t,e,n.request.prompt_id);if(s instanceof Error){let o=Er(n.request,s,"invalid_tool_params");return{request:{...n.request,args:t},status:"error",tool:n.tool,response:o}}return{...n,request:{...n.request,args:t},invocation:s}})}isRunning(){return this.isFinalizingToolCalls||this.toolCalls.some(e=>e.status==="executing"||e.status==="awaiting_approval")}finalizeToolSpan(e){let t=this.toolSpans.get(e);t&&(this.toolSpans.delete(e),n2(t),this.releaseBatchListenerIfDrained(e))}finalizeBlockedSpan(e,t,n){let s=this.blockedSpans.get(e);s&&(this.blockedSpans.delete(e),o2(s,{decision:t,source:n}))}releaseBatchListenerIfDrained(e){let t=this.callIdToBatch.get(e);if(t){this.callIdToBatch.delete(e),t.callIds.delete(e);for(let n of t.callIds)if(this.toolSpans.has(n)||this.blockedSpans.has(n))return;t.signal.removeEventListener("abort",t.onAbort)}}getBlockedSource(){return this.config.getIdeMode?.()?"ide":"cli"}drainSpansForBatch(e){let t=Array.from(e);setTimeout(()=>{for(let n of t)try{this.blockedSpans.has(n)&&this.finalizeBlockedSpan(n,"aborted","system");let s=this.toolSpans.get(n);s&&(bc(s),this.finalizeToolSpan(n)),this.callIdToPostToolBatchSignal.delete(n),this.autoModeFallbackCallIds.delete(n)}catch(s){yt.warn(`drainSpansForBatch: failed to drain ${n}: ${s instanceof Error?s.message:String(s)}`)}},0)}postToolUseFailureEndMeta=e=>e.hookError?{success:!1,error:e.hookError}:{success:!0,hasAdditionalContext:!!e.additionalContext};async withHookSpan(e,t,n){let s=a2(e),o={success:!1};try{let a=await t();return o=n(a),a}catch(a){throw o={success:!1,error:a instanceof Error?a.message:String(a)},a}finally{l2(s,o)}}buildInvocation(e,t,n,s){try{let o=e.build(structuredClone(t));if(n){let a=o;typeof a.setCallId=="function"&&a.setCallId(n)}if(s){let a=o;typeof a.setPromptId=="function"&&a.setPromptId(s)}return o}catch(o){return o instanceof Error?o:new Error(String(o))}}async getToolNotFoundMessage(e,t=3){let n=await this.toolRegistry.ensureTool(R.SKILL);if(n&&"getAvailableSkillNames"in n&&n.getAvailableSkillNames().includes(e))return`"${e}" is a skill name, not a tool name. To use this skill, invoke the "${R.SKILL}" tool with parameter: skill: "${e}"`;let s=this.getToolSuggestion(e,t);return`Tool "${e}" not found in registry. Tools must use the exact names that are registered.${s}`}getToolSuggestion(e,t=3){let s=this.toolRegistry.getAllToolNames().map(l=>({name:l,distance:Mue.default.get(e,l)}));s.sort((l,c)=>l.distance-c.distance);let o=s.slice(0,t);if(o.length===0)return"";let a=o.map(l=>`"${l.name}"`).join(", ");return o.length>1?` Did you mean one of: ${a}?`:` Did you mean ${a}?`}schedule(e,t){return this.isRunning()||this.isScheduling?new Promise((n,s)=>{let o=()=>{let a=this.requestQueue.findIndex(l=>l.request===e);a>-1&&(this.requestQueue.splice(a,1),s(new Error("Tool call cancelled while in queue.")))};t.addEventListener("abort",o,{once:!0}),this.requestQueue.push({request:e,signal:t,resolve:()=>{t.removeEventListener("abort",o),n()},reject:a=>{t.removeEventListener("abort",o),s(a)}})}):this._schedule(e,t)}clearRetryCountsForTool(e){let t=`${e}:`;for(let n of this.validationRetryCounts.keys())n.startsWith(t)&&this.validationRetryCounts.delete(n)}async _schedule(e,t){this.isScheduling=!0;try{if(this.isRunning())throw new Error("Cannot schedule new tool calls while other tool calls are actively running (executing or awaiting approval).");let n=S6e(Array.isArray(e)?e:[e]);if(this.validationRetryCounts.size>0){let a=new Set(n.map(l=>l.name));for(let l of[...this.validationRetryCounts.keys()]){let c=l.indexOf(":"),u=c===-1?l:l.slice(0,c);a.has(u)||this.validationRetryCounts.delete(l)}}let s=[];for(let a of n){let l=vd(a.name),c=this.config.getPermissionManager?.();if(c&&!await c.isToolEnabled(l)){let d=c.findMatchingDenyRule({toolName:l}),f=d?` Matching deny rule: "${d}".`:"",p=`Matilda requires permission to use "${a.name}", but that permission was declined.${f}`;s.push({status:"error",request:a,response:Er(a,new Error(p),"execution_denied"),durationMs:0});continue}if(!c){let d=this.config.getPermissionsDeny?.()??void 0;if(d&&d.length>0){let f=l.toLowerCase().trim(),p=d.find(y=>y.toLowerCase().trim()===f);if(p){let y=`Matilda requires permission to use ${p}, but that permission was declined.`;s.push({status:"error",request:a,response:Er(a,new Error(y),"execution_denied"),durationMs:0});continue}}}let u=await this.toolRegistry.ensureTool(l);if(!u){let d=await this.getToolNotFoundMessage(a.name);s.push({status:"error",request:a,response:Er(a,new Error(d),"tool_not_registered"),durationMs:0});continue}if(a.wasOutputTruncated&&u.kind==="edit"){let d=new Error(H6e);s.push({status:"error",request:a,tool:u,response:Er(a,d,"output_truncated"),durationMs:0});continue}let h=this.buildInvocation(u,a.args,a.callId,a.prompt_id);if(h instanceof Error){let d=a.wasOutputTruncated?new Error(`${h.message} ${U6e}`):h,f=`${a.name}:${h.message}`,p=(this.validationRetryCounts.get(f)??0)+1;for(let w of this.validationRetryCounts.keys())w.startsWith(`${a.name}:`)&&w!==f&&this.validationRetryCounts.delete(w);this.validationRetryCounts.set(f,p);let y=p>=W6e?new Error(`${h.message}${G6e}`):d;s.push({status:"error",request:a,tool:u,response:Er(a,y,"invalid_tool_params"),durationMs:0});continue}this.clearRetryCountsForTool(a.name),s.push({status:"validating",request:a,tool:u,invocation:h,startTime:Date.now()})}for(let a of s)this.callIdToPostToolBatchSignal.set(a.request.callId,t);this.toolCalls=this.toolCalls.concat(s),this.notifyToolCallsUpdate();let o={signal:t,onAbort:()=>this.drainSpansForBatch(o.callIds),callIds:new Set};t.addEventListener("abort",o.onAbort,{once:!0});for(let a of s){if(a.status!=="validating")continue;let{request:l,invocation:c}=a,u=vd(l.name),h=VR(u,{"tool.call_id":l.callId,call_id:l.callId,tool_name:u});this.toolSpans.set(l.callId,h),o.callIds.add(l.callId),this.callIdToBatch.set(l.callId,o);try{if(t.aborted){this.setStatusInternal(l.callId,"cancelled","Tool call cancelled by user."),bc(h),this.finalizeToolSpan(l.callId);continue}let d=c.params,f=await aI(this.config,c,u,d),{finalPermission:p,pmForcedAsk:y,pmCtx:w,denyMessage:m}=f,_=this.config.getApprovalMode(),b=_==="plan",v=u===R.EXIT_PLAN_MODE,S=u===R.ENTER_PLAN_MODE,E=_==="auto"&&FS(w,this.config.getCwd()),T=W4(p,E);if(p==="allow"&&E&&yt.info(`Auto mode: L4 allow overridden by protected-write guard for ${u}`),p==="allow"&&!E){_==="auto"&&this.config.setAutoModeDenialState(gh(this.config.getAutoModeDenialState())),this.setToolCallOutcome(l.callId,"proceed_always"),this.setStatusInternal(l.callId,"scheduled");continue}if(p==="deny"){this.setStatusInternal(l.callId,"error",Er(l,new Error(m??`Tool "${l.name}" is denied.`),"execution_denied")),vs(h,Sue,Cue),this.finalizeToolSpan(l.callId);continue}if(nI(_,u)){let P=this.config.getAutoModeDenialState(),U=NS(P),F=this.config.getGeminiClient?.()?.getHistoryTail(40,!1)??[],D=await BS({ctx:w,pmForcedAsk:y,toolParams:d,messages:F,config:this.config,signal:t,skipClassifierReason:U.fallback?U.reason:void 0}),H=$S(D,this.config,P);if(!this.config.getDisableAllHooks()&&US(D,H))try{await this.config.getHookSystem?.()?.firePermissionDeniedEvent(u,d,l.callId,HS(D),t)}catch(G){yt.warn(`PermissionDenied hook failed for tool ${l.callId}: ${G instanceof Error?G.message:String(G)}`)}switch(H.kind){case"approved":this.setToolCallOutcome(l.callId,"proceed_always"),this.setStatusInternal(l.callId,"scheduled");continue;case"blocked":yt.warn(`Auto mode blocked (${H.reason}): tool=${u}, `+ru(P)),this.setStatusInternal(l.callId,"error",Er(l,new Error(H.errorMessage),"execution_denied"));continue;case"fallback":YM(H.reason)&&(this.autoModeFallbackCallIds.add(l.callId),yt.warn(`Auto mode fallback to manual approval (${H.reason}): `+ru(P)));break;default:{let G=H}}}let A=u===R.ASK_USER_QUESTION,k;if(!q4(T,_,u))this.setToolCallOutcome(l.callId,"proceed_always"),this.setStatusInternal(l.callId,"scheduled");else{if(k=await c.getConfirmationDetails(t),j4(k,w),G4(b,v,A,k,S)){this.setStatusInternal(l.callId,"error",{callId:l.callId,responseParts:Rue(l.name,l.callId,Vv()),resultDisplay:"Plan mode blocked a non-read-only tool call.",error:void 0,errorType:void 0}),vs(h,P6e,N6e),this.finalizeToolSpan(l.callId);continue}if(V4(_,k)){this.setToolCallOutcome(l.callId,"proceed_always"),this.setStatusInternal(l.callId,"scheduled");continue}if(!this.config.isInteractive()&&!this.config.getExperimentalZedIntegration()&&this.config.getInputFormat()!=="stream-json"){let j=`Matilda requires permission to use "${l.name}", but that permission was declined (non-interactive mode cannot prompt for confirmation).`;this.setStatusInternal(l.callId,"error",Er(l,new Error(j),"execution_denied")),vs(h,M6e,F6e),this.finalizeToolSpan(l.callId);continue}let U=this.config.getMessageBus(),F=!this.config.getDisableAllHooks();if(F&&U){let j=String(this.config.getApprovalMode()),q=await xM(U,u,l.args||{},j);if(q.hasDecision){if(q.shouldAllow)q.updatedInput&&typeof l.args=="object"&&this.setArgsInternal(l.callId,q.updatedInput),await k.onConfirm("proceed_once"),this.recordAutoModeFallbackResolution(l.callId,"proceed_once"),this.setToolCallOutcome(l.callId,"proceed_once"),this.setStatusInternal(l.callId,"scheduled");else{let W=q.denyMessage?{cancelMessage:q.denyMessage}:void 0;await k.onConfirm("cancel",W),this.recordAutoModeFallbackResolution(l.callId,"cancel"),this.setToolCallOutcome(l.callId,"cancel"),this.setStatusInternal(l.callId,"error",Er(l,new Error(q.denyMessage||`Permission denied by hook for "${l.name}"`),"execution_denied")),vs(h,R6e,L6e),this.finalizeToolSpan(l.callId)}continue}}if(this.config.getShouldAvoidPermissionPrompts?.()){let j=`Tool "${l.name}" requires permission, but background agents cannot prompt for confirmation. The tool call was denied.`;this.setStatusInternal(l.callId,"error",Er(l,new Error(j),"execution_denied")),vs(h,I6e,$6e),this.finalizeToolSpan(l.callId);continue}if(t.aborted){this.setStatusInternal(l.callId,"cancelled","Tool call cancelled by user."),bc(h),this.finalizeToolSpan(l.callId);continue}this.openIdeDiffIfEnabled(k,l.callId,t);let D=k.onConfirm,H={...k,...y?{hideAlwaysAllow:!0}:{},onConfirm:(j,q)=>this.handleConfirmationResponse(l.callId,D,j,t,q)};this.setStatusInternal(l.callId,"awaiting_approval",H);let G=i2(h,{tool_name:u,call_id:l.callId});this.blockedSpans.set(l.callId,G),F&&U&&Um(U,`Matilda needs your permission to use ${l.name}`,"permission_prompt","Permission needed").catch(j=>{yt.warn(`Permission prompt notification hook failed: ${j instanceof Error?j.message:String(j)}`)})}}catch(d){if(t.aborted){this.setStatusInternal(l.callId,"cancelled","Tool call cancelled by user."),this.finalizeBlockedSpan(l.callId,"aborted","system"),bc(h),this.finalizeToolSpan(l.callId);continue}let f=d?.errorType;this.setStatusInternal(l.callId,"error",Er(l,d instanceof Error?d:new Error(String(d)),f??"unhandled_exception")),this.finalizeBlockedSpan(l.callId,"error","system"),vs(h,yR,d instanceof Error?d.message:String(d)),this.finalizeToolSpan(l.callId)}}await this.attemptExecutionOfScheduledCalls(t),this.checkAndNotifyCompletion().catch(a=>{yt.warn(`_schedule completion notification failed: ${a instanceof Error?a.message:String(a)}`)}),o.callIds.size===0&&t.removeEventListener("abort",o.onAbort)}finally{this.isScheduling=!1}}async handleConfirmationResponse(e,t,n,s,o){let a=this.toolCalls.find(l=>l.request.callId===e&&l.status==="awaiting_approval");if(a){try{await this._handleConfirmationResponseInner(e,a,t,n,s,o)}catch(l){let c=s.aborted;this.finalizeBlockedSpan(e,c?"aborted":"error","system");let u=this.toolSpans.get(e);throw u&&(c?bc(u):vs(u,yR,l instanceof Error?l.message:String(l))),this.finalizeToolSpan(e),yt.warn(`handleConfirmationResponse failed for ${e}: ${l instanceof Error?l.message:String(l)}`),l}await this.attemptExecutionOfScheduledCalls(s)}}async _handleConfirmationResponseInner(e,t,n,s,o,a){if(await n(s,a),(s==="proceed_always"||s==="proceed_always_project"||s==="proceed_always_user")&&(await z4(s,t.confirmationDetails,this.config.getOnPersistPermissionRule?.(),this.config.getPermissionManager?.(),a),await this.autoApproveCompatiblePendingTools(o,e)),this.setToolCallOutcome(e,s),this.recordAutoModeFallbackResolution(e,s),s==="cancel"||o.aborted){let l=a?.cancelMessage||"User did not allow tool call";this.setStatusInternal(e,"cancelled",l);let c=this.toolSpans.get(e);c&&bc(c);let u=s==="cancel";this.finalizeBlockedSpan(e,u?"cancel":"aborted",u?this.getBlockedSource():"system"),this.finalizeToolSpan(e)}else if(s==="modify_with_editor"){let l=t;if(nL(l.tool)){let c=l.tool.getModifyContext(o),u=this.getPreferredEditor();if(!u){yt.warn(`ModifyWithEditor requested for ${e} but no editor available \u2014 tool stays in awaiting_approval; user can recover via Cancel/Proceed`);let p=this.toolSpans.get(e);if(p)try{p.setAttributes({"matilda-code.tool.modify_with_editor_unavailable":!0})}catch{}return}this.setStatusInternal(e,"awaiting_approval",{...l.confirmationDetails,isModifying:!0});let h={...l.request.args};for(let p of Rd)typeof h[p]=="string"&&(h[p]=Xs(String(h[p]).trim()));let{updatedParams:d,updatedDiff:f}=await VK(h,c,u,o,this.onEditorClose);this.setArgsInternal(e,d),this.setStatusInternal(e,"awaiting_approval",{...l.confirmationDetails,fileDiff:f,isModifying:!1})}}else{a?.newContent&&t&&await this._applyInlineModify(t,a,o),this.setStatusInternal(e,"scheduled");let l=s==="proceed_once"?"proceed_once":"proceed_always";this.finalizeBlockedSpan(e,l,this.getBlockedSource())}}recordAutoModeFallbackResolution(e,t){let n=this.autoModeFallbackCallIds.delete(e);if(this.config.getApprovalMode()==="auto"&&n&&QM(t)){let s=this.config.getAutoModeDenialState(),o=ZM(s);if(o===s){yt.warn("Auto mode denial counters already clear after fallback approval: "+ru(s));return}yt.warn(`Auto mode denial counters reset after fallback approval: ${ru(s)} -> ${ru(o)}`),this.config.setAutoModeDenialState(o)}}async openIdeDiffIfEnabled(e,t,n){if(e.type!=="edit"||!this.config.getIdeMode())return;let s;try{let a=await AT.getInstance();if(!a.isDiffingEnabled())return;s=await a.openDiff(e.filePath,e.newContent)}catch(a){n.aborted||yt.warn(`IDE diff open failed for ${t}: ${a instanceof Error?a.message:String(a)}`);return}if(this.toolCalls.find(a=>a.request.callId===t&&a.status==="awaiting_approval"))if(s.status==="accepted"){let a=s.content!=null&&s.content!==e.newContent;await this.handleConfirmationResponse(t,e.onConfirm,"proceed_once",n,a?{newContent:s.content}:void 0)}else await this.handleConfirmationResponse(t,e.onConfirm,"cancel",n)}async _applyInlineModify(e,t,n){let s=e.confirmationDetails;if(s.type!=="edit"||!nL(e.tool)||!t.newContent)return;let o=s.originalContent??"",l=e.tool.getModifyContext(n).createUpdatedParams(o,t.newContent,e.request.args),c=zd(s.filePath,o,t.newContent,"Current","Proposed");this.setArgsInternal(e.request.callId,l),this.setStatusInternal(e.request.callId,"awaiting_approval",{...s,fileDiff:c})}async attemptExecutionOfScheduledCalls(e){if(this.toolCalls.every(n=>n.status==="scheduled"||n.status==="cancelled"||n.status==="success"||n.status==="error")){let n=this.toolCalls.filter(o=>o.status==="scheduled"),s=eVe(n);for(let o of s)if(o.concurrent&&o.calls.length>1)await this.runConcurrently(o.calls,e);else for(let a of o.calls)await this.executeSingleToolCall(a,e)}}async runConcurrently(e,t){let n=parseInt(process.env.MATILDA_CODE_MAX_TOOL_CONCURRENCY||"",10),s=Number.isFinite(n)&&n>=1?n:10,o=new Set;for(let a of e){let l=this.executeSingleToolCall(a,t).finally(()=>{o.delete(l)});o.add(l),o.size>=s&&await Promise.race(o)}await Promise.all(o)}async executeSingleToolCall(e,t){if(e.status!=="scheduled")return;let n=e,{callId:s,name:o}=n.request,a=this.toolSpans.get(s);if(!a){let l=vd(o);a=VR(l,{"tool.call_id":s,call_id:s,tool_name:l}),this.toolSpans.set(s,a)}try{await r2(a,()=>this._executeToolCallBody(n,t,a))}catch(l){let c=l instanceof Error?l.message:String(l);throw vs(a,yR,c),this.setStatusInternal(s,"error",Er(n.request,l instanceof Error?l:new Error(c),"unhandled_exception")),l}finally{this.finalizeToolSpan(s),this.memoryMonitor?.scheduleCheck()}}async _executeToolCallBody(e,t,n){let{callId:s,name:o}=e.request,a=vd(o),l=e.invocation,c=e.request.args;for(let m of Rd)typeof c[m]=="string"&&(c[m]=Xs(String(c[m]).trim()));this.config.getTelemetryIncludeSensitiveSpanAttributes?.()&&Qj(this.config,n,o,Ba(c)??"{}");let u=CM(),h=this.config.getMessageBus(),d=!this.config.getDisableAllHooks();if(d&&h){let m=this.config.getApprovalMode(),_=await this.withHookSpan({hookEvent:"PreToolUse",toolName:a,toolUseId:u},()=>EM(h,a,c,u,m),b=>b.hookError?{success:!1,error:b.hookError,shouldProceed:!0}:{success:!0,shouldProceed:b.shouldProceed,blockType:b.shouldProceed?void 0:b.blockType,hasAdditionalContext:!!b.additionalContext});if(!_.shouldProceed){let b=_.blockReason||"Tool execution blocked by hook",v=Er(e.request,new Error(b),"execution_denied");za(this.config,n,o,`BLOCKED: ${b}`),this.setStatusInternal(s,"error",v),vs(n,T6e,O6e);return}}this.setStatusInternal(s,"executing");let f=e.tool.canUpdateOutput?m=>{this.outputUpdateHandler&&this.outputUpdateHandler(s,m),this.toolCalls=this.toolCalls.map(_=>_.request.callId===s&&_.status==="executing"?{..._,liveOutput:m}:_),this.notifyToolCallsUpdate()}:void 0,p=this.config.getShellExecutionConfig(),y=s2(),w=Jv(this.config,`Matilda is executing tool ${a}`);try{let m;if(l instanceof Pb){let v=E=>{this.toolCalls=this.toolCalls.map(T=>T.request.callId===s&&T.status==="executing"?{...T,pid:E}:T),this.notifyToolCallsUpdate()},S=E=>{this.toolCalls=this.toolCalls.map(T=>T.request.callId===s&&T.status==="executing"?{...T,promoteAbortController:E}:T),this.notifyToolCallsUpdate()};m=l.execute(t,f,p,v,S)}else m=l.execute(t,f,p);let _=await m,b=t.aborted;if(KR(y,{success:_.error===void 0&&!b,error:b?kue:_.error?Eue:void 0,cancelled:b}),b){let v="User cancelled tool execution.";if(d&&h){let S=await this.withHookSpan({hookEvent:"PostToolUseFailure",toolName:a,toolUseId:u,isInterrupt:!0},()=>wR(h,u,a,c,v,!0,this.config.getApprovalMode()),this.postToolUseFailureEndMeta);S.additionalContext&&(v+=`
1985
1985
 
1986
1986
  ${S.additionalContext}`)}za(this.config,n,o,`CANCELLED: ${v}`),this.setStatusInternal(s,"cancelled",v),bc(n);return}if(_.error===void 0){let v=_.llmContent,S=typeof v=="string"?v.length:void 0,E,T;if(d&&h){let W={llmContent:v,returnDisplay:_.returnDisplay},V=this.config.getApprovalMode(),x=await this.withHookSpan({hookEvent:"PostToolUse",toolName:a,toolUseId:u},()=>TM(h,a,c,W,u,V),I=>I.hookError?{success:!1,error:I.hookError,shouldStop:!1}:{success:!0,shouldStop:I.shouldStop,hasAdditionalContext:!!I.additionalContext,blockType:I.shouldStop?"stop":void 0});if(x.additionalContext&&(E=x.additionalContext),x.shouldStop){let I=x.stopReason||"Execution stopped by hook",L=Er(e.request,new Error(I),"execution_denied");za(this.config,n,o,`STOPPED: ${I}`),this.setStatusInternal(s,"error",L),vs(n,k6e,D6e);return}}v=await this.maybePersistLargeToolResult(s,o,v);let A=z6e(o,c),k=B6e(o)&&Array.isArray(_.resultFilePaths)?_.resultFilePaths:[],P=Array.from(new Set([...A.map(W=>Xs(W)),...k]));if(P.length>0){let W=this.config.getConditionalRulesRegistry(),V=this.config.getSkillManager(),x=[];for(let L of P){let O=W?.matchAndConsume(L);O&&x.push(O)}let I=await V?.matchAndActivateByPaths(P);if(I&&I.length>0&&V&&!!this.toolRegistry.getTool(R.SKILL)){let O=[];try{let z=await Bd(V,this.config),Y=new Set(I);O=z.entries.filter(ne=>ne.level!==void 0&&Y.has(ne.name))}catch(z){yt.warn("coreToolScheduler: collectAvailableSkillEntries failed in activation path",z),O=I.map(Y=>({name:Y,description:"",level:"project"}))}O.length>0&&(x.push(`The following skill(s) became available via the Skill tool based on the file you just accessed; invoke a skill by passing its name to the Skill tool:
1987
1987
  <available_skills>
@@ -1996,7 +1996,7 @@ ${A.additionalContext}`)}let S=this.config.getTruncateToolOutputThreshold()+vue;
1996
1996
 
1997
1997
  ${S.additionalContext}`)}za(this.config,n,o,`CANCELLED: ${v}`),this.setStatusInternal(s,"cancelled",v),bc(n);return}else{let v=_;if(d&&h){let S=await this.withHookSpan({hookEvent:"PostToolUseFailure",toolName:a,toolUseId:u,isInterrupt:!1},()=>wR(h,u,a,c,_,!1,this.config.getApprovalMode()),this.postToolUseFailureEndMeta);S.additionalContext&&(v+=`
1998
1998
 
1999
- ${S.additionalContext}`)}za(this.config,n,o,`EXCEPTION: ${v}`),this.setStatusInternal(s,"error",Er(e.request,m instanceof Error?new Error(v):new Error(String(m)),"unhandled_exception")),vs(n,yR,Tue)}}finally{w.release()}}async checkAndNotifyCompletion(){this.recordToolResults(this.toolCalls.filter(t=>t.status==="success"||t.status==="error"||t.status==="cancelled"));let e=this.toolCalls.every(t=>t.status==="success"||t.status==="error"||t.status==="cancelled");if(this.toolCalls.length>0&&e){let t=[...this.toolCalls];this.toolCalls=[],this.isFinalizingToolCalls=!0;let n=t.map(o=>this.callIdToPostToolBatchSignal.get(o.request.callId)).find(o=>!!o);for(let o of t)this.callIdToPostToolBatchSignal.delete(o.request.callId);let s;try{s=!this.config.getDisableAllHooks()&&(this.config.hasHooksForEvent?.("PostToolBatch")??!1)?this.config.getMessageBus():void 0}catch(o){yt.warn(`PostToolBatch hook setup failed: ${o instanceof Error?o.message:String(o)}`)}try{if(s){let o=t.map(K6e),a=this.config.getApprovalMode(),l=await this.withHookSpan({hookEvent:"PostToolBatch",toolName:"batch"},()=>g3(s,o,a,n),c=>c.hookError?{success:!1,error:c.hookError,shouldStop:!1,postBatchStop:!1}:{success:!0,shouldStop:c.shouldStop,hasAdditionalContext:!!c.additionalContext,blockType:c.shouldStop?"stop":void 0,postBatchStop:c.shouldStop,postBatchStopReason:c.shouldStop?c.stopReason||"no reason given":void 0});l.shouldStop&&(yt.info(`PostToolBatch hook stopped batch (${t.length} calls): ${l.stopReason||"no reason given"}`),t=Z6e(t,l.stopReason||"Execution stopped by PostToolBatch hook")),t=X6e(t,l.additionalContext)}t=await this.applyBatchOutputBudget(t);for(let o of t)w2(this.config,new O2(o));this.recordToolResults(t,!0),this.onAllToolCallsComplete&&await this.onAllToolCallsComplete(t),this.notifyToolCallsUpdate()}finally{if(this.recordedToolResults.clear(),this.isFinalizingToolCalls=!1,this.requestQueue.length>0){let o=this.requestQueue.shift();this._schedule(o.request,o.signal).then(o.resolve).catch(o.reject)}}}}async maybePersistLargeToolResult(e,t,n){if(C6e.has(t))return n;let s=E6e(n);if(!s||sP(s))return n;let o=this.config.getTruncateToolOutputThreshold()+vue;if(s.length<=o)return n;let a=await iP(e,t,s,this.config);if(a.outputFile&&yt.debug(`Persisted ${t} result (${a.bytesWritten} bytes) to ${a.outputFile}`),Array.isArray(n)){let l=n.filter(u=>u.inlineData||u.fileData),c={text:a.content};return l.length>0?[c,...l]:[c]}return a.content}recordToolResults(e,t=!1){if(!this.chatRecordingService)return;if(t){let s=[...this.recordedToolResults.entries()];if(e.every((o,a)=>s[a]?.[0]===o.request&&s[a]?.[1].response===o.response))return}if(e.flatMap(s=>s.response.responseParts).length!==0)for(let s of e){let o=this.recordedToolResults.get(s.request);if(!t&&o?.response===s.response)continue;let a=this.chatRecordingService.recordToolResult(s.response.responseParts,{callId:s.request.callId,status:s.status,resultDisplay:s.response.resultDisplay,error:s.response.error,errorType:s.response.errorType},o?.uuid);a&&this.recordedToolResults.set(s.request,{uuid:a,response:s.response})}}async applyBatchOutputBudget(e){let t=this.config.getToolOutputBatchBudget?.()??Number.POSITIVE_INFINITY;if(!Number.isFinite(t))return e;let n=e.map(Pue),s=n.reduce((c,u)=>c+u,0);if(s<=t)return e;let o=e.map((c,u)=>u).sort((c,u)=>n[u]-n[c]),a=[...e],l=0;for(let c of o){if(s<=t)break;let u=await this.offloadCallOutput(a[c]);u&&(s-=n[c]-Pue(u),a[c]=u,l++)}return l>0&&yt.info(`Batch output budget (${t} chars): offloaded ${l} largest result(s) to disk.`),s>t&&yt.warn(`Batch output budget (${t} chars) still exceeded after offloading ${l}: ${s} chars across ${e.length} result(s).`),a}async offloadCallOutput(e){if(e.status!=="success")return null;let t=e.response.responseParts;if(t.length!==1)return null;let n=t[0]?.functionResponse;if(!n)return null;let s=n.response?.output;if(typeof s!="string"||n.parts&&n.parts.length>0||s.startsWith(nP)||s.startsWith("<persisted-output>"))return null;let o;try{o=await Zp(this.config,e.request.name,s,{threshold:q6e},e.request.prompt_id)}catch{return null}return o.outputFile?{...e,response:{...e.response,responseParts:[{functionResponse:{id:n.id,name:n.name,response:{output:o.content}}}],contentLength:o.content.length}}:null}notifyToolCallsUpdate(){this.onToolCallsUpdate&&this.onToolCallsUpdate([...this.toolCalls])}setToolCallOutcome(e,t){this.toolCalls=this.toolCalls.map(n=>n.request.callId!==e?n:{...n,outcome:t})}async autoApproveCompatiblePendingTools(e,t){let n=this.toolCalls.filter(s=>s.status==="awaiting_approval"&&s.request.callId!==t);for(let s of n)try{let o=s.invocation.params,a=await aI(this.config,s.invocation,s.request.name,o),{finalPermission:l,pmForcedAsk:c,pmCtx:u}=a,h=this.config.getApprovalMode()==="auto"&&FS(u,this.config.getCwd());if(l==="allow"&&h){yt.info(`Auto mode: pending L4 allow overridden by protected-write guard for ${s.request.name}`);let d=this.config.getAutoModeDenialState(),f=NS(d),p=this.config.getGeminiClient?.()?.getHistoryTail(40,!1)??[],y=await BS({ctx:u,pmForcedAsk:c,toolParams:o,messages:p,config:this.config,signal:e,skipClassifierReason:f.fallback?f.reason:void 0}),w=$S(y,this.config,d);if(!this.config.getDisableAllHooks()&&US(y,w))try{await this.config.getHookSystem?.()?.firePermissionDeniedEvent(s.request.name,o,s.request.callId,HS(y),e)}catch(m){yt.warn(`PermissionDenied hook failed for pending tool ${s.request.callId}: ${m instanceof Error?m.message:String(m)}`)}switch(w.kind){case"approved":this.setToolCallOutcome(s.request.callId,"proceed_always"),this.setStatusInternal(s.request.callId,"scheduled"),this.finalizeBlockedSpan(s.request.callId,"auto_approved","auto");break;case"blocked":{this.setStatusInternal(s.request.callId,"error",Er(s.request,new Error(w.errorMessage),"execution_denied")),this.finalizeBlockedSpan(s.request.callId,"error","auto");let m=this.toolSpans.get(s.request.callId);m&&(vs(m,Sue,Cue),this.finalizeToolSpan(s.request.callId));break}case"fallback":f.fallback&&(this.autoModeFallbackCallIds.add(s.request.callId),yt.warn(`Auto mode fallback for pending tool (${f.reason}): consecutiveBlock=${d.consecutiveBlock}, consecutiveUnavailable=${d.consecutiveUnavailable}`));break;default:{let m=w}}if(w.kind==="approved"||w.kind==="blocked"||w.kind==="fallback")continue}l==="allow"&&(this.setToolCallOutcome(s.request.callId,"proceed_always"),this.setStatusInternal(s.request.callId,"scheduled"),this.finalizeBlockedSpan(s.request.callId,"auto_approved","auto"))}catch(o){yt.error(`Error checking confirmation for tool ${s.request.callId}:`,o)}}};var gd=new Set([R.AGENT,R.CRON_CREATE,R.CRON_LIST,R.CRON_DELETE,R.TASK_STOP,R.SEND_MESSAGE,R.TEAM_CREATE,R.TEAM_DELETE,R.TASK_CREATE,R.TASK_UPDATE,R.TASK_LIST,R.ENTER_WORKTREE,R.EXIT_WORKTREE,R.WORKFLOW]),nVe=new Set([R.AGENT,R.CRON_CREATE,R.CRON_LIST,R.CRON_DELETE,R.TASK_STOP,R.TEAM_CREATE,R.TEAM_DELETE,R.ENTER_WORKTREE,R.EXIT_WORKTREE,R.WORKFLOW]),sVe="[Message from parent agent]:",Cp=class{subagentId;name;runtimeContext;promptConfig;modelConfig;runConfig;toolConfig;eventEmitter;hooks;stats=new Nj;runtimeView;messages=[];pendingApprovals=new Map;liveOutputs=new Map;shellPids=new Map;executionStats={startTimeMs:0,totalDurationMs:0,rounds:0,totalToolCalls:0,successfulToolCalls:0,failedToolCalls:0,inputTokens:0,outputTokens:0,totalTokens:0};lastPromptTokenCount=0;toolUsage=new Map;constructor(e,t,n,s,o,a,l,c,u){let h=rVe().replace(/-/g,"").slice(0,8);this.subagentId=`${e}-${h}`,this.name=e,this.runtimeContext=t,this.promptConfig=n,this.modelConfig=s,this.runConfig=o,this.toolConfig=a,this.eventEmitter=l??new ls,this.hooks=c,this.runtimeView=u,this.setupStateListeners()}async createChat(e,t){if(!this.promptConfig.systemPrompt&&!this.promptConfig.renderedSystemPrompt&&!this.promptConfig.initialMessages)throw new Error("PromptConfig must have `systemPrompt`, `renderedSystemPrompt`, or `initialMessages` defined.");if(this.promptConfig.systemPrompt&&this.promptConfig.renderedSystemPrompt)throw new Error("PromptConfig cannot have both `systemPrompt` and `renderedSystemPrompt` defined.");let n=!!this.promptConfig.initialMessages&&this.promptConfig.initialMessages.length>0,s=this.willHaveSkillTool(),[o]=n?[[]]:await Ja(this.runtimeContext,void 0,{includeDeferredToolsReminder:!1,includeAvailableSkillsReminder:s}),a=[...o,...t?.extraHistory??[],...this.promptConfig.initialMessages??[]],l={};if(this.promptConfig.renderedSystemPrompt!==void 0)l.systemInstruction=this.promptConfig.renderedSystemPrompt;else if(this.promptConfig.systemPrompt){let c=this.buildChatSystemPrompt(e,t);c&&(l.systemInstruction=c)}try{let c=new Xa(this.runtimeContext,l,a);return c.setLastPromptTokenCount(this.lastPromptTokenCount),c}catch(c){await Bi(c,"Error initializing chat session.",a,"startChat");return}}willHaveSkillTool(){if(!this.toolConfig)return!gd.has(R.SKILL);let e=this.toolConfig.tools.filter(n=>typeof n=="string");return e.includes("*")||e.length===0?!gd.has(R.SKILL):e.includes(R.SKILL)}async prepareTools(){let e=this.runtimeContext.getToolRegistry();await e.warmAll();let t=[],n=cv()?nVe:gd,s=new Set([R.AGENT]);if(this.toolConfig){let o=this.toolConfig.tools.filter(c=>typeof c=="string"),a=o.includes("*"),l=this.toolConfig.tools.filter(c=>typeof c!="string");a||o.length===0&&l.length===0?t.push(...e.getFunctionDeclarations({includeDeferred:!0}).filter(c=>!(c.name&&n.has(c.name)))):t.push(...e.getFunctionDeclarationsFiltered(o.filter(c=>!n.has(c)))),t.push(...l.filter(c=>!(c.name&&s.has(c.name))))}else t.push(...e.getFunctionDeclarations({includeDeferred:!0}).filter(o=>!(o.name&&n.has(o.name))));if(this.toolConfig?.disallowedTools?.length){let o=this.toolConfig.disallowedTools;return t.filter(a=>a.name?!o.some(l=>a.name.startsWith("mcp__")?DM(l,a.name):l===a.name):!0)}return t}async runReasoningLoop(e,t,n,s,o){let a=()=>this._runReasoningLoopInner(e,t,n,s,o);return this.runInAgentFrames(a)}runInAgentFrames(e,t,n,s){let o=()=>Ld("unknown",()=>Io.run(this.name,()=>{let a=()=>this.withRuntimeView(e,t);return n?el(n,a):a()}));return s?tm(s,o):o()}withRuntimeView(e,t){let n=this.runtimeView??t;return n?wS(n,e):e()}async _runReasoningLoopInner(e,t,n,s,o){let a=o?.startTimeMs??Date.now(),l=t,c=0,u="",h=null,d;for(;;){if(s.signal.aborted){h="CANCELLED";break}if(o?.maxTurns&&c>=o.maxTurns){h="MAX_TURNS";break}let f=(Date.now()-a)/(1e3*60);if(o?.maxTimeMinutes&&f>=o.maxTimeMinutes){h="TIMEOUT";break}let p=Lo(s);try{let y=`${this.runtimeContext.getSessionId()}#${this.subagentId}#${c++}`,w={message:l[0]?.parts||[],config:{abortSignal:p.signal,tools:[{functionDeclarations:n}],...d!==void 0?{maxOutputTokens:d}:{}}},m=Date.now(),_=await e.sendMessageStream(this.modelConfig.model||this.runtimeContext.getModel()||Do,w,y);this.eventEmitter?.emit("round_start",{subagentId:this.subagentId,round:c,promptId:y,timestamp:Date.now()});let b=[],v="",S="",E,T,A=!1;for await(let k of _){if(p.signal.aborted)return{text:u,terminateMode:"CANCELLED",turnsUsed:c};if(k.type==="retry"){k.maxOutputTokensEscalated!==void 0&&(d=k.maxOutputTokensEscalated),b.length=0,v="",S="",E=void 0,T=void 0,A=!1;continue}if(k.type==="compressed"){this.runtimeContext.getDebugLogger().debug(`[AGENT-COMPACT] subagent=${this.subagentId} round=${c} tokens ${k.info.originalTokenCount} -> ${k.info.newTokenCount}`);continue}if(k.type==="chunk"){let P=k.value;P.responseId&&(T=P.responseId),P.functionCalls&&b.push(...P.functionCalls),P.candidates?.[0]?.finishReason===Gr.MAX_TOKENS&&(A=!0);let F=P.candidates?.[0]?.content?.parts||[];for(let D of F){let H=D.text,G=D.thought??!1;H&&G&&(S+=H),H&&!G&&(v+=H),H&&this.eventEmitter?.emit("stream_text",{subagentId:this.subagentId,round:c,text:H,thought:G,timestamp:Date.now()})}P.usageMetadata&&(E=P.usageMetadata)}}if((v||S)&&this.eventEmitter?.emit("round_text",{subagentId:this.subagentId,round:c,text:v,thoughtText:S,timestamp:Date.now()}),this.executionStats.rounds=c,this.stats.setRounds(c),f=(Date.now()-a)/(1e3*60),o?.maxTimeMinutes&&f>=o.maxTimeMinutes){h="TIMEOUT";break}if(E&&this.recordTokenUsage(E,c,m),b.length>0){l=await this.processFunctionCalls(b,p,y,c,n,T,A);let k=this.drainExternalInputs(o);k.length>0&&(l[l.length-1].parts.push(...this.externalInputsToParts(k,!0)),this.emitExternalInputEvents(k))}else{let k=this.drainExternalInputs(o);if(k.length>0)l=this.externalInputsToContent(k),this.emitExternalInputEvents(k);else if(o?.shouldWaitForExternalMessages?.()){this.eventEmitter?.emit("round_end",{subagentId:this.subagentId,round:c,promptId:y,timestamp:Date.now()});let P=await this.waitForExternalInputs(o,s,a,c);if(P.terminateMode){u=v.trim(),h=P.terminateMode;break}if(P.inputs.length>0){l=this.externalInputsToContent(P.inputs),this.emitExternalInputEvents(P.inputs);continue}if(v&&v.trim().length>0){u=v.trim();break}l=[{role:"user",parts:[{text:"Please provide the final result now and stop calling tools."}]}];continue}else{if(v&&v.trim().length>0){u=v.trim(),this.eventEmitter?.emit("round_end",{subagentId:this.subagentId,round:c,promptId:y,timestamp:Date.now()});break}l=[{role:"user",parts:[{text:"Please provide the final result now and stop calling tools."}]}]}}this.eventEmitter?.emit("round_end",{subagentId:this.subagentId,round:c,promptId:y,timestamp:Date.now()})}finally{p.abort()}}return{text:u,terminateMode:h,turnsUsed:c}}drainExternalInputs(e){return e?.getExternalMessages?.()??[]}externalInputText(e,t){let n=typeof e=="string"?`${sVe} ${e}`:e.text;return t?`
1999
+ ${S.additionalContext}`)}za(this.config,n,o,`EXCEPTION: ${v}`),this.setStatusInternal(s,"error",Er(e.request,m instanceof Error?new Error(v):new Error(String(m)),"unhandled_exception")),vs(n,yR,Tue)}}finally{w.release()}}async checkAndNotifyCompletion(){this.recordToolResults(this.toolCalls.filter(t=>t.status==="success"||t.status==="error"||t.status==="cancelled"));let e=this.toolCalls.every(t=>t.status==="success"||t.status==="error"||t.status==="cancelled");if(this.toolCalls.length>0&&e){let t=[...this.toolCalls];this.toolCalls=[],this.isFinalizingToolCalls=!0;let n=t.map(a=>this.callIdToPostToolBatchSignal.get(a.request.callId)).find(a=>!!a);for(let a of t)this.callIdToPostToolBatchSignal.delete(a.request.callId);let s;try{s=!this.config.getDisableAllHooks()&&(this.config.hasHooksForEvent?.("PostToolBatch")??!1)?this.config.getMessageBus():void 0}catch(a){yt.warn(`PostToolBatch hook setup failed: ${a instanceof Error?a.message:String(a)}`)}let o=!1;try{if(this.chatRecordingService&&await this.toolResultWriteChain,s){let a=t.map(K6e),l=this.config.getApprovalMode(),c=await this.withHookSpan({hookEvent:"PostToolBatch",toolName:"batch"},()=>g3(s,a,l,n),u=>u.hookError?{success:!1,error:u.hookError,shouldStop:!1,postBatchStop:!1}:{success:!0,shouldStop:u.shouldStop,hasAdditionalContext:!!u.additionalContext,blockType:u.shouldStop?"stop":void 0,postBatchStop:u.shouldStop,postBatchStopReason:u.shouldStop?u.stopReason||"no reason given":void 0});c.shouldStop&&(yt.info(`PostToolBatch hook stopped batch (${t.length} calls): ${c.stopReason||"no reason given"}`),t=Z6e(t,c.stopReason||"Execution stopped by PostToolBatch hook")),t=X6e(t,c.additionalContext)}t=await this.applyBatchOutputBudget(t);for(let a of t)w2(this.config,new O2(a));this.recordToolResults(t,!0),this.chatRecordingService&&await this.toolResultWriteChain,o=!0,this.onAllToolCallsComplete&&await this.onAllToolCallsComplete(t),this.notifyToolCallsUpdate()}catch(a){let l=a instanceof Error?a:new Error(String(a));if(!o)for(let c of this.requestQueue.splice(0))c.reject(l);throw this.onToolCallsCompleteError?.(l,t,n),a}finally{if(this.recordedToolResults.clear(),this.toolResultWriteChain=Promise.resolve(),this.isFinalizingToolCalls=!1,this.requestQueue.length>0){let a=this.requestQueue.shift();this._schedule(a.request,a.signal).then(a.resolve).catch(a.reject)}}}}async maybePersistLargeToolResult(e,t,n){if(C6e.has(t))return n;let s=E6e(n);if(!s||sP(s))return n;let o=this.config.getTruncateToolOutputThreshold()+vue;if(s.length<=o)return n;let a=await iP(e,t,s,this.config);if(a.outputFile&&yt.debug(`Persisted ${t} result (${a.bytesWritten} bytes) to ${a.outputFile}`),Array.isArray(n)){let l=n.filter(u=>u.inlineData||u.fileData),c={text:a.content};return l.length>0?[c,...l]:[c]}return a.content}recordToolResults(e,t=!1){if(!this.chatRecordingService)return;if(t){let s=[...this.recordedToolResults.entries()];if(e.every((o,a)=>s[a]?.[0]===o.request&&s[a]?.[1].response===o.response))return}if(e.flatMap(s=>s.response.responseParts).length!==0)for(let s of e){let o=this.recordedToolResults.get(s.request);if(!t&&o?.response===s.response)continue;let a=this.chatRecordingService,l=this.toolResultWriteChain.then(async()=>a.recordToolResultCommitted(s.response.responseParts,{callId:s.request.callId,status:s.status,resultDisplay:s.response.resultDisplay,error:s.response.error,errorType:s.response.errorType},(await o?.commit)?.recordUuid));this.toolResultWriteChain=l.then(()=>{}),this.toolResultWriteChain.catch(()=>{}),this.recordedToolResults.set(s.request,{commit:l,response:s.response})}}async applyBatchOutputBudget(e){let t=this.config.getToolOutputBatchBudget?.()??Number.POSITIVE_INFINITY;if(!Number.isFinite(t))return e;let n=e.map(Pue),s=n.reduce((c,u)=>c+u,0);if(s<=t)return e;let o=e.map((c,u)=>u).sort((c,u)=>n[u]-n[c]),a=[...e],l=0;for(let c of o){if(s<=t)break;let u=await this.offloadCallOutput(a[c]);u&&(s-=n[c]-Pue(u),a[c]=u,l++)}return l>0&&yt.info(`Batch output budget (${t} chars): offloaded ${l} largest result(s) to disk.`),s>t&&yt.warn(`Batch output budget (${t} chars) still exceeded after offloading ${l}: ${s} chars across ${e.length} result(s).`),a}async offloadCallOutput(e){if(e.status!=="success")return null;let t=e.response.responseParts;if(t.length!==1)return null;let n=t[0]?.functionResponse;if(!n)return null;let s=n.response?.output;if(typeof s!="string"||n.parts&&n.parts.length>0||s.startsWith(nP)||s.startsWith("<persisted-output>"))return null;let o;try{o=await Zp(this.config,e.request.name,s,{threshold:q6e},e.request.prompt_id)}catch{return null}return o.outputFile?{...e,response:{...e.response,responseParts:[{functionResponse:{id:n.id,name:n.name,response:{output:o.content}}}],contentLength:o.content.length}}:null}notifyToolCallsUpdate(){this.onToolCallsUpdate&&this.onToolCallsUpdate([...this.toolCalls])}setToolCallOutcome(e,t){this.toolCalls=this.toolCalls.map(n=>n.request.callId!==e?n:{...n,outcome:t})}async autoApproveCompatiblePendingTools(e,t){let n=this.toolCalls.filter(s=>s.status==="awaiting_approval"&&s.request.callId!==t);for(let s of n)try{let o=s.invocation.params,a=await aI(this.config,s.invocation,s.request.name,o),{finalPermission:l,pmForcedAsk:c,pmCtx:u}=a,h=this.config.getApprovalMode()==="auto"&&FS(u,this.config.getCwd());if(l==="allow"&&h){yt.info(`Auto mode: pending L4 allow overridden by protected-write guard for ${s.request.name}`);let d=this.config.getAutoModeDenialState(),f=NS(d),p=this.config.getGeminiClient?.()?.getHistoryTail(40,!1)??[],y=await BS({ctx:u,pmForcedAsk:c,toolParams:o,messages:p,config:this.config,signal:e,skipClassifierReason:f.fallback?f.reason:void 0}),w=$S(y,this.config,d);if(!this.config.getDisableAllHooks()&&US(y,w))try{await this.config.getHookSystem?.()?.firePermissionDeniedEvent(s.request.name,o,s.request.callId,HS(y),e)}catch(m){yt.warn(`PermissionDenied hook failed for pending tool ${s.request.callId}: ${m instanceof Error?m.message:String(m)}`)}switch(w.kind){case"approved":this.setToolCallOutcome(s.request.callId,"proceed_always"),this.setStatusInternal(s.request.callId,"scheduled"),this.finalizeBlockedSpan(s.request.callId,"auto_approved","auto");break;case"blocked":{this.setStatusInternal(s.request.callId,"error",Er(s.request,new Error(w.errorMessage),"execution_denied")),this.finalizeBlockedSpan(s.request.callId,"error","auto");let m=this.toolSpans.get(s.request.callId);m&&(vs(m,Sue,Cue),this.finalizeToolSpan(s.request.callId));break}case"fallback":f.fallback&&(this.autoModeFallbackCallIds.add(s.request.callId),yt.warn(`Auto mode fallback for pending tool (${f.reason}): consecutiveBlock=${d.consecutiveBlock}, consecutiveUnavailable=${d.consecutiveUnavailable}`));break;default:{let m=w}}if(w.kind==="approved"||w.kind==="blocked"||w.kind==="fallback")continue}l==="allow"&&(this.setToolCallOutcome(s.request.callId,"proceed_always"),this.setStatusInternal(s.request.callId,"scheduled"),this.finalizeBlockedSpan(s.request.callId,"auto_approved","auto"))}catch(o){yt.error(`Error checking confirmation for tool ${s.request.callId}:`,o)}}};var gd=new Set([R.AGENT,R.CRON_CREATE,R.CRON_LIST,R.CRON_DELETE,R.TASK_STOP,R.SEND_MESSAGE,R.TEAM_CREATE,R.TEAM_DELETE,R.TASK_CREATE,R.TASK_UPDATE,R.TASK_LIST,R.ENTER_WORKTREE,R.EXIT_WORKTREE,R.WORKFLOW]),nVe=new Set([R.AGENT,R.CRON_CREATE,R.CRON_LIST,R.CRON_DELETE,R.TASK_STOP,R.TEAM_CREATE,R.TEAM_DELETE,R.ENTER_WORKTREE,R.EXIT_WORKTREE,R.WORKFLOW]),sVe="[Message from parent agent]:",Cp=class{subagentId;name;runtimeContext;promptConfig;modelConfig;runConfig;toolConfig;eventEmitter;hooks;stats=new Nj;runtimeView;messages=[];pendingApprovals=new Map;liveOutputs=new Map;shellPids=new Map;executionStats={startTimeMs:0,totalDurationMs:0,rounds:0,totalToolCalls:0,successfulToolCalls:0,failedToolCalls:0,inputTokens:0,outputTokens:0,totalTokens:0};lastPromptTokenCount=0;toolUsage=new Map;constructor(e,t,n,s,o,a,l,c,u){let h=rVe().replace(/-/g,"").slice(0,8);this.subagentId=`${e}-${h}`,this.name=e,this.runtimeContext=t,this.promptConfig=n,this.modelConfig=s,this.runConfig=o,this.toolConfig=a,this.eventEmitter=l??new ls,this.hooks=c,this.runtimeView=u,this.setupStateListeners()}async createChat(e,t){if(!this.promptConfig.systemPrompt&&!this.promptConfig.renderedSystemPrompt&&!this.promptConfig.initialMessages)throw new Error("PromptConfig must have `systemPrompt`, `renderedSystemPrompt`, or `initialMessages` defined.");if(this.promptConfig.systemPrompt&&this.promptConfig.renderedSystemPrompt)throw new Error("PromptConfig cannot have both `systemPrompt` and `renderedSystemPrompt` defined.");let n=!!this.promptConfig.initialMessages&&this.promptConfig.initialMessages.length>0,s=this.willHaveSkillTool(),[o]=n?[[]]:await Ja(this.runtimeContext,void 0,{includeDeferredToolsReminder:!1,includeAvailableSkillsReminder:s}),a=[...o,...t?.extraHistory??[],...this.promptConfig.initialMessages??[]],l={};if(this.promptConfig.renderedSystemPrompt!==void 0)l.systemInstruction=this.promptConfig.renderedSystemPrompt;else if(this.promptConfig.systemPrompt){let c=this.buildChatSystemPrompt(e,t);c&&(l.systemInstruction=c)}try{let c=new Xa(this.runtimeContext,l,a);return c.setLastPromptTokenCount(this.lastPromptTokenCount),c}catch(c){await Bi(c,"Error initializing chat session.",a,"startChat");return}}willHaveSkillTool(){if(!this.toolConfig)return!gd.has(R.SKILL);let e=this.toolConfig.tools.filter(n=>typeof n=="string");return e.includes("*")||e.length===0?!gd.has(R.SKILL):e.includes(R.SKILL)}async prepareTools(){let e=this.runtimeContext.getToolRegistry();await e.warmAll();let t=[],n=cv()?nVe:gd,s=new Set([R.AGENT]);if(this.toolConfig){let o=this.toolConfig.tools.filter(c=>typeof c=="string"),a=o.includes("*"),l=this.toolConfig.tools.filter(c=>typeof c!="string");a||o.length===0&&l.length===0?t.push(...e.getFunctionDeclarations({includeDeferred:!0}).filter(c=>!(c.name&&n.has(c.name)))):t.push(...e.getFunctionDeclarationsFiltered(o.filter(c=>!n.has(c)))),t.push(...l.filter(c=>!(c.name&&s.has(c.name))))}else t.push(...e.getFunctionDeclarations({includeDeferred:!0}).filter(o=>!(o.name&&n.has(o.name))));if(this.toolConfig?.disallowedTools?.length){let o=this.toolConfig.disallowedTools;return t.filter(a=>a.name?!o.some(l=>a.name.startsWith("mcp__")?DM(l,a.name):l===a.name):!0)}return t}async runReasoningLoop(e,t,n,s,o){let a=()=>this._runReasoningLoopInner(e,t,n,s,o);return this.runInAgentFrames(a)}runInAgentFrames(e,t,n,s){let o=()=>Ld("unknown",()=>Io.run(this.name,()=>{let a=()=>this.withRuntimeView(e,t);return n?el(n,a):a()}));return s?tm(s,o):o()}withRuntimeView(e,t){let n=this.runtimeView??t;return n?wS(n,e):e()}async _runReasoningLoopInner(e,t,n,s,o){let a=o?.startTimeMs??Date.now(),l=t,c=0,u="",h=null,d;for(;;){if(s.signal.aborted){h="CANCELLED";break}if(o?.maxTurns&&c>=o.maxTurns){h="MAX_TURNS";break}let f=(Date.now()-a)/(1e3*60);if(o?.maxTimeMinutes&&f>=o.maxTimeMinutes){h="TIMEOUT";break}let p=Lo(s);try{let y=`${this.runtimeContext.getSessionId()}#${this.subagentId}#${c++}`,w={message:l[0]?.parts||[],config:{abortSignal:p.signal,tools:[{functionDeclarations:n}],...d!==void 0?{maxOutputTokens:d}:{}}},m=Date.now(),_=await e.sendMessageStream(this.modelConfig.model||this.runtimeContext.getModel()||Do,w,y);this.eventEmitter?.emit("round_start",{subagentId:this.subagentId,round:c,promptId:y,timestamp:Date.now()});let b=[],v="",S="",E,T,A=!1;for await(let k of _){if(p.signal.aborted)return{text:u,terminateMode:"CANCELLED",turnsUsed:c};if(k.type==="retry"){k.maxOutputTokensEscalated!==void 0&&(d=k.maxOutputTokensEscalated),b.length=0,v="",S="",E=void 0,T=void 0,A=!1;continue}if(k.type==="compressed"){this.runtimeContext.getDebugLogger().debug(`[AGENT-COMPACT] subagent=${this.subagentId} round=${c} tokens ${k.info.originalTokenCount} -> ${k.info.newTokenCount}`);continue}if(k.type==="chunk"){let P=k.value;P.responseId&&(T=P.responseId),P.functionCalls&&b.push(...P.functionCalls),P.candidates?.[0]?.finishReason===Gr.MAX_TOKENS&&(A=!0);let F=P.candidates?.[0]?.content?.parts||[];for(let D of F){let H=D.text,G=D.thought??!1;H&&G&&(S+=H),H&&!G&&(v+=H),H&&this.eventEmitter?.emit("stream_text",{subagentId:this.subagentId,round:c,text:H,thought:G,timestamp:Date.now()})}P.usageMetadata&&(E=P.usageMetadata)}}if((v||S)&&this.eventEmitter?.emit("round_text",{subagentId:this.subagentId,round:c,text:v,thoughtText:S,timestamp:Date.now()}),this.executionStats.rounds=c,this.stats.setRounds(c),f=(Date.now()-a)/(1e3*60),o?.maxTimeMinutes&&f>=o.maxTimeMinutes){h="TIMEOUT";break}if(E&&this.recordTokenUsage(E,c,m),b.length>0){l=await this.processFunctionCalls(b,p,y,c,n,T,A);let k=this.drainExternalInputs(o);k.length>0&&(l[l.length-1].parts.push(...this.externalInputsToParts(k,!0)),this.emitExternalInputEvents(k))}else{let k=this.drainExternalInputs(o);if(k.length>0)l=this.externalInputsToContent(k),this.emitExternalInputEvents(k);else if(o?.shouldWaitForExternalMessages?.()){this.eventEmitter?.emit("round_end",{subagentId:this.subagentId,round:c,promptId:y,timestamp:Date.now()});let P=await this.waitForExternalInputs(o,s,a,c);if(P.terminateMode){u=v.trim(),h=P.terminateMode;break}if(P.inputs.length>0){l=this.externalInputsToContent(P.inputs),this.emitExternalInputEvents(P.inputs);continue}if(v&&v.trim().length>0){u=v.trim();break}l=[{role:"user",parts:[{text:"Please provide the final result now and stop calling tools."}]}];continue}else{if(v&&v.trim().length>0){u=v.trim(),this.eventEmitter?.emit("round_end",{subagentId:this.subagentId,round:c,promptId:y,timestamp:Date.now()});break}l=[{role:"user",parts:[{text:"Please provide the final result now and stop calling tools."}]}]}}this.eventEmitter?.emit("round_end",{subagentId:this.subagentId,round:c,promptId:y,timestamp:Date.now()})}finally{p.abort()}}return{text:u,terminateMode:h,turnsUsed:c}}drainExternalInputs(e){return e?.getExternalMessages?.()??[]}externalInputText(e,t){let n=typeof e=="string"?`${sVe} ${e}`:e.text;return t?`
2000
2000
  ${n}`:n}externalInputsToParts(e,t){return e.map(n=>({text:this.externalInputText(n,t)}))}externalInputsToContent(e){return[{role:"user",parts:this.externalInputsToParts(e,!1)}]}emitExternalInputEvents(e){for(let t of e)this.eventEmitter?.emit("external_message",{subagentId:this.subagentId,kind:typeof t=="string"?"message":t.kind,text:typeof t=="string"?t:t.text,timestamp:Date.now()})}hasTurnBudgetForAnotherRound(e,t){return!e?.maxTurns||t<e.maxTurns}getRemainingTimeMs(e,t){if(e?.maxTimeMinutes)return e.maxTimeMinutes*60*1e3-(Date.now()-t)}async waitForExternalInputs(e,t,n,s){for(;;){let o=this.drainExternalInputs(e);if(o.length>0)return{inputs:o};if(t.signal.aborted)return{inputs:[],terminateMode:"CANCELLED"};if(!this.hasTurnBudgetForAnotherRound(e,s))return{inputs:[],terminateMode:"MAX_TURNS"};let a=this.getRemainingTimeMs(e,n);if(a!==void 0&&a<=0)return{inputs:[],terminateMode:"TIMEOUT"};if(!e.waitForExternalMessages)return{inputs:[]};if(!e.shouldWaitForExternalMessages?.())return{inputs:[]};let l=Lo(t),c=!1,u;a!==void 0&&(u=setTimeout(()=>{c=!0,l.abort()},a),u.unref?.());try{let h=await e.waitForExternalMessages(l.signal);if(t.signal.aborted)return{inputs:[],terminateMode:"CANCELLED"};if(c)return{inputs:[],terminateMode:"TIMEOUT"};if(h.length>0)return{inputs:h};if(!e.shouldWaitForExternalMessages?.())return{inputs:[]}}catch(h){if(t.signal.aborted)return{inputs:[],terminateMode:"CANCELLED"};if(c)return{inputs:[],terminateMode:"TIMEOUT"};throw h}finally{u&&clearTimeout(u),l.abort()}}}async processFunctionCalls(e,t,n,s,o,a,l=!1){let c=[],u=NG(e),h=new Set(o.map(E=>E.name)),d=[];for(let E of u){let T=E.id??`${E.name}-${Date.now()}`;if(!h.has(E.name)){let A=String(E.name),k=`Tool "${A}" not found. Tools must use the exact names provided.`;this.eventEmitter?.emit("tool_call",{subagentId:this.subagentId,round:s,callId:T,name:A,args:E.args??{},description:`Tool "${A}" not found`,isOutputMarkdown:!1,timestamp:Date.now()});let P={functionResponse:{id:T,name:A,response:{error:k}}};this.eventEmitter?.emit("tool_result",{subagentId:this.subagentId,round:s,callId:T,name:A,success:!1,error:k,responseParts:[P],resultDisplay:k,durationMs:0,timestamp:Date.now()}),this.recordToolCallStats(A,!1,0,k),c.push(P);continue}d.push(E)}let f=new Set,p=null,y=new Set,w=new Map,m=E=>({subagentId:this.subagentId,round:s,callId:E.request.callId,name:E.request.name,success:E.status==="success",error:E.response.error?.message,responseParts:E.response.responseParts,resultDisplay:E.response.resultDisplay,durationMs:E.durationMs??0,timestamp:Date.now()}),_=new Map,b=new Set,v=new vh({config:this.runtimeContext,outputUpdateHandler:(E,T)=>{this.eventEmitter?.emit("tool_output_update",{subagentId:this.subagentId,round:s,callId:E,outputChunk:T,pid:_.get(E),timestamp:Date.now()})},onAllToolCallsComplete:async E=>{for(let T of E){if(y.has(T.request.callId))continue;y.add(T.request.callId);let A=T.request.name,k=T.durationMs??0,P=T.status==="success",U=T.status==="error"||T.status==="cancelled"?T.response.error?.message:void 0;this.recordToolCallStats(A,P,k,U),this.eventEmitter?.emit("tool_result",m(T)),await this.hooks?.postToolUse?.({subagentId:this.subagentId,name:this.name,toolName:A,args:T.request.args,success:P,durationMs:k,errorMessage:U,timestamp:Date.now()});let F=T.response.responseParts;if(F){let D=Array.isArray(F)?F:[F];for(let H of D)typeof H=="string"?c.push({text:H}):H&&c.push(H)}}p?.()},onToolCallsUpdate:E=>{for(let T of E){if((T.status==="success"||T.status==="error"||T.status==="cancelled")&&!w.has(T.request.callId)&&!y.has(T.request.callId)){let k=m(T);w.set(T.request.callId,k),this.eventEmitter?.emit("tool_result_checkpoint",k)}if(T.status==="executing"){let k=T,P=k.pid,U=P!==void 0&&!_.has(T.request.callId);P!==void 0&&_.set(T.request.callId,P);let F=k.executionStartTime!==void 0&&!b.has(T.request.callId);F&&b.add(T.request.callId),(U||F)&&this.eventEmitter?.emit("tool_output_update",{subagentId:this.subagentId,round:s,callId:T.request.callId,outputChunk:k.liveOutput??"",pid:P,executionStartTime:k.executionStartTime,timestamp:Date.now()})}if(T.status!=="awaiting_approval")continue;let A=T;try{let{confirmationDetails:k}=A,{onConfirm:P,...U}=k,F=$m(),D=tl(),H=Cz();this.eventEmitter?.emit("tool_waiting_approval",{subagentId:this.subagentId,round:s,callId:A.request.callId,name:A.request.name,description:this.getToolDescription(A.request.name,A.request.args),args:A.request.args,confirmationDetails:U,respond:async(G,j)=>{f.has(A.request.callId)||(f.add(A.request.callId),await this.runInAgentFrames(()=>A.confirmationDetails.onConfirm(G,j),F,D??void 0,H))},timestamp:Date.now()})}catch{}}},getPreferredEditor:()=>{},onEditorClose:()=>{}}),S=d.map(E=>{let T=String(E.name||"unknown"),A=E.id??`${E.name}-${Date.now()}`,k=E.args??{},P={callId:A,name:T,args:k,isClientInitiated:!0,prompt_id:n,response_id:a,wasOutputTruncated:l},U=this.getToolDescription(T,k),F=this.getToolIsOutputMarkdown(T);return this.eventEmitter?.emit("tool_call",{subagentId:this.subagentId,round:s,callId:A,name:T,args:k,description:U,isOutputMarkdown:F,timestamp:Date.now()}),this.hooks?.preToolUse?.({subagentId:this.subagentId,name:this.name,toolName:T,args:k,timestamp:Date.now()}),P});if(S.length>0){let E=new Promise(A=>{p=()=>{A(),p=null}}),T=()=>{p?.();for(let A of S){if(y.has(A.callId))continue;y.add(A.callId);let k=w.get(A.callId);if(k){this.recordToolCallStats(A.name,k.success,k.durationMs??0,k.error),this.eventEmitter?.emit("tool_result",k);continue}let P="Tool call cancelled by user abort.";this.recordToolCallStats(A.name,!1,0,P),this.eventEmitter?.emit("tool_result",{subagentId:this.subagentId,round:s,callId:A.callId,name:A.name,success:!1,error:P,responseParts:[{functionResponse:{id:A.callId,name:A.name,response:{error:P}}}],resultDisplay:P,durationMs:0,timestamp:Date.now()})}};t.signal.addEventListener("abort",T,{once:!0});try{t.signal.aborted&&T(),await v.schedule(S,t.signal),await E}finally{t.signal.removeEventListener("abort",T)}}return e.length>0&&c.length===0&&c.push({text:"All tool calls failed. Please analyze the errors and try an alternative approach."}),[{role:"user",parts:c}]}getMessages(){return this.messages}getPendingApprovals(){return this.pendingApprovals}getLiveOutputs(){return this.liveOutputs}getShellPids(){return this.shellPids}pushMessage(e,t,n){let s={role:e,content:t,timestamp:Date.now()};n?.thought&&(s.thought=!0),n?.metadata&&(s.metadata=n.metadata),this.messages.push(s)}setPendingApproval(e,t){this.pendingApprovals.set(e,t)}deletePendingApproval(e){this.pendingApprovals.delete(e)}clearPendingApprovals(){this.pendingApprovals.clear()}getEventEmitter(){return this.eventEmitter}getExecutionSummary(){return this.stats.getSummary()}getStatistics(){let e=this.executionStats.totalToolCalls,t=e>0?this.executionStats.successfulToolCalls/e*100:0;return{...this.executionStats,successRate:t,toolUsage:Array.from(this.toolUsage.entries()).map(([n,s])=>({name:n,...s}))}}getToolDescription(e,t){try{let s=this.runtimeContext.getToolRegistry().getTool(e);return s&&s.build(t).getDescription()||""}catch{return""}}getToolIsOutputMarkdown(e){try{return this.runtimeContext.getToolRegistry().getTool(e)?.isOutputMarkdown??!1}catch{return!1}}recordToolCallStats(e,t,n,s){this.executionStats.totalToolCalls+=1,t?this.executionStats.successfulToolCalls+=1:this.executionStats.failedToolCalls+=1;let o=this.toolUsage.get(e)||{count:0,success:0,failure:0,totalDurationMs:0,averageDurationMs:0};o.count+=1,t?o.success+=1:(o.failure+=1,o.lastError=s||"Unknown error"),o.totalDurationMs=(o.totalDurationMs||0)+n,o.averageDurationMs=o.count>0?o.totalDurationMs/o.count:0,this.toolUsage.set(e,o),this.stats.recordToolCall(e,t,n,this.toolUsage.get(e)?.lastError)}setupStateListeners(){let e=this.eventEmitter;e.on("round_text",t=>{t.thoughtText&&this.pushMessage("assistant",t.thoughtText,{thought:!0}),t.text&&this.pushMessage("assistant",t.text)}),e.on("tool_call",t=>{this.pushMessage("tool_call",`Tool call: ${t.name}`,{metadata:{callId:t.callId,toolName:t.name,args:t.args,description:t.description,renderOutputAsMarkdown:t.isOutputMarkdown,round:t.round}})}),e.on("tool_output_update",t=>{this.liveOutputs.set(t.callId,t.outputChunk),t.pid!==void 0&&this.shellPids.set(t.callId,t.pid)}),e.on("tool_result",t=>{this.liveOutputs.delete(t.callId),this.shellPids.delete(t.callId),this.pendingApprovals.delete(t.callId);let n=t.success?"succeeded":"failed",s=t.error?`Tool ${t.name} ${n}: ${t.error}`:`Tool ${t.name} ${n}`;this.pushMessage("tool_result",s,{metadata:{callId:t.callId,toolName:t.name,success:t.success,resultDisplay:t.resultDisplay,outputFile:t.outputFile,round:t.round}})}),e.on("external_message",t=>{this.pushMessage("user",t.text)})}buildChatSystemPrompt(e,t){if(!this.promptConfig.systemPrompt)return"";let n=wae(this.promptConfig.systemPrompt,e);t?.interactive||(n+=`
2001
2001
 
2002
2002
  Important Rules:
@@ -2188,12 +2188,12 @@ ${Ud(r)}
2188
2188
  `)];return tt.debug(l.join(`
2189
2189
  `)),{contextParts:l,newIdeContext:t}}else{let n=[],s=new Map((this.lastSentIdeContext.workspaceState?.openFiles||[]).map(d=>[d.path,d])),o=new Map((t.workspaceState?.openFiles||[]).map(d=>[d.path,d])),a=[];for(let[d]of o.entries())s.has(d)||a.push(d);if(a.length>0){n.push("Files opened:");for(let d of a)n.push(` - ${d}`)}let l=[];for(let[d]of s.entries())o.has(d)||l.push(d);if(l.length>0){n.length>0&&n.push(""),n.push("Files closed:");for(let d of l)n.push(` - ${d}`)}let c=(this.lastSentIdeContext.workspaceState?.openFiles||[]).find(d=>d.isActive),u=(t.workspaceState?.openFiles||[]).find(d=>d.isActive);if(u)if(!c||c.path!==u.path)n.length>0&&n.push(""),n.push("Active file changed:"),n.push(` Path: ${u.path}`),u.cursor&&n.push(` Cursor: line ${u.cursor.line}, character ${u.cursor.character}`),u.selectedText&&(n.push(" Selected text:"),n.push("```"),n.push(u.selectedText),n.push("```"));else{let d=c.cursor,f=u.cursor;f&&(!d||d.line!==f.line||d.character!==f.character)&&(n.length>0&&n.push(""),n.push("Cursor moved:"),n.push(` Path: ${u.path}`),n.push(` New position: line ${f.line}, character ${f.character}`));let p=c.selectedText||"",y=u.selectedText||"";p!==y&&(n.length>0&&n.push(""),n.push("Selection changed:"),n.push(` Path: ${u.path}`),y?(n.push(" Selected text:"),n.push("```"),n.push(y),n.push("```")):n.push(" Selected text: (none)"))}else c&&(n.length>0&&n.push(""),n.push("Active file changed:"),n.push(" No active file"),n.push(` Previous path: ${c.path}`));if(n.length===0)return{contextParts:[],newIdeContext:t};let h=["Here is a summary of changes in the user's current editor context. Use it with the previous editor context when relevant, including to answer questions about the active file, open files, cursor, or selected text.",n.join(`
2190
2190
  `)];return tt.debug(h.join(`
2191
- `)),{contextParts:h,newIdeContext:t}}}runManagedAutoMemoryBackgroundTasks(e){if(e==="userQuery"||e==="toolResult"){let c=this.config.getProjectRoot(),u=this.config.getSessionId(),h=this.getHistoryShallow(),d=this.config.getMemoryManager(),f=this.config.getAutoSkillEnabled();if(f){let p=d.scheduleSkillReview({projectRoot:c,sessionId:u,history:h,config:this.config,toolCallCount:this.toolCallCount,skillsModified:this.skillsModifiedInSession,enabled:f,threshold:TR,maxTurns:ZB,timeoutMs:QB});p.status==="scheduled"?(this.toolCallCount=0,p.promise&&this.pendingMemoryTaskPromises.push(p.promise.then(y=>{let w=y.metadata?.touchedSkillFiles;return Array.isArray(w)?w.length:0}).catch(y=>(tt.warn("Failed to run managed skill review.",y),0)))):p.status==="skipped"&&p.skippedReason==="already_running"&&this.toolCallCount>=TR&&(this.toolCallCount=0),this.skillsModifiedInSession=!1}}if(e!=="userQuery")return;let t=this.config.getProjectRoot(),n=this.config.getSessionId(),s=this.getHistoryShallow(),o=this.config.getMemoryManager();if(!this.config.getManagedAutoMemoryEnabled())return;let a=o.scheduleExtract({projectRoot:t,sessionId:n,history:s,config:this.config}).then(c=>c.touchedTopics.length).catch(c=>(tt.warn("Failed to schedule managed auto-memory extraction.",c),0));this.pendingMemoryTaskPromises.push(a);let l=o.scheduleDream({projectRoot:t,sessionId:n,config:this.config}).then(c=>c.status==="scheduled"&&c.promise?c.promise.then(u=>{let h=u.metadata?.touchedTopics;return h?h.length:0}):0).catch(c=>(tt.warn("Failed to schedule managed auto-memory dream.",c),0));this.pendingMemoryTaskPromises.push(l)}consumePendingMemoryTaskPromises(){let e=this.pendingMemoryTaskPromises;return this.pendingMemoryTaskPromises=[],e}recordCompletedToolCall(e,t){if(this.rememberCompletedToolName(e),t&&o5e.has(e)){let n=t.file_path??t.path??t.target_file;typeof n=="string"&&Cd(n,this.config.getProjectRoot())&&(this.skillsModifiedInSession=!0)}this.toolCallCount+=1}rememberCompletedToolName(e){let t=e.trim();t&&(this.recentCompletedToolNames=[...this.recentCompletedToolNames.filter(n=>n!==t),t].slice(-e5e))}seedRecentCompletedToolNamesFromHistory(e){let t=new Set;for(let n of e)for(let s of n.parts??[]){let o=s.functionResponse?.id;o&&t.add(o)}this.recentCompletedToolNames=[];for(let n of e)for(let s of n.parts??[]){let o=s.functionCall;o?.name&&(o.id&&!t.has(o.id)||this.rememberCompletedToolName(o.name))}}async microcompactHistoryBeforeSend(e,t){try{let n=Yd(this.getHistoryShallow(),e,this.config.getClearContextOnIdle(),t);if(!n.meta)return!1;let s=n.meta,o=s.tokensSaved>0;if(o&&(this.getChat().setHistory(n.history),await this.disarmFileReadCacheAfterEviction(s,"microcompaction")),s.triggerReason==="size"){let a=s.pendingToolResultChars&&s.pendingToolResultChars>0?` (+${s.pendingToolResultChars} pending)`:"";tt.info(`[TOOL-RESULT MC] tool result chars ${s.toolResultCharsBefore} > ${s.toolResultsTotalCharsThreshold}, cleared ${s.toolsCleared} tool result(s) (~${s.tokensSaved} tokens), history now ${s.toolResultCharsAfter}${a}, kept ${s.toolsKept} tool result(s)`)}else tt.info(`[TIME-BASED MC] gap ${s.gapMinutes}min > ${s.thresholdMinutes}min, cleared ${s.toolsCleared} tool result(s) + ${s.mediaCleared} media (~${s.tokensSaved} tokens), kept ${s.toolsKept} tool / ${s.mediaKept} media`);return o}catch(n){return tt.error(`[MICROCOMPACTION] microcompactHistory failed: ${n instanceof Error?n.message:String(n)}`),!1}}sendMessageStream(e,t,n,s,o=sj){let a=s?.type??"userQuery",l=r5e(a),u=!(G2()!==void 0)&&n5e(a)?this.reportedOperationTracker.begin(l):this.reportedOperationTracker.continue(l);return K2(u,this.sendMessageStreamInternal(e,t,n,s,o))}async*sendMessageStreamInternal(e,t,n,s,o=sj){let a=s?.type??"userQuery";a==="retry"&&this.stripOrphanedUserEntriesFromHistory();let l=!this.config.getDisableAllHooks(),c=this.config.getMessageBus();if(a!=="retry"&&a!=="cron"&&a!=="notification"&&a!=="teammate"&&l&&c&&this.config.hasHooksForEvent("UserPromptSubmit")){let d=$o(e),f=await c.request({type:"hook-execution-request",eventName:"UserPromptSubmit",input:{prompt:d}},"hook-execution-response"),p=f.output?ct("UserPromptSubmit",f.output):void 0;if(p?.isBlockingDecision()||p?.shouldStopExecution())return yield{type:"user_prompt_submit_blocked",value:{reason:p.getEffectiveReason(),originalPrompt:d}},new Bo(this.getChat(),n);let y=p?.getAdditionalContext();y&&(e=[...Array.isArray(e)?e:[e],{text:y}])}(a==="notification"||a==="teammate")&&this.config.getChatRecordingService()?.recordNotification(e,s?.notificationDisplayText);let u=a==="userQuery"||a==="cron"||a==="notification"||a==="teammate";if(u){this.loopDetector.reset(n),this.lastPromptId=n,t2(this.config,{promptId:n,model:s?.modelOverride??this.config.getModel(),messageType:a});let d=h2();d&&this.config.getTelemetryIncludeSensitiveSpanAttributes?.()&&Zj(this.config,d,$o(e))}let h=!1;try{if(a==="userQuery"||a==="cron"){if(this.config.getManagedAutoMemoryEnabled()){this.cancelPendingMemoryPrefetch();let H=new AbortController,G=()=>H.abort();t.aborted?H.abort():t.addEventListener("abort",G,{once:!0});let j=this.config.getMemoryManager().recall(this.config.getProjectRoot(),$o(e),{config:this.config,excludedFilePaths:this.surfacedRelevantAutoMemoryPaths,recentTools:[...this.recentCompletedToolNames],abortSignal:H.signal}).catch(W=>(W instanceof DOMException&&W.name==="AbortError"?tt.debug("Managed auto-memory recall prefetch aborted."):tt.warn("Managed auto-memory recall prefetch failed.",W),s5e)),q={promise:j,settledAt:null,consumed:!1,controller:H};j.finally(()=>{q.settledAt=Date.now(),t.removeEventListener("abort",G)}),this.pendingMemoryPrefetch=q}let D=ii.getInstance();a==="userQuery"&&D.incrementPromptCount(),a==="cron"?await this.config.getChatRecordingService()?.recordCronPrompt(e,s?.notificationDisplayText):await this.config.getChatRecordingService()?.recordUserMessage(e)}if(a==="userQuery"||a==="cron"){let D=await this.microcompactHistoryBeforeSend(this.lastApiCompletionTimestamp);(a==="userQuery"||D)&&(this.lastHookMicrocompactionTimestamp=Date.now())}else if(a==="hook"){this.lastHookMicrocompactionTimestamp??=this.lastApiCompletionTimestamp??Date.now();let D=this.lastHookMicrocompactionTimestamp;await this.microcompactHistoryBeforeSend(D)&&(this.lastHookMicrocompactionTimestamp=Date.now())}if(a!=="retry"){if(this.config.getChatRecordingService()?.recordAttributionSnapshot(ii.getInstance().toSnapshot()),this.sessionTurnCount++,a==="userQuery")try{await this.config.getFileHistoryService().makeSnapshot(n);try{let D=this.config.getFileHistoryService().getSnapshots().at(-1);D&&this.config.getChatRecordingService()?.recordFileHistorySnapshot(D)}catch(D){tt.error(`FileHistory: recordSnapshot failed: ${D}`)}}catch(D){tt.error(`FileHistory: makeSnapshot failed: ${D}`)}if(this.config.getMaxSessionTurns()>0&&this.sessionTurnCount>this.config.getMaxSessionTurns())return this.cancelPendingMemoryPrefetch(),yield{type:"max_session_turns"},u&&on("error",{errorMessage:"max session turns exceeded"}),new Bo(this.getChat(),n)}let d=Math.min(o,sj);if(!d)return this.cancelPendingMemoryPrefetch(),u&&on("error",{errorMessage:"max turns exhausted"}),new Bo(this.getChat(),n);let f=this.config.getSessionTokenLimit();if(f>0){let D=Gn.getLastPromptTokenCount();if(D>f)return this.cancelPendingMemoryPrefetch(),yield{type:"session_token_limit_exceeded",value:{currentTokens:D,limit:f,message:`Session token limit exceeded: ${D} tokens > ${f} limit. Please start a new session or increase the sessionTokenLimit in your settings.json.`}},u&&on("error",{errorMessage:"session token limit exceeded"}),new Bo(this.getChat(),n)}let p=this.getHistoryLength(),y=this.peekLastHistoryEntry(),w=!!y&&y.role==="model"&&(y.parts?.some(D=>"functionCall"in D)||!1),m,_,b=!1;if(this.config.getIdeMode()&&!w){let{contextParts:D,newIdeContext:H}=this.getIdeContextParts(this.forceFullIdeContext||p===0);D.length>0?(m=i5e(D.join(`
2191
+ `)),{contextParts:h,newIdeContext:t}}}runManagedAutoMemoryBackgroundTasks(e){if(e==="userQuery"||e==="toolResult"){let c=this.config.getProjectRoot(),u=this.config.getSessionId(),h=this.getHistoryShallow(),d=this.config.getMemoryManager(),f=this.config.getAutoSkillEnabled();if(f){let p=d.scheduleSkillReview({projectRoot:c,sessionId:u,history:h,config:this.config,toolCallCount:this.toolCallCount,skillsModified:this.skillsModifiedInSession,enabled:f,threshold:TR,maxTurns:ZB,timeoutMs:QB});p.status==="scheduled"?(this.toolCallCount=0,p.promise&&this.pendingMemoryTaskPromises.push(p.promise.then(y=>{let w=y.metadata?.touchedSkillFiles;return Array.isArray(w)?w.length:0}).catch(y=>(tt.warn("Failed to run managed skill review.",y),0)))):p.status==="skipped"&&p.skippedReason==="already_running"&&this.toolCallCount>=TR&&(this.toolCallCount=0),this.skillsModifiedInSession=!1}}if(e!=="userQuery")return;let t=this.config.getProjectRoot(),n=this.config.getSessionId(),s=this.getHistoryShallow(),o=this.config.getMemoryManager();if(!this.config.getManagedAutoMemoryEnabled())return;let a=o.scheduleExtract({projectRoot:t,sessionId:n,history:s,config:this.config}).then(c=>c.touchedTopics.length).catch(c=>(tt.warn("Failed to schedule managed auto-memory extraction.",c),0));this.pendingMemoryTaskPromises.push(a);let l=o.scheduleDream({projectRoot:t,sessionId:n,config:this.config}).then(c=>c.status==="scheduled"&&c.promise?c.promise.then(u=>{let h=u.metadata?.touchedTopics;return h?h.length:0}):0).catch(c=>(tt.warn("Failed to schedule managed auto-memory dream.",c),0));this.pendingMemoryTaskPromises.push(l)}consumePendingMemoryTaskPromises(){let e=this.pendingMemoryTaskPromises;return this.pendingMemoryTaskPromises=[],e}recordCompletedToolCall(e,t){if(this.rememberCompletedToolName(e),t&&o5e.has(e)){let n=t.file_path??t.path??t.target_file;typeof n=="string"&&Cd(n,this.config.getProjectRoot())&&(this.skillsModifiedInSession=!0)}this.toolCallCount+=1}rememberCompletedToolName(e){let t=e.trim();t&&(this.recentCompletedToolNames=[...this.recentCompletedToolNames.filter(n=>n!==t),t].slice(-e5e))}seedRecentCompletedToolNamesFromHistory(e){let t=new Set;for(let n of e)for(let s of n.parts??[]){let o=s.functionResponse?.id;o&&t.add(o)}this.recentCompletedToolNames=[];for(let n of e)for(let s of n.parts??[]){let o=s.functionCall;o?.name&&(o.id&&!t.has(o.id)||this.rememberCompletedToolName(o.name))}}async microcompactHistoryBeforeSend(e,t){try{let n=Yd(this.getHistoryShallow(),e,this.config.getClearContextOnIdle(),t);if(!n.meta)return!1;let s=n.meta,o=s.tokensSaved>0;if(o&&(this.getChat().setHistory(n.history),await this.disarmFileReadCacheAfterEviction(s,"microcompaction")),s.triggerReason==="size"){let a=s.pendingToolResultChars&&s.pendingToolResultChars>0?` (+${s.pendingToolResultChars} pending)`:"";tt.info(`[TOOL-RESULT MC] tool result chars ${s.toolResultCharsBefore} > ${s.toolResultsTotalCharsThreshold}, cleared ${s.toolsCleared} tool result(s) (~${s.tokensSaved} tokens), history now ${s.toolResultCharsAfter}${a}, kept ${s.toolsKept} tool result(s)`)}else tt.info(`[TIME-BASED MC] gap ${s.gapMinutes}min > ${s.thresholdMinutes}min, cleared ${s.toolsCleared} tool result(s) + ${s.mediaCleared} media (~${s.tokensSaved} tokens), kept ${s.toolsKept} tool / ${s.mediaKept} media`);return o}catch(n){return tt.error(`[MICROCOMPACTION] microcompactHistory failed: ${n instanceof Error?n.message:String(n)}`),!1}}sendMessageStream(e,t,n,s,o=sj){let a=s?.type??"userQuery",l=r5e(a),u=!(G2()!==void 0)&&n5e(a)?this.reportedOperationTracker.begin(l):this.reportedOperationTracker.continue(l);return K2(u,this.sendMessageStreamInternal(e,t,n,s,o))}async*sendMessageStreamInternal(e,t,n,s,o=sj){let a=s?.type??"userQuery";a==="retry"&&this.stripOrphanedUserEntriesFromHistory();let l=!this.config.getDisableAllHooks(),c=this.config.getMessageBus();if(a!=="retry"&&a!=="cron"&&a!=="notification"&&a!=="teammate"&&l&&c&&this.config.hasHooksForEvent("UserPromptSubmit")){let d=$o(e),f=await c.request({type:"hook-execution-request",eventName:"UserPromptSubmit",input:{prompt:d}},"hook-execution-response"),p=f.output?ct("UserPromptSubmit",f.output):void 0;if(p?.isBlockingDecision()||p?.shouldStopExecution())return yield{type:"user_prompt_submit_blocked",value:{reason:p.getEffectiveReason(),originalPrompt:d}},new Bo(this.getChat(),n);let y=p?.getAdditionalContext();y&&(e=[...Array.isArray(e)?e:[e],{text:y}])}if(a==="notification"||a==="teammate"){let d=this.config.getChatRecordingService();d&&await d.recordNotification(e,s?.notificationDisplayText)}let u=a==="userQuery"||a==="cron"||a==="notification"||a==="teammate";if(u){this.loopDetector.reset(n),this.lastPromptId=n,t2(this.config,{promptId:n,model:s?.modelOverride??this.config.getModel(),messageType:a});let d=h2();d&&this.config.getTelemetryIncludeSensitiveSpanAttributes?.()&&Zj(this.config,d,$o(e))}let h=!1;try{if(a==="userQuery"||a==="cron"){if(this.config.getManagedAutoMemoryEnabled()){this.cancelPendingMemoryPrefetch();let H=new AbortController,G=()=>H.abort();t.aborted?H.abort():t.addEventListener("abort",G,{once:!0});let j=this.config.getMemoryManager().recall(this.config.getProjectRoot(),$o(e),{config:this.config,excludedFilePaths:this.surfacedRelevantAutoMemoryPaths,recentTools:[...this.recentCompletedToolNames],abortSignal:H.signal}).catch(W=>(W instanceof DOMException&&W.name==="AbortError"?tt.debug("Managed auto-memory recall prefetch aborted."):tt.warn("Managed auto-memory recall prefetch failed.",W),s5e)),q={promise:j,settledAt:null,consumed:!1,controller:H};j.finally(()=>{q.settledAt=Date.now(),t.removeEventListener("abort",G)}),this.pendingMemoryPrefetch=q}let D=ii.getInstance();a==="userQuery"&&D.incrementPromptCount(),a==="cron"?await this.config.getChatRecordingService()?.recordCronPrompt(e,s?.notificationDisplayText):await this.config.getChatRecordingService()?.recordUserMessage(e)}if(a==="userQuery"||a==="cron"){let D=await this.microcompactHistoryBeforeSend(this.lastApiCompletionTimestamp);(a==="userQuery"||D)&&(this.lastHookMicrocompactionTimestamp=Date.now())}else if(a==="hook"){this.lastHookMicrocompactionTimestamp??=this.lastApiCompletionTimestamp??Date.now();let D=this.lastHookMicrocompactionTimestamp;await this.microcompactHistoryBeforeSend(D)&&(this.lastHookMicrocompactionTimestamp=Date.now())}if(a!=="retry"){if(this.config.getChatRecordingService()?.recordAttributionSnapshot(ii.getInstance().toSnapshot()),this.sessionTurnCount++,a==="userQuery")try{await this.config.getFileHistoryService().makeSnapshot(n);try{let D=this.config.getFileHistoryService().getSnapshots().at(-1);D&&this.config.getChatRecordingService()?.recordFileHistorySnapshot(D)}catch(D){tt.error(`FileHistory: recordSnapshot failed: ${D}`)}}catch(D){tt.error(`FileHistory: makeSnapshot failed: ${D}`)}if(this.config.getMaxSessionTurns()>0&&this.sessionTurnCount>this.config.getMaxSessionTurns())return this.cancelPendingMemoryPrefetch(),yield{type:"max_session_turns"},u&&on("error",{errorMessage:"max session turns exceeded"}),new Bo(this.getChat(),n)}let d=Math.min(o,sj);if(!d)return this.cancelPendingMemoryPrefetch(),u&&on("error",{errorMessage:"max turns exhausted"}),new Bo(this.getChat(),n);let f=this.config.getSessionTokenLimit();if(f>0){let D=Gn.getLastPromptTokenCount();if(D>f)return this.cancelPendingMemoryPrefetch(),yield{type:"session_token_limit_exceeded",value:{currentTokens:D,limit:f,message:`Session token limit exceeded: ${D} tokens > ${f} limit. Please start a new session or increase the sessionTokenLimit in your settings.json.`}},u&&on("error",{errorMessage:"session token limit exceeded"}),new Bo(this.getChat(),n)}let p=this.getHistoryLength(),y=this.peekLastHistoryEntry(),w=!!y&&y.role==="model"&&(y.parts?.some(D=>"functionCall"in D)||!1),m,_,b=!1;if(this.config.getIdeMode()&&!w){let{contextParts:D,newIdeContext:H}=this.getIdeContextParts(this.forceFullIdeContext||p===0);D.length>0?(m=i5e(D.join(`
2192
2192
  `)),_=H,b=!0):tt.debug("IDE mode enabled but no context parts generated (forceFull=%s)",this.forceFullIdeContext)}let v=this.config.getArenaAgentClient();if(v){let D=await v.checkControlSignal();if(D)return tt.info(`Arena control signal received: ${D.type} - ${D.reason}`),await v.reportCancelled(),this.cancelPendingMemoryPrefetch(),u&&on("cancelled"),new Bo(this.getChat(),n)}!w&&(a==="userQuery"||a==="cron")&&(this.drainPendingAddedMcpToolsReminder(),await this.drainSkillAndCommandReminders());let S=new Bo(this.getChat(),n),E=s?.modelOverride??this.config.getModel(),T=await lq(e,async D=>[D]);if(m&&(T=cq(T,m)),a==="userQuery"||a==="cron"){let D=[];if(a==="userQuery"){let j=aM();j!==this.lastInjectedDate&&(D.push(`<system-reminder>
2193
2193
  The current date is: ${j}. Note: This is the authoritative current date \u2014 it may differ from the "Today's date" mentioned earlier in the conversation startup context.
2194
2194
  </system-reminder>`),this.lastInjectedDate=j)}this.config.getApprovalMode()==="plan"&&D.push(Vv(this.config.getSdkMode()));let H=this.config.getArenaManager();if(H)try{let q=`${H.getArenaSessionDir()}/config.json`;D.push(oG(q))}catch{}let G=await this.tryConsumeMemoryPrefetch();G?.prompt&&D.unshift(G.prompt),T=[...D,...T]}if(a==="toolResult"){let D=await this.tryConsumeMemoryPrefetch();D?.prompt&&(T=[...T,D.prompt]),await this.microcompactHistoryBeforeSend(null,{sizeOnly:!0,pendingContent:xs(T)})}let A=$d(this.config.getSessionId());A&&(yield{type:"active_goal",value:A});let k=A,P=D=>{if(!EP(k,D))return k=D,{type:"active_goal",value:D??null}},U=S.run(E,T,t),F=!1;for await(let D of U){b&&!F&&(this.lastSentIdeContext=_,this.forceFullIdeContext=!1,F=!0);let H=this.config.getSkipLoopDetection(),G=!H&&this.loopDetector.addAndCheckDeterministicToolCallLoop(D),j=!G&&!H&&this.loopDetector.addAndCheckHeuristicLoops(D);if(G||j){let q=this.loopDetector.getLastLoopType();if(D.type==="tool_call_request"&&q==="consecutive_identical_tool_calls"){let W=this.loopDetector.getConsecutiveToolCallCount(),V=Math.max(0,S.pendingToolCalls.length-W);S.pendingToolCalls.splice(V)}return yield{type:"loop_detected",...q&&{value:{loopType:q}}},v&&await v.reportError("Loop detected"),this.lastApiCompletionTimestamp=Date.now(),u&&on("error",{errorMessage:"loop detected"}),this.cancelPendingMemoryPrefetch(),S}if(v&&D.type==="finished"&&await v.updateStatus(),D.type==="chat_compressed"&&D.value?.compressionStatus===1){this.forceFullIdeContext=!0;try{await this.restoreStartupContextAfterCompaction()}catch(q){this.config.getDebugLogger().warn(`Failed to restore startup context after compaction: ${q}`)}this.fireSessionStartHook("compact").then(q=>{!q||!this.chat||(this.lastSessionStartContext=q,this.lastSessionStartSource="compact",this.chat.applySessionStartContext(q,"compact"))}).catch(q=>{this.config.getDebugLogger().warn(`SessionStart hook failed: ${q}`)})}if(yield D,D.type==="error"){if(this.forceFullIdeContext=!0,v){let q=D.value instanceof Error?D.value.message:"Unknown error";await v.reportError(q)}if(this.lastApiCompletionTimestamp=Date.now(),u){let q=D.value instanceof Error?"[API error]":"unknown error";on("error",{errorMessage:q})}return this.cancelPendingMemoryPrefetch(),S}}if(this.lastApiCompletionTimestamp=Date.now(),l&&c&&!S.pendingToolCalls.length&&t&&!t.aborted&&this.config.hasHooksForEvent("Stop")){let D=this.getLastModelMessageText()||"[no response text]",H=await c.request({type:"hook-execution-request",eventName:"Stop",input:{stop_hook_active:!0,last_assistant_message:D},signal:t},"hook-execution-response"),G=$d(this.config.getSessionId());if(t.aborted){let V=P(G);return V&&(yield V),u&&on("cancelled"),S}let q=H.output?ct("Stop",H.output):void 0;if(q?.systemMessage&&(yield{type:"hook_system_message",value:q.systemMessage}),q?.isBlockingDecision()||q?.shouldStopExecution()){if(t.aborted){let Z=P(G);return Z&&(yield Z),u&&on("cancelled"),S}let V=q.getEffectiveReason(),x=(s?.stopHookState?.iterationCount??0)+1,I=[...s?.stopHookState?.reasons??[],V],L=this.config.getStopHookBlockingCap();if(x>=L){let Z=Uc("Stop",L);TP(this.config,this.config.getSessionId(),Z);let M=$d(this.config.getSessionId()),K=P(M);return K&&(yield K),yield{type:"hook_system_message",value:Z},tt.warn(Z),u&&on("ok"),S}let O=P(G);O&&(yield O),yield{type:"stop_hook_loop",value:{iterationCount:x,reasons:I,stopHookCount:H.stopHookCount??1}};let z=[{text:V}],ne=$d(this.config.getSessionId())?d:d-1,te=yield*this.sendMessageStream(z,t,n,{type:"hook",modelOverride:s?.modelOverride,stopHookState:{iterationCount:x,reasons:I}},ne);return u&&on(t.aborted?"cancelled":"ok"),h=!0,te}let W=P(G);W&&(yield W)}if(!S.pendingToolCalls.length&&t&&!t.aborted){try{let V=this.getChat(),I=this.getHistoryTailShallow(40,!0);zue(V.getGenerationConfig(),I,this.config.getModel())}catch{}let D=this.config.getApprovalMode(),H=fq(D)||D==="plan",G=this.getChat().getLastHistoryEntry?.(),j=rj(G),q=xR(G)||j||!!G&&kR(G);if(this.config.getSkipNextSpeakerCheck()&&!H&&!q)return this.runManagedAutoMemoryBackgroundTasks(a),v&&await v.reportCompleted(),u&&on("ok"),S;let W=await Ede(this.getChat(),this.config,t,n);if(v2(this.config,new F2(n,S.finishReason?.toString()||"",W?.next_speaker||"")),W?.next_speaker==="model"){let V=[{text:xR(G)?"Please continue with a user-visible response. Do not only think silently \u2014 summarize results or take the next concrete action.":j?"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(V,t,n,{...s,type:"hook"},d-1);return u&&on(t.aborted?"cancelled":"ok"),h=!0,x}this.runManagedAutoMemoryBackgroundTasks(a),v&&await v.reportCompleted()}return t?.aborted&&v&&await v.reportCancelled(),u&&on(t?.aborted?"cancelled":"ok"),h=!0,S}finally{h||this.cancelPendingMemoryPrefetch(),u&&on(t?.aborted?"cancelled":"error",{errorMessage:"unexpected exit"})}}async generateContent(e,t,n,s,o){let a=o??mT.getStore()??this.lastPromptId,l=s;try{let c=this.config.getUserMemory(),u=t.systemInstruction?Am(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 Nc(()=>(l=y,d.generateContent({model:y,config:h,contents:e},a)),{authType:f,extraRetryErrorCodes:p,persistentMode:Lc(),signal:n,heartbeatFn:_=>{nj.stderr.write(`[matilda-code] Waiting for API capacity... attempt ${_.attempt}, retry in ${Math.ceil(_.remainingMs/1e3)}s
2195
2195
  `)},onRetry:_=>{Tc(this.config,new Ac({model:l,promptId:a,attemptNumber:_.attempt,error:_.error,statusCode:_.errorStatus,retryDelayMs:_.delayMs,subagentName:Io.getStore()}))}})}catch(c){throw n.aborted?c:(await Bi(c,`Error generating content via API with model ${l}.`,{requestContents:e,requestConfig:t},"generateContent-api"),new Error(`Failed to generate content with model ${l}: ${re(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)),tt.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){tt.debug(`[FILE_READ_CACHE] clear after ${t} (${e.unresolvedEvictedReads} unresolved blanked read(s))`),n.clear();return}if(e.evictedReadPaths.length===0)return;let s=await Promise.all(e.evictedReadPaths.map(a=>Q8e.stat(a).catch(()=>{}))),o=!0;for(let a of s)(!a||!n.markReadEvictedFromHistory(a))&&(o=!1);o?tt.debug(`[FILE_READ_CACHE] disarmed fast-path for ${e.evictedReadPaths.length} file(s) after ${t}`):(tt.debug(`[FILE_READ_CACHE] clear after ${t} (an evicted path was unresolvable)`),n.clear())}async tryCompressChatFast(){let{info:e,microcompactMeta:t}=this.getChat().compressFast();return e.compressionStatus!==1||(t&&await this.disarmFileReadCacheAfterEviction(t,"compress-fast"),this.forceFullIdeContext=!0),e}};g();import*as Wp from"node:fs/promises";import*as Tde from"node:path";var Td=$("WORKTREE_CLEANUP"),a5e=[CN],l5e=30*24*60*60*1e3;function c5e(r){return a5e.some(e=>e.test(r))}async function kde(r,e={}){let t=e.cutoffMs??l5e,n=Date.now()-t,s=new as(r),o=s.getUserWorktreesDir();try{await Wp.access(o)}catch{return 0}let a;try{a=await Wp.readdir(o,{withFileTypes:!0})}catch(c){return c.code==="ENOENT"||Td.warn(`Failed to read ${o}: ${c}`),0}let l=0;for(let c of a){if(!c.isDirectory()||!c5e(c.name))continue;let u=Tde.join(o,c.name),h;try{h=(await Wp.stat(u)).mtimeMs}catch(y){y.code!=="ENOENT"&&Td.warn(`cleanupStaleAgentWorktrees: cannot stat ${u} \u2014 skipping: ${y}`);continue}if(h>=n)continue;let[d,f]=await Promise.all([u5e(u),s.hasUnmergedWorktreeCommits(c.name)]);if(d||f)continue;let p=await s.removeUserWorktree(c.name,{deleteBranch:!0});if(!p.success){Td.warn(`Failed to remove stale agent worktree ${u}: ${p.error}`);continue}p.branchPreserved?Td.warn(`Removed stale agent worktree ${u} but kept branch ${rw(c.name)} (unmerged commits at delete time)`):Td.debug(`Removed stale agent worktree ${u}`),l+=1}return l>0&&Td.debug(`cleanupStaleAgentWorktrees: removed ${l} stale worktree(s)`),l}async function u5e(r){try{return(await tn(r).raw(["status","--porcelain","--untracked-files=no"])).trim().length>0}catch(e){return Td.warn(`hasTrackedChanges: cannot inspect ${r} \u2014 assuming dirty: ${e}`),!0}}g();import*as Gp from"node:os";import{readFileSync as h5e}from"node:fs";import{EventEmitter as f5e}from"node:events";import{getHeapStatistics as Rde}from"node:v8";g();import*as Nb from"node:fs";import*as ij from"node:path";import*as Ade from"node:v8";var Lb=$("MEMORY_DUMP"),xde=3,d5e=3e4,RR=class{constructor(e){this.config=e}dumpCount=0;lastDumpTime=0;resetForNewSession(){this.dumpCount=0,this.lastDumpTime=0}async dump(e,t=[]){if(this.dumpCount>=xde){Lb.debug(`Skipping dump: session cap reached (${xde})`);return}let n=Date.now();if(n-this.lastDumpTime<d5e){Lb.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=ij.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:Ade.getHeapStatistics(),recentSamples:t,session:this.collectSessionStats(),suggestion:this.getSuggestion(e),collectionComplete:!1};Nb.writeFileSync(u,JSON.stringify(f,null,2),"utf8"),Lb.info(`Phase 1 diagnostics written to ${u} (trigger=${e}, dump #${s})`);let p=await Ice({sessionId:a,matildaVersion:this.config.getCliVersion()}),y={trigger:e,dumpNumber:s,...p,recentSamples:t,session:this.collectSessionStats(),suggestion:this.getSuggestion(e),collectionComplete:!0};return Nb.writeFileSync(u,JSON.stringify(y,null,2),"utf8"),Lb.info(`Phase 2 diagnostics written to ${u} (trigger=${e}, dump #${s})`),{filePath:u,trigger:e}}catch(o){Lb.error(`Failed to write memory diagnostics: ${re(o)}`);return}}ensureDiagnosticsDir(){let e=this.config.storage.getProjectDir(),t=ij.join(e,"diagnostics");return Nb.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 p5e=60,kd;function m5e(){if(kd===void 0){try{kd=Gp.availableParallelism?.()??Gp.cpus().length??1}catch{kd=1}(!kd||kd<1)&&(kd=1)}return kd}function oj(){try{return process.cpuUsage()}catch{return{user:0,system:0}}}var aj=class{samples=[];prevCpuUsage=oj();prevSampleTime=Date.now();record(e){let t=Date.now(),n=t-this.prevSampleTime,s=oj(),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/m5e()));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>p5e&&this.samples.shift(),e}getAll(){return[...this.samples]}reset(){this.samples.length=0,this.prevCpuUsage=oj(),this.prevSampleTime=Date.now()}},PR={softPressureRatio:.5,hardPressureRatio:.65,criticalRatio:.8,cleanupCooldownMs:5e3,enableExplicitGC:!0};function cj(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 lt=$("MEMORY_PRESSURE"),g5e=64*1024*1024,Ub=class extends f5e{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 aj;constructor(e,t){super(),this.coreConfig=e,this.config={...t??PR},cj(this.config),this.effectiveMemoryLimit=this.computeEffectiveMemoryLimit(),this.diagnosticsDumper=new RR(e);let n=Rde().heap_size_limit;lt.info(`Effective memory limit: ${$b(this.effectiveMemoryLimit)} MiB; V8 heap limit: ${$b(n)} MiB`),this.effectiveMemoryLimit<=0&&lt.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){lt.error(`Memory pressure check failed: ${re(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);Xj()&&(GR(this.coreConfig,l.rss,{memory_type:"rss"}),GR(this.coreConfig,l.heapUsed,{memory_type:"heap_used"}),Jj(this.coreConfig,l.cpuPercent,{}))}catch(l){let c=`Runtime sampling failed: ${re(l)}`;this.hasLoggedSamplingError?lt.debug(c):(this.hasLoggedSamplingError=!0,lt.error(c))}if(t==="normal")return;let n=this.recommendCleanup(t);if(n.action==="none")return;let s=Date.now(),o=Fb(n.action)>Fb(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){lt.error(`Failed to read memory usage for pressure check: ${re(e)}`);return}}getPressureLevel(e){let t=e??this.readMemoryUsage();if(!t)return"normal";let n=this.effectiveMemoryLimit>0?t.rss/this.effectiveMemoryLimit:0,s=Rde().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 lj(e)}}executeCleanup(e){if(this.cleanupInProgress){let s=Fb(e.action),o=Fb(this.activeCleanupAction),a=this.queuedCleanupRecommendation?Fb(this.queuedCleanupRecommendation.action):0;s>o&&s>a?(this.queuedCleanupRecommendation=e,lt.debug(`Queued escalated cleanup "${e.action}" while "${this.activeCleanupAction}" is in progress`)):lt.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){lt.error(`Cleanup measurement failed: ${re(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(lt.info(`Cleanup "${n.action}" completed; RSS delta ${s} bytes (${(o*100).toFixed(1)}%)`),o<.01){if(this.consecutiveIneffectiveCleanups++,n.action==="aggressive"&&this.consecutiveIneffectiveAggressiveCleanups++,Pde(this.consecutiveIneffectiveCleanups)){let a={rss:t,freedBytes:s,freedRatio:o,consecutiveIneffectiveCleanups:this.consecutiveIneffectiveCleanups,recommendation:n};lt.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=re(t),s=0;try{s=process.memoryUsage().rss}catch(o){lt.error(`Failed to read RSS after cleanup failure: ${re(o)}`)}this.consecutiveCleanupFailures++,lt.error(`Cleanup "${e.action}" failed: ${n}; consecutive failures: ${this.consecutiveCleanupFailures}`),Pde(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){lt.error(`${e} handler threw: ${re(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(),lt.debug("FileReadCache cleared");break}case"evict_cold_cache":{let t=this.coreConfig.getFileReadCache().evictNotAccessedSince(30);lt.debug(`FileReadCache cold eviction: ${t} entries`);break}case"evict_stale_cache":{let t=this.coreConfig.getFileReadCache().evictNotAccessedSince(60);lt.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;lt.debug(`global.gc() freed ${t-n} bytes`)}else lt.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?.()){lt.debug("[COMPACT_HISTORY] skipped: client not initialized");break}let n=t.getChat(),s=n.getHistoryShallow?.()??n.getHistory(),o=this.coreConfig.getClearContextOnIdle(),a=Yd(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;lt.debug(`[COMPACT_HISTORY] cleared ${l.toolsCleared} tool result(s) + ${l.mediaCleared} media (~${l.tokensSaved} tokens), kept ${l.toolsKept} tool / ${l.mediaKept} media`)}else lt.debug("[COMPACT_HISTORY] nothing to compact")}catch(t){lt.error(`[COMPACT_HISTORY] failed: ${re(t)}`)}break}default:return lj(e)}}computeEffectiveMemoryLimit(){let e=Gp.totalmem(),t=this.readCgroupMemoryLimit("/sys/fs/cgroup/memory.max",e);if(t!==void 0)return lt.info(`Using cgroup v2 memory limit: ${$b(t)} MiB`),t;let n=this.readCgroupMemoryLimit("/sys/fs/cgroup/memory/memory.limit_in_bytes",e);return n!==void 0?(lt.info(`Using cgroup v1 memory limit: ${$b(n)} MiB`),n):(lt.info(`Using host memory limit: ${$b(e)} MiB`),e)}readCgroupMemoryLimit(e,t){try{let n=h5e(e,"utf-8").trim();if(n==="max")return;if(!/^-?\d+$/.test(n)){lt.warn(`Ignoring non-numeric cgroup memory limit from ${e}: ${n}`);return}let s=Number(n);if(!Number.isFinite(s)||s<=0){lt.warn(`Ignoring out-of-range cgroup memory limit from ${e}: ${n}`);return}if(s<g5e){lt.warn(`Ignoring unrealistically small cgroup memory limit from ${e}: ${n}`);return}if(!Number.isSafeInteger(s)){lt.debug(`Ignoring unlimited cgroup memory limit from ${e}: ${n}`);return}if(t>0&&s>t){lt.debug(`Ignoring cgroup memory limit above host total from ${e}: ${n}`);return}return s}catch(n){lt.debug(`Failed to read cgroup memory limit from ${e}: `+re(n));return}}};function Fb(r){switch(r){case"aggressive":return 3;case"moderate":return 2;case"light":return 1;case"none":return 0;default:return lj(r)}}function Pde(r){return r===3||r===10||r>10&&r%20===0}function $b(r){return(r/1024/1024).toFixed(0)}function lj(r){throw new Error(`Unhandled memory pressure monitor value: ${String(r)}`)}g();var y5e=$("PROMPT_REGISTRY"),MR=class{prompts=new Map;registerPrompt(e){if(this.prompts.has(e.name)){let t=`${e.serverName}_${e.name}`;y5e.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 Mde}from"node:crypto";var w5e=$("GIT_CO_AUTHOR"),_5e=$("MEMORY_PRESSURE"),Ide=.15;var Rs=(o=>(o.PLAN="plan",o.DEFAULT="default",o.AUTO_EDIT="auto-edit",o.AUTO="auto",o.BOGAN="bogan",o))(Rs||{}),yH=Object.values(Rs).filter(r=>r!=="auto"),dj=class extends Error{constructor(e){super(e),this.name="TrustGateError"}},YVt={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"}},IR="Written by Matilda \u{1F1E6}\u{1F1FA} made by [Maincode](https://maincode.com)";function b5e(r){if(typeof r=="boolean")return{commit:r,pr:r,prMessage:IR};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)||w5e.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:IR;return{commit:e(r?.commit,"commit"),pr:e(r?.pr,"pr"),prMessage:n}}var v5e=25e3,S5e=1e3,C5e=2e5;function JVt(r){return r==="project"||r==="workspace"}var Ode=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 On(r){return r.type==="sdk"}var pK=(n=>(n.DYNAMIC_DISCOVERY="dynamic_discovery",n.GOOGLE_CREDENTIALS="google_credentials",n.SERVICE_ACCOUNT_IMPERSONATION="service_account_impersonation",n))(pK||{});function E5e(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 T5e(){let r={...PR};try{r.softPressureRatio=uj("MATILDA_MEMORY_PRESSURE_SOFT",r.softPressureRatio),r.hardPressureRatio=uj("MATILDA_MEMORY_PRESSURE_HARD",r.hardPressureRatio),r.criticalRatio=uj("MATILDA_MEMORY_PRESSURE_CRITICAL",r.criticalRatio);let e=Xt.env.MATILDA_MEMORY_ENABLE_GC;e&&["0","false","off","no"].includes(e.trim().toLowerCase())&&(r.enableExplicitGC=!1),cj(r)}catch(e){let t=`[MATILDA] WARNING: Invalid memory pressure config; using defaults. Error: ${re(e)}`;return Xt.stderr.write(`${t}
2196
- `),_5e.warn(t),{...PR}}return r}function uj(r,e){let t=Xt.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 k5e=[R.READ_FILE,R.EDIT,R.NOTEBOOK_EDIT,R.SHELL],x5e=Object.freeze(new Set),Dde=!1,Ep=class{sessionId;sessionData;pendingStartupWorktreeNotice=null;debugLogger;toolRegistry;pendingMcpBudgetCallback;promptRegistry;subagentManager;memoryPressureConfig;memoryPressureMonitor;backgroundTaskRegistry=new jA;monitorRegistry=new bT;backgroundAgentResumeService;backgroundShellRegistry=new vT;workflowRunRegistry=new ST;fileReadCache=new ky;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=Xm();accessibility;telemetrySettings;outboundCorrelationSettings;gitCoAuthor;usageStatisticsEnabled;fileReadCacheDisabled;geminiClient;baseLlmClient;cronScheduler=null;fileFiltering;fileDiscoveryService=null;sessionService=void 0;sessionStorageDir;sessionRuntimeBaseDir;sessionStorage;sessionStoragePinned;chatRecordingService=void 0;fileCheckpointingEnabled;toolResultBudget={bytesWritten:0};fileHistoryService;proxy;cwd;explicitIncludeDirectories;bugCommand;outputLanguageFilePath;noBrowser;folderTrustFeature;folderTrust;ideMode;maxSessionTurns;maxWallTimeSeconds;maxToolCalls;clearContextOnIdle;sessionTokenLimit;listExtensions;overrideExtensions;cliVersion;runtimeStatusEnabled=!1;experimentalZedIntegration=!1;cronEnabled=!0;agentTeamEnabled=!1;workflowsEnabled=!1;computerUseEnabled=!0;computerUseMaxImageDimension;emitToolUseSummaries=!0;chatRecordingEnabled;loadMemoryFromIncludeDirectories=!1;importFormat;chatCompression;interactive;trustedFolder;useRipgrep;useBuiltinRipgrep;shouldUseNodePtyShell;preventSystemSleep;skipNextSpeakerCheck;shellExecutionConfig;arenaManager=null;arenaManagerChangeCallback=null;arenaAgentClient;teamManager=null;teamManagerChangeCallbacks=new Set;teamContext=null;agentsSettings;worktreeSettings;skipLoopDetection;skipStartupContext;bareMode;warnings;allowedHttpHookUrls;onPersistPermissionRuleCallback;onRefreshPermissionsFromDiskCallback;initialized=!1;storage;sessionTransitionMutex=new Ha;runtimeStatusWrite=Promise.resolve();fileExclusions;truncateToolOutputThreshold;truncateToolOutputLines;toolOutputBatchBudget;eventEmitter;channel;jsonFd;jsonFile;jsonPartials;jsonSchema;inputFile;plansDir;plansDirectoryConfigured;defaultFileEncoding;enableManagedAutoMemory;enableManagedAutoDream;enableAutoSkill;fastModel;modelDisplayName;disableAllHooks;stopHookBlockingCap;userHooks;projectHooks;hooks;hookSystem;messageBus;memoryManager;modelChangeListeners=new Set;constructor(e){this.sessionId=e.sessionId??Mde(),!Dde&&Xt.env&&(Xt.env.MATILDA_CODE_SESSION_ID=this.sessionId,Dde=!0),this.sessionData=e.sessionData,zR(this),this.debugLogger=$(),this.embeddingModel=e.embeddingModel??wP,this.fileSystemService=new zE,this.sandbox=e.sandbox,this.targetDir=qr.resolve(e.targetDir),this.sessionStoragePinned=e.sessionStorageDir!==void 0,this.sessionStorageDir=qr.resolve(e.sessionStorageDir??this.targetDir),this.sessionRuntimeBaseDir=e.sessionRuntimeBaseDir?qr.resolve(e.sessionRuntimeBaseDir):void 0,this.plansDirectoryConfigured=!!e.plansDirectory?.trim(),this.plansDir=fe.getPlansDir(this.targetDir,e.plansDirectory),this.explicitIncludeDirectories=Array.from(new Set(e.includeDirectories??[])),this.workspaceContext=new Ia(this.targetDir,this.explicitIncludeDirectories),this.debugMode=e.debugMode,this.inputFormat=e.inputFormat??"text";let t=E5e(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??yP,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={...b5e(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??Xt.cwd(),this.fileDiscoveryService=e.fileDiscoveryService??null,this.bugCommand=e.bugCommand,this.maxSessionTurns=e.maxSessionTurns??-1,this.maxWallTimeSeconds=e.maxWallTimeSeconds??-1,this.maxToolCalls=e.maxToolCalls??-1;let n=e.clearContextOnIdle,s=n?.toolResultsThresholdMinutes??5;this.clearContextOnIdle={toolResultsThresholdMinutes:s,toolResultsNumToKeep:n?.toolResultsNumToKeep??5,toolResultsTotalCharsThreshold:n?.toolResultsTotalCharsThreshold??((n?.toolResultsThresholdMinutes??0)<0?-1:5e5)},this.sessionTokenLimit=e.sessionTokenLimit??-1,this.experimentalZedIntegration=e.experimentalZedIntegration??!1,this.cronEnabled=e.cronEnabled??!0,this.agentTeamEnabled=e.agentTeamEnabled??!1,this.workflowsEnabled=e.workflowsEnabled??!1,this.computerUseEnabled=e.computerUseEnabled??!0,this.computerUseMaxImageDimension=e.computerUseMaxImageDimension,this.emitToolUseSummaries=e.emitToolUseSummaries??!0,this.listExtensions=e.listExtensions??!1,this.overrideExtensions=e.overrideExtensions,this.noBrowser=e.noBrowser??!1,this.folderTrustFeature=e.folderTrustFeature??!1,this.folderTrust=e.folderTrust??!1,this.ideMode=e.ideMode??!1,this.modelProvidersConfig=e.modelProvidersConfig,this.cliVersion=e.cliVersion,this.chatRecordingEnabled=e.chatRecording??!0,this.loadMemoryFromIncludeDirectories=e.loadMemoryFromIncludeDirectories??!1,this.importFormat=e.importFormat??"tree",this.chatCompression=e.chatCompression,this.interactive=e.interactive??!1,this.trustedFolder=e.trustedFolder,this.skipLoopDetection=e.skipLoopDetection??!1,this.skipStartupContext=e.skipStartupContext??!1,this.bareMode=e.bareMode??!1,this.warnings=e.warnings??[],this.addLegacyPlanLocationWarning(),this.allowedHttpHookUrls=e.allowedHttpHookUrls??[],this.onPersistPermissionRuleCallback=e.onPersistPermissionRule,this.onRefreshPermissionsFromDiskCallback=e.onRefreshPermissionsFromDisk,this.useRipgrep=e.useRipgrep??!0,this.useBuiltinRipgrep=e.useBuiltinRipgrep??!0,this.shouldUseNodePtyShell=e.shouldUseNodePtyShell??V3(),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??v5e,this.truncateToolOutputLines=e.truncateToolOutputLines??S5e,this.toolOutputBatchBudget=e.toolOutputBatchBudget??C5e,this.channel=e.channel,this.jsonFd=e.jsonFd,this.jsonFile=e.jsonFile,this.jsonPartials=e.jsonPartials??!0,this.jsonSchema=e.jsonSchema,this.inputFile=e.inputFile,this.defaultFileEncoding=e.defaultFileEncoding,this.storage=new fe(this.targetDir),this.sessionStorage=new fe(this.sessionStorageDir,this.sessionRuntimeBaseDir),this.inputFormat=e.inputFormat??"text",this.fileExclusions=new Vj(this),this.eventEmitter=e.eventEmitter,this.arenaAgentClient=bv.create(),this.agentsSettings=e.agents??{},this.worktreeSettings=e.worktree??{},e.contextFileName&&Wj(e.contextFileName),this.modelsConfig=new iv({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&&m2(this);let o=this.getProxy();o&&(0,OR.setGlobalDispatcher)(new OR.ProxyAgent(o)),this.geminiClient=new AR(this),this.chatRecordingService=this.chatRecordingEnabled?new nh(this):void 0,this.extensionManager=new SA({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=n0(e.stopHookBlockingCap),this.userHooks=e.userHooks,this.projectHooks=e.projectHooks,this.hooks=e.hooks,this.memoryManager=new Db}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 MR,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 $p(this),await this.hookSystem.initialize(),this.debugLogger.debug("Hook system initialized"),this.messageBus=new wb,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?ct("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 G_(this),this.getBareMode()?await this.skillManager.refreshCache():await this.skillManager.startWatching(),this.debugLogger.debug("Skill manager initialized"),this.memoryPressureConfig=T5e(),this.memoryPressureMonitor=new Ub(this,this.memoryPressureConfig),this.permissionManager=new Ym(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=Xt.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),Kn("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 sz().getInstallationId(),YR(this,new oP(this)),this.debugLogger.info("Config initialization completed"),this.getBareMode()||(async()=>{try{let a=await new as(this.targetDir).getRepoTopLevel()??this.targetDir,l=qr.join(a,".matilda","worktrees");try{await Lde.access(l)}catch{this.debugLogger.debug(`Stale worktree sweep skipped: ${l} does not exist`);return}let c=await kde(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)||uE(n)!=="connected"&&t.push(n);return t}async refreshHierarchicalMemory(e="refresh"){let{memoryContent:t,fileCount:n,conditionalRules:s,projectRoot:o}=await aue(this.getWorkingDir(),this.getMemoryDiscoveryDirectories(),this.getFileService(),this.getExtensionContextFilePaths(),this.isTrustedFolder(),this.getImportFormat(),this.contextRuleExcludes,{explicitOnly:this.getBareMode(),loadReason:e,onInstructionsLoaded:gR(()=>this.hookSystem)});if(this.getManagedAutoMemoryEnabled()){let[a,l]=await Promise.all([h3(this.getProjectRoot()),p3().catch(()=>null)]);this.setUserMemory(this.memoryManager.appendToUserMemory(t,Mr(this.getProjectRoot()),a,{memoryDir:ei(),indexContent:l}))}else this.setUserMemory(t);this.setGeminiMdFileCount(n),this.conditionalRulesRegistry=new gb(s,o)}buildMemoryContextWarning(e){let t=this.getContentGeneratorConfig()?.contextWindowSize??this.modelsConfig.getGenerationConfig().contextWindowSize??Qp(this.getModel(),"input");if(!t||t<=0||!e)return;let n=Math.ceil(e.length/Xn),s=Math.floor(t*Ide);if(!(n<=s))return`Warning: Loaded MATILDA.md/context instructions use about ${n.toLocaleString()} tokens, more than ${Math.round(Ide*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 $m()?.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}=CP(this,e,this.modelsConfig.getGenerationConfig(),this.modelsConfig.getGenerationConfigSources(),{strictModelProvider:this.modelsConfig.isStrictModelProviderSelection()}),l=o;this.contentGenerator=await Fd(l,this,s?!0:t),this.contentGeneratorConfig=l,this.contentGeneratorConfigSources=a,this.baseLlmClient=new um(this.contentGenerator,this);let c=this.getMessageBus();!this.getDisableAllHooks()&&c&&Um(c,`Successfully authenticated with ${e}`,"auth_success","Authentication successful").catch(()=>{})}getBaseLlmClient(){if(!this.baseLlmClient)if(this.contentGenerator)this.baseLlmClient=new um(this.getContentGenerator(),this);else throw new Error("BaseLlmClient not initialized. Ensure authentication has occurred and ContentGenerator is ready.");return this.baseLlmClient}getSessionId(){return this.sessionId}getWarnings(){let e=this.buildMemoryContextWarning(this.getUserMemory());return e?[...this.warnings,e]:this.warnings}getDebugLogger(){return this.debugLogger}async startNewSession(e,t){return this.sessionTransitionMutex.runExclusive(async()=>{let n=this.chatRecordingService;try{n?.finalize()}catch{}await n?.releaseTranscriptOwnership();let s=this.sessionId;if(this.sessionId=e??Mde(),Xt.env&&(Xt.env.MATILDA_CODE_SESSION_ID=this.sessionId),this.sessionData=t,zR(this),this.debugLogger=$(),this.chatRecordingService=this.chatRecordingEnabled?new nh(this):void 0,this.getFileReadCache().clear(),this.toolResultBudget.bytesWritten=0,this.getMemoryPressureMonitor()?.resetForNewSession(),this.fileHistoryService=void 0,g2(this.sessionId),f2(),ii.resetInstance(),this.initialized&&YR(this,new oP(this)),this.runtimeStatusEnabled&&s!==this.sessionId){let o=this.sessionStorage.getRuntimeStatusPath(s),a=this.sessionStorage.getRuntimeStatusPath(this.sessionId),l=this.cliVersion??null,c=this.targetDir,u=this.sessionId;this.queueRuntimeStatusWrite(async()=>{await nW(o),await v0(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 v0(this.sessionStorage.getRuntimeStatusPath(this.sessionId),{sessionId:this.sessionId,workDir:e,matildaVersion:this.cliVersion??null})}),await this.flushRuntimeStatusWrites())}getResumedSessionData(){return this.sessionData}shouldLoadMemoryFromIncludeDirectories(){return this.loadMemoryFromIncludeDirectories}getImportFormat(){return this.importFormat}getContentGeneratorConfig(){return $m()?.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=ri(this.fastModel);return n?.authType?`${n.authType}:${e.modelId}`:e.modelId}resolveFastModelSelector(){if(this.fastModel)try{return ri(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}=CP(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=Xt.env.SEATBELT_PROFILE,n=Xt.env.SANDBOX,s=Xt.env.MATILDA_DESKTOP_SANDBOX_NONCE,o=Xt.env.MATILDA_DESKTOP_SANDBOX_ACTIVE;return(e?.command==="sandbox-exec"||n==="sandbox-exec")&&!!t&&t.startsWith("restrictive-")&&(!s||o===s)}getTargetDir(){return this.targetDir}getCurrentSessionArtifactMoves(e,t){let n=qr.join(e.getProjectDir(),"chats"),s=qr.join(t.getProjectDir(),"chats");return[`${this.sessionId}.jsonl`,`${this.sessionId}.runtime.json`,`${this.sessionId}.worktree.json`].map(o=>({from:qr.join(n,o),to:qr.join(s,o)}))}moveFile(e,t){try{_t.renameSync(e,t)}catch(n){if(n.code!=="EXDEV")throw n;let s=!1;try{_t.copyFileSync(e,t),s=!0,_t.unlinkSync(e)}catch(o){if(s)try{_t.unlinkSync(t)}catch{}throw o}}}moveCurrentSessionArtifacts(e,t){let n=[];for(let{from:s,to:o}of this.getCurrentSessionArtifactMoves(e,t))if(_t.existsSync(s)){_t.mkdirSync(qr.dirname(o),{recursive:!0});try{this.moveFile(s,o),n.push({from:s,to:o})}catch(a){for(let l of n.reverse())try{_t.mkdirSync(qr.dirname(l.from),{recursive:!0}),this.moveFile(l.to,l.from)}catch(c){this.debugLogger.warn("Failed to roll back moved session artifact",c)}throw a}}}async prepareSessionArtifactMigration(e,t,n){this.chatRecordingService?.finalize(),await this.chatRecordingService?.releaseTranscriptOwnership(),await this.flushRuntimeStatusWrites();try{this.moveCurrentSessionArtifacts(e,t)}catch(s){try{Xt.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=_t.realpathSync(Xt.cwd()),s=qr.resolve(e),o=t??_t.realpathSync(s);if(!_t.statSync(s).isDirectory())throw new Error(`Path is not a directory: ${s}`);let a=Ia.resolveRootDirectories(o,this.explicitIncludeDirectories);Xt.chdir(s);let l=_t.realpathSync(Xt.cwd());if(l!==o)throw Xt.chdir(n),new Error(`Changed directory to ${l}, expected ${o}.`);let c=this.sessionStorage,u=new fe(o);this.sessionStoragePinned||await this.prepareSessionArtifactMigration(c,u,n),this.targetDir=o,this.cwd=o,this.storage=u,this.sessionStoragePinned||(this.sessionStorage=u,this.sessionStorageDir=o,this.chatRecordingService?.resetStoragePaths(),this.sessionService=void 0),await this.refreshCurrentRuntimeStatus(o),this.workspaceContext.applyRootDirectories(a),this.fileDiscoveryService=null,this.fileHistoryService=void 0,this.getFileReadCache().clear();try{return await this.refreshHierarchicalMemory(),{}}catch(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?.releaseTranscriptOwnership()}catch{}this.skillManager?.stopWatching(),this.toolRegistry&&await this.toolRegistry.stop(),this.backgroundTaskRegistry.abortAll(),this.monitorRegistry.abortAll({notify:!1}),this.backgroundShellRegistry.abortAll(),await this.cleanupArenaRuntime(),await this.cleanupTeamRuntime()}catch(e){this.debugLogger.error("Error during Config shutdown:",e)}finally{p2()&&await y2()}}getPromptRegistry(){return this.promptRegistry}getDebugMode(){return this.debugMode}getQuestion(){return this.question}getSystemPrompt(){return this.systemPrompt}getAppendSystemPrompt(){return this.appendSystemPrompt}getCoreTools(){return this.getBareMode()?k5e: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?.()??x5e}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 dj("Cannot enable privileged approval modes in an untrusted folder.");e==="plan"&&this.approvalMode!=="plan"?(this.prePlanMode=this.approvalMode,this.planGateState=hq(++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=eI()),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 _t.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 qr.join(this.plansDir,`${fe.sanitizePlanSessionId(this.sessionId)}.md`)}savePlan(e){this.assertPlansDirWithinTargetDir();let t=this.getPlanFilePath(),n=qr.dirname(t);_t.mkdirSync(n,{recursive:!0});let s=t+".tmp";_t.writeFileSync(s,e,"utf-8");try{_t.renameSync(s,t)}catch(o){if(o.code!=="EXDEV")throw o;_t.copyFileSync(s,t),_t.unlinkSync(s)}try{this.assertPlanFilePathWithinTargetDir(t)}catch(o){try{_t.unlinkSync(t)}catch{}throw o}}loadPlan(){this.assertPlansDirWithinTargetDir();let e=this.getPlanFilePath();this.assertPlanFilePathWithinTargetDir(e);try{return _t.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??J2}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??yP}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 Ub(this,this.memoryPressureConfig)}return this.memoryPressureMonitor}getCronScheduler(){return this.cronScheduler||(this.cronScheduler=new bE(this.getProjectRoot())),this.cronScheduler}isCronEnabled(){return Xt.env.MATILDA_CODE_DISABLE_CRON==="1"?!1:this.cronEnabled}isAgentTeamEnabled(){return Xt.env.MATILDA_CODE_ENABLE_AGENT_TEAM==="1"?!0:this.agentTeamEnabled}isWorkflowsEnabled(){return Xt.env.MATILDA_CODE_DISABLE_WORKFLOWS==="1"?!1:Xt.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=Xt.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 Mv(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 cue(this.proxy)}getWorkingDir(){return this.cwd}getBugCommand(){return this.bugCommand}getFileService(){return this.fileDiscoveryService||(this.fileDiscoveryService=new Tl(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()||!ez()}getIdeMode(){return this.ideMode}getFolderTrustFeature(){return this.folderTrustFeature}getFolderTrust(){return this.folderTrust}getAllowedHttpHookUrls(){return this.getBareMode()?[]:this.allowedHttpHookUrls}isTrustedFolder(){let e=Nu.get();return e?.workspaceState?.isTrusted!==void 0?e.workspaceState.isTrusted:this.trustedFolder??!0}setIdeMode(e){this.ideMode=e}getAuthType(){return this.getContentGeneratorConfig()?.authType}getCliVersion(){return this.cliVersion}getChannel(){return this.channel}getJsonFd(){return this.jsonFd}getJsonFile(){return this.jsonFile}getJsonPartials(){return this.jsonPartials}getJsonSchema(){return this.jsonSchema}getInputFile(){return this.inputFile}getDefaultFileEncoding(){return this.defaultFileEncoding}getFileSystemService(){return this.fileSystemService}setFileSystemService(e){this.fileSystemService=e}getChatCompression(){return this.chatCompression}isInteractive(){return this.interactive}getUseRipgrep(){return this.useRipgrep}getUseBuiltinRipgrep(){return this.useBuiltinRipgrep}getShouldUseNodePtyShell(){return this.shouldUseNodePtyShell}getSkipNextSpeakerCheck(){return this.skipNextSpeakerCheck}getShellExecutionConfig(){return this.shellExecutionConfig}setShellExecutionConfig(e){this.shellExecutionConfig={terminalWidth:e.terminalWidth??this.shellExecutionConfig.terminalWidth,terminalHeight:e.terminalHeight??this.shellExecutionConfig.terminalHeight,showColor:e.showColor??this.shellExecutionConfig.showColor,pager:e.pager??this.shellExecutionConfig.pager,maxBufferedOutputBytes:e.maxBufferedOutputBytes??this.shellExecutionConfig.maxBufferedOutputBytes}}getScreenReader(){return this.accessibility.screenReader??!1}getSkipLoopDetection(){return this.skipLoopDetection}getSkipStartupContext(){return this.skipStartupContext}getBareMode(){return this.bareMode}getTruncateToolOutputThreshold(){return this.truncateToolOutputThreshold<=0?Number.POSITIVE_INFINITY:this.truncateToolOutputThreshold}getTruncateToolOutputLines(){return this.truncateToolOutputLines<=0?Number.POSITIVE_INFINITY:this.truncateToolOutputLines}getToolOutputBatchBudget(){return this.toolOutputBatchBudget<=0?Number.POSITIVE_INFINITY:this.toolOutputBatchBudget}trackToolResultBytes(e){this.toolResultBudget.bytesWritten+=e}getToolResultBytesWritten(){return this.toolResultBudget.bytesWritten}getOutputFormat(){return this.outputFormat}getChatRecordingService(){if(this.chatRecordingEnabled)return this.chatRecordingService||(this.chatRecordingService=new nh(this)),this.chatRecordingService}getTranscriptPath(){if(!this.chatRecordingEnabled)return"";let e=this.sessionStorage.getProjectDir(),n=`${this.getSessionId()}.jsonl`;return qr.join(e,"chats",n)}getSessionService(){return this.sessionService||(this.sessionService=new Fv(this.sessionStorageDir,this.sessionRuntimeBaseDir)),this.sessionService}getFileExclusions(){return this.fileExclusions}getSubagentManager(){return this.subagentManager}getBackgroundTaskRegistry(){return this.backgroundTaskRegistry}getMonitorRegistry(){return this.monitorRegistry}getBackgroundAgentResumeService(){return this.backgroundAgentResumeService||(this.backgroundAgentResumeService=new qA(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 ky),this.fileReadCache}getFileReadCacheDisabled(){return this.fileReadCacheDisabled}getShouldAvoidPermissionPrompts(){return!1}getSkillManager(){return this.skillManager}setModelInvocableCommandsProvider(e){this.modelInvocableCommandsProvider=e}getModelInvocableCommandsProvider(){return this.modelInvocableCommandsProvider}setModelInvocableCommandsExecutor(e){this.modelInvocableCommandsExecutor=e}getModelInvocableCommandsExecutor(){return this.modelInvocableCommandsExecutor}addInlineAnnouncedSkillKeys(e){for(let t of e)this.pendingInlineAnnouncedSkillKeys.add(t)}consumeInlineAnnouncedSkillKeys(){let e=this.pendingInlineAnnouncedSkillKeys;return this.pendingInlineAnnouncedSkillKeys=new Set,e}getPermissionManager(){return this.permissionManager}getOnPersistPermissionRule(){return this.onPersistPermissionRuleCallback}getOnRefreshPermissionsFromDisk(){return this.onRefreshPermissionsFromDiskCallback}async createToolRegistry(e,t){let n=new hE(this,this.eventEmitter,e),s=async(a,l)=>{let c=!0;try{c=this.permissionManager?await this.permissionManager.isToolEnabled(a):!0}catch(u){this.debugLogger.warn(`Failed to check permissions for tool "${a}", skipping registration:`,u);return}c&&n.registerFactory(a,l)},o=async()=>{if(!this.jsonSchema||t?.forSubAgent)return;let a=this.jsonSchema;await s(R.STRUCTURED_OUTPUT,async()=>{let{SyntheticOutputTool:l}=await import("./syntheticOutput-QEUQIVQJ.js");return new l(a)})};if(this.getBareMode())return await s(R.READ_FILE,async()=>{let{ReadFileTool:a}=await import("./read-file-J5UBJYDO.js");return new a(this)}),await s(R.EDIT,async()=>{let{EditTool:a}=await import("./edit-ZLVT3HLS.js");return new a(this)}),await s(R.NOTEBOOK_EDIT,async()=>{let{NotebookEditTool:a}=await import("./notebook-edit-UBSCMF55.js");return new a(this)}),await s(R.SHELL,async()=>{let{ShellTool:a}=await import("./shell-JDSST5O4.js");return new a(this)}),await o(),this.debugLogger.debug(`ToolRegistry created: ${JSON.stringify(n.getAllToolNames())} (${n.getAllToolNames().length} tools)`),n;if(await s(R.TOOL_SEARCH,async()=>{let{ToolSearchTool:a}=await import("./tool-search-OWJC3UTX.js");return new a(this)}),await s(R.AGENT,async()=>{let{AgentTool:a}=await import("./agent-KYTWNT5B.js");return new a(this)}),await s(R.TASK_STOP,async()=>{let{TaskStopTool:a}=await import("./task-stop-JO3CXG2K.js");return new a(this)}),await s(R.SEND_MESSAGE,async()=>{let{SendMessageTool:a}=await import("./send-message-XXRROIL7.js");return new a(this)}),await s(R.SKILL,async()=>{let{SkillTool:a}=await import("./skill-GLBTH3Q4.js");return new a(this)}),await s(R.LS,async()=>{let{LSTool:a}=await import("./ls-CLDNF3YS.js");return new a(this)}),await s(R.READ_FILE,async()=>{let{ReadFileTool:a}=await import("./read-file-J5UBJYDO.js");return new a(this)}),this.getUseRipgrep()){let a=!1,l;try{a=await OK(this.getUseBuiltinRipgrep())}catch(c){l=re(c)}a?await s(R.GREP,async()=>{let{RipGrepTool:c}=await import("./ripGrep-RTSNQ27E.js");return new c(this)}):(_2(this,new L2(this.getUseRipgrep(),this.getUseBuiltinRipgrep(),l||"ripgrep is not available")),await s(R.GREP,async()=>{let{GrepTool:c}=await import("./grep-YXF7LG25.js");return new c(this)}))}else await s(R.GREP,async()=>{let{GrepTool:a}=await import("./grep-YXF7LG25.js");return new a(this)});if(await s(R.GLOB,async()=>{let{GlobTool:a}=await import("./glob-JGVGPH7O.js");return new a(this)}),await s(R.EDIT,async()=>{let{EditTool:a}=await import("./edit-ZLVT3HLS.js");return new a(this)}),await s(R.NOTEBOOK_EDIT,async()=>{let{NotebookEditTool:a}=await import("./notebook-edit-UBSCMF55.js");return new a(this)}),await s(R.WRITE_FILE,async()=>{let{WriteFileTool:a}=await import("./write-file-FMBJAKLZ.js");return new a(this)}),await s(R.SHELL,async()=>{let{ShellTool:a}=await import("./shell-JDSST5O4.js");return new a(this)}),await s(R.TODO_WRITE,async()=>{let{TodoWriteTool:a}=await import("./todoWrite-7BZMVNBC.js");return new a(this)}),await s(R.UPDATE_GOAL,async()=>{let{UpdateGoalTool:a}=await import("./update-goal-CF6G57J7.js");return new a(this)}),await s(R.ASK_USER_QUESTION,async()=>{let{AskUserQuestionTool:a}=await import("./askUserQuestion-MJ4FTAOQ.js");return new a(this)}),this.sdkMode||(await s(R.EXIT_PLAN_MODE,async()=>{let{ExitPlanModeTool:a}=await import("./exitPlanMode-3DSR3TTH.js");return new a(this)}),await s(R.ENTER_PLAN_MODE,async()=>{let{EnterPlanModeTool:a}=await import("./enterPlanMode-H6P74G54.js");return new a(this)})),await s(R.ENTER_WORKTREE,async()=>{let{EnterWorktreeTool:a}=await import("./enter-worktree-TZ4BHFV3.js");return new a(this)}),await s(R.EXIT_WORKTREE,async()=>{let{ExitWorktreeTool:a}=await import("./exit-worktree-TRFH3EKK.js");return new a(this)}),await s(R.WEB_FETCH,async()=>{let{WebFetchTool:a}=await import("./web-fetch-K575OWZ7.js");return new a(this)}),await s(R.WEB_SEARCH,async()=>{let{WebSearchTool:a}=await import("./web-search-F6JRBXFV.js");return new a(this)}),await s(R.SYMBOL_SEARCH,async()=>{let{SymbolSearchTool:a}=await import("./symbol-search-3MVTK4KV.js");return new a(this)}),this.isLspEnabled()&&this.getLspClient()&&await s(R.LSP,async()=>{let{LspTool:a}=await import("./lsp-7SKRKR5Q.js");return new a(this)}),await o(),this.isCronEnabled()&&(await s(R.CRON_CREATE,async()=>{let{CronCreateTool:a}=await import("./cron-create-BTTPO3JC.js");return new a(this)}),await s(R.CRON_LIST,async()=>{let{CronListTool:a}=await import("./cron-list-J4HRR46K.js");return new a(this)}),await s(R.CRON_DELETE,async()=>{let{CronDeleteTool:a}=await import("./cron-delete-U55RHRID.js");return new a(this)})),this.isAgentTeamEnabled()&&(await s(R.TEAM_CREATE,async()=>{let{TeamCreateTool:a}=await import("./team-create-TQHT5HCX.js");return new a(this)}),await s(R.TEAM_DELETE,async()=>{let{TeamDeleteTool:a}=await import("./team-delete-4YYLUV23.js");return new a(this)}),await s(R.TASK_CREATE,async()=>{let{TaskCreateTool:a}=await import("./task-create-AEJQ73GE.js");return new a(this)}),await s(R.TASK_UPDATE,async()=>{let{TaskUpdateTool:a}=await import("./task-update-3YY37VFN.js");return new a(this)}),await s(R.TASK_LIST,async()=>{let{TaskListTool:a}=await import("./task-list-ZEJTNZ2O.js");return new a(this)})),this.isWorkflowsEnabled()&&await s(R.WORKFLOW,async()=>{let{WorkflowTool:a}=await import("./workflow-WMRTYTZE.js");return new a(this)}),this.isComputerUseEnabled()){let{registerComputerUseTools:a}=await import("./computer-use-PHYIWQFA.js");await a(s,this)}if(await s(R.MONITOR,async()=>{let{MonitorTool:a}=await import("./monitor-DBD44UCH.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 A5e="refs/notes/ai-attribution";function Nde(r,e){let t=JSON.stringify(r);return Buffer.byteLength(t,"utf-8")>30720?null:{command:"git",args:["notes",`--ref=${A5e}`,"add","-f","-m",t,e]}}var uhe=Ve(rl(),1);g();import*as Fde from"node:fs";var Hb=class extends Error{constructor(t,n){super(t);this.errorType=n;Object.setPrototypeOf(this,new.target.prototype)}name="StructuredToolError"};function DR(r){return r instanceof Hb||typeof r=="object"&&r!==null&&r.name==="StructuredToolError"&&"errorType"in r}async function $de(r,e,t,n={}){let s;try{s=await Fde.promises.stat(e)}catch(d){let f=d?.code;if(f==="ENOENT"){if(n.expectExisting){let w=`File ${e} disappeared after the model read it (stat now returns ENOENT). Re-read with the ${R.READ_FILE} tool \u2014 the path may have been deleted or moved \u2014 before retrying ${t} it.`;return{ok:!1,type:"file_changed_since_read",rawMessage:w,displayMessage:`file disappeared after last read; re-run ${R.READ_FILE} first.`}}return{ok:!0}}let p=`Could not stat ${e} to verify prior read (${f??"unknown error"}). Re-read with the ${R.READ_FILE} tool, then retry ${t} it.`,y=t==="editing"?"editing this file":"overwriting this file";return{ok:!1,type:"prior_read_verification_failed",rawMessage:p,displayMessage:`cannot verify prior read of ${e}; re-run ${R.READ_FILE} before ${y}.`}}if(s.isDirectory()){let d=t==="editing"?"edit":"overwrite",f=`${e} is a directory. The Edit / WriteFile tools only operate on regular files. Use a different mechanism (e.g. the shell tool) if you need to ${d} the contents of this directory.`;return{ok:!1,type:"target_is_directory",rawMessage:f,displayMessage:`path is a directory; cannot ${d} via this tool.`}}if(!s.isFile()){let d=t==="editing"?"edit":"overwrite",f=`${e} is a FIFO / socket / character or block device. The Edit / WriteFile tools only operate on regular files; the ${R.READ_FILE} tool also rejects these targets. Use a different mechanism (e.g. shell tool with the appropriate command) if you need to ${d} this path.`;return{ok:!1,type:"edit_requires_prior_read",rawMessage:f,displayMessage:`special file; cannot ${d} via this tool.`}}let o=r.check(s);if(o.state==="fresh"&&o.entry.lastReadAt!==void 0&&o.entry.lastReadCacheable)return{ok:!0};if(o.state==="stale"){let d=`File ${e} has been modified since you last read it (mtime or size changed). Re-read it with the ${R.READ_FILE} tool before ${t} it to ensure your changes are based on current content.`;return{ok:!1,type:"file_changed_since_read",rawMessage:d,displayMessage:`file changed since last read; re-run ${R.READ_FILE} first.`}}if(o.state==="fresh"&&o.entry.lastReadAt!==void 0&&!o.entry.lastReadCacheable){let d=t==="editing"?"edit":"overwrite",f=`File ${e} is a binary / image / audio / video / PDF / notebook payload that the ${R.READ_FILE} tool returns as a structured value rather than as plain text. The Edit / WriteFile tools cannot mutate that payload safely \u2014 re-reading it would not change this. If this is a Jupyter notebook (.ipynb), use the ${R.NOTEBOOK_EDIT} tool for cell-level edits after reading it. For other non-text files, use a different mechanism (e.g. shell tool with an appropriate writer) if you need to ${d} it.`;return{ok:!1,type:"edit_requires_prior_read",rawMessage:f,displayMessage:`non-text payload; cannot ${d} via this tool.`}}let a=t==="editing"?"edit":"overwrite",l=t==="editing"?"editing this file":"overwriting this file";if(t==="editing"&&n.autoStampUnread!==!1)return r.recordRead(e,s,{full:!0,cacheable:!0}),{ok:!0};let u=t==="editing"?`(a partial read with offset / limit is fine \u2014 you only need to have seen the bytes you intend to ${a})`:"(read the full file \u2014 overwriting replaces every byte, so any unseen bytes would be discarded)",h=`File ${e} has not been read in this session. Use the ${R.READ_FILE} tool first to load the current content ${u} before ${t} it.`;return{ok:!1,type:"edit_requires_prior_read",rawMessage:h,displayMessage:`${R.READ_FILE} required before ${l}.`}}g();var jde=Ve(rl(),1);var Ude=new Set(["+","?","|","(",")","{","}"]),R5e=new Set(["*","+","?"]);function zde(r){let e=r.trim(),t=e.match(/^\s*sed\s+/);if(!t)return null;let n;try{n=(0,jde.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(P5e(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||M5e(l)||c.startsWith("~")||c.includes("$"))return null;let h=$5e(l);if(h===null)return null;let d={filePath:c,...h,extendedRegex:a};return I5e(d)?d:null}function P5e(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 M5e(r){return r.includes("`")||/\$(?:[A-Za-z_][A-Za-z0-9_]*|\{|\(|\d|[#?@$!*])/u.test(r)}function I5e(r){try{let e=Gde(r);return O5e(e)||D5e(e)||(new RegExp(e),L5e(r.replacement,N5e(e)))?!1:!F5e(e)}catch{return!1}}function O5e(r){return/\[\[:[A-Za-z]+:\]\]/u.test(r)}function D5e(r){return/\\[<>dDwWsS]/u.test(r)}function L5e(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 N5e(r){let e=0;for(let t=0;t<r.length;t++){let n=r[t];if(n==="\\"){t++;continue}if(n==="["){t=qde(r,t);continue}n==="("&&r[t+1]!=="?"&&e++}return e}function F5e(r){let e=[];for(let t=0;t<r.length;t++){let n=r[t];if(n==="\\"){t++;continue}if(n==="["){t=qde(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=Hde(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=Hde(r,t);s!==null&&(e.length>0&&(e[e.length-1].hasQuantifier=!0),t=s-1)}return!1}function qde(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 Hde(r,e){let t=r[e];if(t===void 0)return null;if(R5e.has(t))return e+1;if(t!=="{")return null;let n=e+1,s=!1;for(;Bde(r[n]);)s=!0,n++;if(!s)return null;if(r[n]===",")for(n++;Bde(r[n]);)n++;return r[n]==="}"?n+1:null}function Bde(r){return r!==void 0&&r>="0"&&r<="9"}function $5e(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"||!U5e(s)||H5e(n)?null:{pattern:t,replacement:n,flags:s}}function U5e(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 H5e(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 Wde(r,e){if(r.length===0)return"";let t=Gde(e),n=j5e(e.flags),s=e.flags.includes("g");try{let o=new RegExp(t,"g"),a=r.split(/(\n)/);return(r.endsWith(`
2196
+ `),_5e.warn(t),{...PR}}return r}function uj(r,e){let t=Xt.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 k5e=[R.READ_FILE,R.EDIT,R.NOTEBOOK_EDIT,R.SHELL],x5e=Object.freeze(new Set),Dde=!1,Ep=class{sessionId;sessionData;pendingStartupWorktreeNotice=null;debugLogger;toolRegistry;pendingMcpBudgetCallback;promptRegistry;subagentManager;memoryPressureConfig;memoryPressureMonitor;backgroundTaskRegistry=new jA;monitorRegistry=new bT;backgroundAgentResumeService;backgroundShellRegistry=new vT;workflowRunRegistry=new ST;fileReadCache=new ky;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=Xm();accessibility;telemetrySettings;outboundCorrelationSettings;gitCoAuthor;usageStatisticsEnabled;fileReadCacheDisabled;geminiClient;baseLlmClient;cronScheduler=null;fileFiltering;fileDiscoveryService=null;sessionService=void 0;sessionStorageDir;sessionRuntimeBaseDir;sessionStorage;sessionStoragePinned;chatRecordingService=void 0;fileCheckpointingEnabled;toolResultBudget={bytesWritten:0};fileHistoryService;proxy;cwd;explicitIncludeDirectories;bugCommand;outputLanguageFilePath;noBrowser;folderTrustFeature;folderTrust;ideMode;maxSessionTurns;maxWallTimeSeconds;maxToolCalls;clearContextOnIdle;sessionTokenLimit;listExtensions;overrideExtensions;cliVersion;runtimeStatusEnabled=!1;experimentalZedIntegration=!1;cronEnabled=!0;agentTeamEnabled=!1;workflowsEnabled=!1;computerUseEnabled=!0;computerUseMaxImageDimension;emitToolUseSummaries=!0;chatRecordingEnabled;loadMemoryFromIncludeDirectories=!1;importFormat;chatCompression;interactive;trustedFolder;useRipgrep;useBuiltinRipgrep;shouldUseNodePtyShell;preventSystemSleep;skipNextSpeakerCheck;shellExecutionConfig;arenaManager=null;arenaManagerChangeCallback=null;arenaAgentClient;teamManager=null;teamManagerChangeCallbacks=new Set;teamContext=null;agentsSettings;worktreeSettings;skipLoopDetection;skipStartupContext;bareMode;warnings;allowedHttpHookUrls;onPersistPermissionRuleCallback;onRefreshPermissionsFromDiskCallback;initialized=!1;storage;sessionTransitionMutex=new Ha;runtimeStatusWrite=Promise.resolve();fileExclusions;truncateToolOutputThreshold;truncateToolOutputLines;toolOutputBatchBudget;eventEmitter;channel;jsonFd;jsonFile;jsonPartials;jsonSchema;inputFile;plansDir;plansDirectoryConfigured;defaultFileEncoding;enableManagedAutoMemory;enableManagedAutoDream;enableAutoSkill;fastModel;modelDisplayName;disableAllHooks;stopHookBlockingCap;userHooks;projectHooks;hooks;hookSystem;messageBus;memoryManager;modelChangeListeners=new Set;constructor(e){this.sessionId=e.sessionId??Mde(),!Dde&&Xt.env&&(Xt.env.MATILDA_CODE_SESSION_ID=this.sessionId,Dde=!0),this.sessionData=e.sessionData,zR(this),this.debugLogger=$(),this.embeddingModel=e.embeddingModel??wP,this.fileSystemService=new zE,this.sandbox=e.sandbox,this.targetDir=qr.resolve(e.targetDir),this.sessionStoragePinned=e.sessionStorageDir!==void 0,this.sessionStorageDir=qr.resolve(e.sessionStorageDir??this.targetDir),this.sessionRuntimeBaseDir=e.sessionRuntimeBaseDir?qr.resolve(e.sessionRuntimeBaseDir):void 0,this.plansDirectoryConfigured=!!e.plansDirectory?.trim(),this.plansDir=fe.getPlansDir(this.targetDir,e.plansDirectory),this.explicitIncludeDirectories=Array.from(new Set(e.includeDirectories??[])),this.workspaceContext=new Ia(this.targetDir,this.explicitIncludeDirectories),this.debugMode=e.debugMode,this.inputFormat=e.inputFormat??"text";let t=E5e(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??yP,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={...b5e(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??Xt.cwd(),this.fileDiscoveryService=e.fileDiscoveryService??null,this.bugCommand=e.bugCommand,this.maxSessionTurns=e.maxSessionTurns??-1,this.maxWallTimeSeconds=e.maxWallTimeSeconds??-1,this.maxToolCalls=e.maxToolCalls??-1;let n=e.clearContextOnIdle,s=n?.toolResultsThresholdMinutes??5;this.clearContextOnIdle={toolResultsThresholdMinutes:s,toolResultsNumToKeep:n?.toolResultsNumToKeep??5,toolResultsTotalCharsThreshold:n?.toolResultsTotalCharsThreshold??((n?.toolResultsThresholdMinutes??0)<0?-1:5e5)},this.sessionTokenLimit=e.sessionTokenLimit??-1,this.experimentalZedIntegration=e.experimentalZedIntegration??!1,this.cronEnabled=e.cronEnabled??!0,this.agentTeamEnabled=e.agentTeamEnabled??!1,this.workflowsEnabled=e.workflowsEnabled??!1,this.computerUseEnabled=e.computerUseEnabled??!0,this.computerUseMaxImageDimension=e.computerUseMaxImageDimension,this.emitToolUseSummaries=e.emitToolUseSummaries??!0,this.listExtensions=e.listExtensions??!1,this.overrideExtensions=e.overrideExtensions,this.noBrowser=e.noBrowser??!1,this.folderTrustFeature=e.folderTrustFeature??!1,this.folderTrust=e.folderTrust??!1,this.ideMode=e.ideMode??!1,this.modelProvidersConfig=e.modelProvidersConfig,this.cliVersion=e.cliVersion,this.chatRecordingEnabled=e.chatRecording??!0,this.loadMemoryFromIncludeDirectories=e.loadMemoryFromIncludeDirectories??!1,this.importFormat=e.importFormat??"tree",this.chatCompression=e.chatCompression,this.interactive=e.interactive??!1,this.trustedFolder=e.trustedFolder,this.skipLoopDetection=e.skipLoopDetection??!1,this.skipStartupContext=e.skipStartupContext??!1,this.bareMode=e.bareMode??!1,this.warnings=e.warnings??[],this.addLegacyPlanLocationWarning(),this.allowedHttpHookUrls=e.allowedHttpHookUrls??[],this.onPersistPermissionRuleCallback=e.onPersistPermissionRule,this.onRefreshPermissionsFromDiskCallback=e.onRefreshPermissionsFromDisk,this.useRipgrep=e.useRipgrep??!0,this.useBuiltinRipgrep=e.useBuiltinRipgrep??!0,this.shouldUseNodePtyShell=e.shouldUseNodePtyShell??V3(),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??v5e,this.truncateToolOutputLines=e.truncateToolOutputLines??S5e,this.toolOutputBatchBudget=e.toolOutputBatchBudget??C5e,this.channel=e.channel,this.jsonFd=e.jsonFd,this.jsonFile=e.jsonFile,this.jsonPartials=e.jsonPartials??!0,this.jsonSchema=e.jsonSchema,this.inputFile=e.inputFile,this.defaultFileEncoding=e.defaultFileEncoding,this.storage=new fe(this.targetDir),this.sessionStorage=new fe(this.sessionStorageDir,this.sessionRuntimeBaseDir),this.inputFormat=e.inputFormat??"text",this.fileExclusions=new Vj(this),this.eventEmitter=e.eventEmitter,this.arenaAgentClient=bv.create(),this.agentsSettings=e.agents??{},this.worktreeSettings=e.worktree??{},e.contextFileName&&Wj(e.contextFileName),this.modelsConfig=new iv({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&&m2(this);let o=this.getProxy();o&&(0,OR.setGlobalDispatcher)(new OR.ProxyAgent(o)),this.geminiClient=new AR(this),this.chatRecordingService=this.chatRecordingEnabled?new nh(this):void 0,this.extensionManager=new SA({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=n0(e.stopHookBlockingCap),this.userHooks=e.userHooks,this.projectHooks=e.projectHooks,this.hooks=e.hooks,this.memoryManager=new Db}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 MR,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 $p(this),await this.hookSystem.initialize(),this.debugLogger.debug("Hook system initialized"),this.messageBus=new wb,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?ct("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 G_(this),this.getBareMode()?await this.skillManager.refreshCache():await this.skillManager.startWatching(),this.debugLogger.debug("Skill manager initialized"),this.memoryPressureConfig=T5e(),this.memoryPressureMonitor=new Ub(this,this.memoryPressureConfig),this.permissionManager=new Ym(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=Xt.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),Kn("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 sz().getInstallationId(),YR(this,new oP(this)),this.debugLogger.info("Config initialization completed"),this.getBareMode()||(async()=>{try{let a=await new as(this.targetDir).getRepoTopLevel()??this.targetDir,l=qr.join(a,".matilda","worktrees");try{await Lde.access(l)}catch{this.debugLogger.debug(`Stale worktree sweep skipped: ${l} does not exist`);return}let c=await kde(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)||uE(n)!=="connected"&&t.push(n);return t}async refreshHierarchicalMemory(e="refresh"){let{memoryContent:t,fileCount:n,conditionalRules:s,projectRoot:o}=await aue(this.getWorkingDir(),this.getMemoryDiscoveryDirectories(),this.getFileService(),this.getExtensionContextFilePaths(),this.isTrustedFolder(),this.getImportFormat(),this.contextRuleExcludes,{explicitOnly:this.getBareMode(),loadReason:e,onInstructionsLoaded:gR(()=>this.hookSystem)});if(this.getManagedAutoMemoryEnabled()){let[a,l]=await Promise.all([h3(this.getProjectRoot()),p3().catch(()=>null)]);this.setUserMemory(this.memoryManager.appendToUserMemory(t,Mr(this.getProjectRoot()),a,{memoryDir:ei(),indexContent:l}))}else this.setUserMemory(t);this.setGeminiMdFileCount(n),this.conditionalRulesRegistry=new gb(s,o)}buildMemoryContextWarning(e){let t=this.getContentGeneratorConfig()?.contextWindowSize??this.modelsConfig.getGenerationConfig().contextWindowSize??Qp(this.getModel(),"input");if(!t||t<=0||!e)return;let n=Math.ceil(e.length/Xn),s=Math.floor(t*Ide);if(!(n<=s))return`Warning: Loaded MATILDA.md/context instructions use about ${n.toLocaleString()} tokens, more than ${Math.round(Ide*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 $m()?.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}=CP(this,e,this.modelsConfig.getGenerationConfig(),this.modelsConfig.getGenerationConfigSources(),{strictModelProvider:this.modelsConfig.isStrictModelProviderSelection()}),l=o;this.contentGenerator=await Fd(l,this,s?!0:t),this.contentGeneratorConfig=l,this.contentGeneratorConfigSources=a,this.baseLlmClient=new um(this.contentGenerator,this);let c=this.getMessageBus();!this.getDisableAllHooks()&&c&&Um(c,`Successfully authenticated with ${e}`,"auth_success","Authentication successful").catch(()=>{})}getBaseLlmClient(){if(!this.baseLlmClient)if(this.contentGenerator)this.baseLlmClient=new um(this.getContentGenerator(),this);else throw new Error("BaseLlmClient not initialized. Ensure authentication has occurred and ContentGenerator is ready.");return this.baseLlmClient}getSessionId(){return this.sessionId}getWarnings(){let e=this.buildMemoryContextWarning(this.getUserMemory());return e?[...this.warnings,e]:this.warnings}getDebugLogger(){return this.debugLogger}async startNewSession(e,t){return this.sessionTransitionMutex.runExclusive(async()=>{let n=this.chatRecordingService;try{n?.finalize()}catch{}await n?.releaseTranscriptOwnership();let s=this.sessionId;if(this.sessionId=e??Mde(),Xt.env&&(Xt.env.MATILDA_CODE_SESSION_ID=this.sessionId),this.sessionData=t,zR(this),this.debugLogger=$(),this.chatRecordingService=this.chatRecordingEnabled?new nh(this):void 0,this.getFileReadCache().clear(),this.toolResultBudget.bytesWritten=0,this.getMemoryPressureMonitor()?.resetForNewSession(),this.fileHistoryService=void 0,g2(this.sessionId),f2(),ii.resetInstance(),this.initialized&&YR(this,new oP(this)),this.runtimeStatusEnabled&&s!==this.sessionId){let o=this.sessionStorage.getRuntimeStatusPath(s),a=this.sessionStorage.getRuntimeStatusPath(this.sessionId),l=this.cliVersion??null,c=this.targetDir,u=this.sessionId;this.queueRuntimeStatusWrite(async()=>{await nW(o),await v0(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 v0(this.sessionStorage.getRuntimeStatusPath(this.sessionId),{sessionId:this.sessionId,workDir:e,matildaVersion:this.cliVersion??null})}),await this.flushRuntimeStatusWrites())}getResumedSessionData(){return this.sessionData}shouldLoadMemoryFromIncludeDirectories(){return this.loadMemoryFromIncludeDirectories}getImportFormat(){return this.importFormat}getContentGeneratorConfig(){return $m()?.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=ri(this.fastModel);return n?.authType?`${n.authType}:${e.modelId}`:e.modelId}resolveFastModelSelector(){if(this.fastModel)try{return ri(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}=CP(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=Xt.env.SEATBELT_PROFILE,n=Xt.env.SANDBOX,s=Xt.env.MATILDA_DESKTOP_SANDBOX_NONCE,o=Xt.env.MATILDA_DESKTOP_SANDBOX_ACTIVE;return(e?.command==="sandbox-exec"||n==="sandbox-exec")&&!!t&&t.startsWith("restrictive-")&&(!s||o===s)}getTargetDir(){return this.targetDir}getCurrentSessionArtifactMoves(e,t){let n=qr.join(e.getProjectDir(),"chats"),s=qr.join(t.getProjectDir(),"chats");return[`${this.sessionId}.jsonl`,`${this.sessionId}.runtime.json`,`${this.sessionId}.worktree.json`].map(o=>({from:qr.join(n,o),to:qr.join(s,o)}))}moveFile(e,t){try{_t.renameSync(e,t)}catch(n){if(n.code!=="EXDEV")throw n;let s=!1;try{_t.copyFileSync(e,t),s=!0,_t.unlinkSync(e)}catch(o){if(s)try{_t.unlinkSync(t)}catch{}throw o}}}moveCurrentSessionArtifacts(e,t){let n=[];for(let{from:s,to:o}of this.getCurrentSessionArtifactMoves(e,t))if(_t.existsSync(s)){_t.mkdirSync(qr.dirname(o),{recursive:!0});try{this.moveFile(s,o),n.push({from:s,to:o})}catch(a){for(let l of n.reverse())try{_t.mkdirSync(qr.dirname(l.from),{recursive:!0}),this.moveFile(l.to,l.from)}catch(c){this.debugLogger.warn("Failed to roll back moved session artifact",c)}throw a}}}async prepareSessionArtifactMigration(e,t,n){this.chatRecordingService?.finalize(),await this.chatRecordingService?.releaseTranscriptOwnership(),await this.flushRuntimeStatusWrites();try{this.moveCurrentSessionArtifacts(e,t)}catch(s){try{Xt.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=_t.realpathSync(Xt.cwd()),s=qr.resolve(e),o=t??_t.realpathSync(s);if(!_t.statSync(s).isDirectory())throw new Error(`Path is not a directory: ${s}`);let a=Ia.resolveRootDirectories(o,this.explicitIncludeDirectories);Xt.chdir(s);let l=_t.realpathSync(Xt.cwd());if(l!==o)throw Xt.chdir(n),new Error(`Changed directory to ${l}, expected ${o}.`);let c=this.sessionStorage,u=new fe(o);this.sessionStoragePinned||await this.prepareSessionArtifactMigration(c,u,n),this.targetDir=o,this.cwd=o,this.storage=u,this.sessionStoragePinned||(this.sessionStorage=u,this.sessionStorageDir=o,this.chatRecordingService?.resetStoragePaths(),this.sessionService=void 0),await this.refreshCurrentRuntimeStatus(o),this.workspaceContext.applyRootDirectories(a),this.fileDiscoveryService=null,this.fileHistoryService=void 0,this.getFileReadCache().clear();try{return await this.refreshHierarchicalMemory(),{}}catch(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?.releaseTranscriptOwnership()}catch{}this.skillManager?.stopWatching(),this.toolRegistry&&await this.toolRegistry.stop(),this.backgroundTaskRegistry.abortAll(),this.monitorRegistry.abortAll({notify:!1}),this.backgroundShellRegistry.abortAll(),await this.cleanupArenaRuntime(),await this.cleanupTeamRuntime()}catch(e){this.debugLogger.error("Error during Config shutdown:",e)}finally{p2()&&await y2()}}getPromptRegistry(){return this.promptRegistry}getDebugMode(){return this.debugMode}getQuestion(){return this.question}getSystemPrompt(){return this.systemPrompt}getAppendSystemPrompt(){return this.appendSystemPrompt}getCoreTools(){return this.getBareMode()?k5e: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?.()??x5e}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 dj("Cannot enable privileged approval modes in an untrusted folder.");e==="plan"&&this.approvalMode!=="plan"?(this.prePlanMode=this.approvalMode,this.planGateState=hq(++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=eI()),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 _t.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 qr.join(this.plansDir,`${fe.sanitizePlanSessionId(this.sessionId)}.md`)}savePlan(e){this.assertPlansDirWithinTargetDir();let t=this.getPlanFilePath(),n=qr.dirname(t);_t.mkdirSync(n,{recursive:!0});let s=t+".tmp";_t.writeFileSync(s,e,"utf-8");try{_t.renameSync(s,t)}catch(o){if(o.code!=="EXDEV")throw o;_t.copyFileSync(s,t),_t.unlinkSync(s)}try{this.assertPlanFilePathWithinTargetDir(t)}catch(o){try{_t.unlinkSync(t)}catch{}throw o}}loadPlan(){this.assertPlansDirWithinTargetDir();let e=this.getPlanFilePath();this.assertPlanFilePathWithinTargetDir(e);try{return _t.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??J2}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??yP}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 Ub(this,this.memoryPressureConfig)}return this.memoryPressureMonitor}getCronScheduler(){return this.cronScheduler||(this.cronScheduler=new bE(this.getProjectRoot())),this.cronScheduler}isCronEnabled(){return Xt.env.MATILDA_CODE_DISABLE_CRON==="1"?!1:this.cronEnabled}isAgentTeamEnabled(){return Xt.env.MATILDA_CODE_ENABLE_AGENT_TEAM==="1"?!0:this.agentTeamEnabled}isWorkflowsEnabled(){return Xt.env.MATILDA_CODE_DISABLE_WORKFLOWS==="1"?!1:Xt.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=Xt.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 Mv(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 cue(this.proxy)}getWorkingDir(){return this.cwd}getBugCommand(){return this.bugCommand}getFileService(){return this.fileDiscoveryService||(this.fileDiscoveryService=new Tl(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()||!ez()}getIdeMode(){return this.ideMode}getFolderTrustFeature(){return this.folderTrustFeature}getFolderTrust(){return this.folderTrust}getAllowedHttpHookUrls(){return this.getBareMode()?[]:this.allowedHttpHookUrls}isTrustedFolder(){let e=Nu.get();return e?.workspaceState?.isTrusted!==void 0?e.workspaceState.isTrusted:this.trustedFolder??!0}setIdeMode(e){this.ideMode=e}getAuthType(){return this.getContentGeneratorConfig()?.authType}getCliVersion(){return this.cliVersion}getChannel(){return this.channel}getJsonFd(){return this.jsonFd}getJsonFile(){return this.jsonFile}getJsonPartials(){return this.jsonPartials}getJsonSchema(){return this.jsonSchema}getInputFile(){return this.inputFile}getDefaultFileEncoding(){return this.defaultFileEncoding}getFileSystemService(){return this.fileSystemService}setFileSystemService(e){this.fileSystemService=e}getChatCompression(){return this.chatCompression}isInteractive(){return this.interactive}getUseRipgrep(){return this.useRipgrep}getUseBuiltinRipgrep(){return this.useBuiltinRipgrep}getShouldUseNodePtyShell(){return this.shouldUseNodePtyShell}getSkipNextSpeakerCheck(){return this.skipNextSpeakerCheck}getShellExecutionConfig(){return this.shellExecutionConfig}setShellExecutionConfig(e){this.shellExecutionConfig={terminalWidth:e.terminalWidth??this.shellExecutionConfig.terminalWidth,terminalHeight:e.terminalHeight??this.shellExecutionConfig.terminalHeight,showColor:e.showColor??this.shellExecutionConfig.showColor,pager:e.pager??this.shellExecutionConfig.pager,maxBufferedOutputBytes:e.maxBufferedOutputBytes??this.shellExecutionConfig.maxBufferedOutputBytes}}getScreenReader(){return this.accessibility.screenReader??!1}getSkipLoopDetection(){return this.skipLoopDetection}getSkipStartupContext(){return this.skipStartupContext}getBareMode(){return this.bareMode}getTruncateToolOutputThreshold(){return this.truncateToolOutputThreshold<=0?Number.POSITIVE_INFINITY:this.truncateToolOutputThreshold}getTruncateToolOutputLines(){return this.truncateToolOutputLines<=0?Number.POSITIVE_INFINITY:this.truncateToolOutputLines}getToolOutputBatchBudget(){return this.toolOutputBatchBudget<=0?Number.POSITIVE_INFINITY:this.toolOutputBatchBudget}trackToolResultBytes(e){this.toolResultBudget.bytesWritten+=e}getToolResultBytesWritten(){return this.toolResultBudget.bytesWritten}getOutputFormat(){return this.outputFormat}getChatRecordingService(){if(this.chatRecordingEnabled)return this.chatRecordingService||(this.chatRecordingService=new nh(this)),this.chatRecordingService}getTranscriptPath(){if(!this.chatRecordingEnabled)return"";let e=this.sessionStorage.getProjectDir(),n=`${this.getSessionId()}.jsonl`;return qr.join(e,"chats",n)}getSessionService(){return this.sessionService||(this.sessionService=new Fv(this.sessionStorageDir,this.sessionRuntimeBaseDir)),this.sessionService}getFileExclusions(){return this.fileExclusions}getSubagentManager(){return this.subagentManager}getBackgroundTaskRegistry(){return this.backgroundTaskRegistry}getMonitorRegistry(){return this.monitorRegistry}getBackgroundAgentResumeService(){return this.backgroundAgentResumeService||(this.backgroundAgentResumeService=new qA(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 ky),this.fileReadCache}getFileReadCacheDisabled(){return this.fileReadCacheDisabled}getShouldAvoidPermissionPrompts(){return!1}getSkillManager(){return this.skillManager}setModelInvocableCommandsProvider(e){this.modelInvocableCommandsProvider=e}getModelInvocableCommandsProvider(){return this.modelInvocableCommandsProvider}setModelInvocableCommandsExecutor(e){this.modelInvocableCommandsExecutor=e}getModelInvocableCommandsExecutor(){return this.modelInvocableCommandsExecutor}addInlineAnnouncedSkillKeys(e){for(let t of e)this.pendingInlineAnnouncedSkillKeys.add(t)}consumeInlineAnnouncedSkillKeys(){let e=this.pendingInlineAnnouncedSkillKeys;return this.pendingInlineAnnouncedSkillKeys=new Set,e}getPermissionManager(){return this.permissionManager}getOnPersistPermissionRule(){return this.onPersistPermissionRuleCallback}getOnRefreshPermissionsFromDisk(){return this.onRefreshPermissionsFromDiskCallback}async createToolRegistry(e,t){let n=new hE(this,this.eventEmitter,e),s=async(a,l)=>{let c=!0;try{c=this.permissionManager?await this.permissionManager.isToolEnabled(a):!0}catch(u){this.debugLogger.warn(`Failed to check permissions for tool "${a}", skipping registration:`,u);return}c&&n.registerFactory(a,l)},o=async()=>{if(!this.jsonSchema||t?.forSubAgent)return;let a=this.jsonSchema;await s(R.STRUCTURED_OUTPUT,async()=>{let{SyntheticOutputTool:l}=await import("./syntheticOutput-QEUQIVQJ.js");return new l(a)})};if(this.getBareMode())return await s(R.READ_FILE,async()=>{let{ReadFileTool:a}=await import("./read-file-J5UBJYDO.js");return new a(this)}),await s(R.EDIT,async()=>{let{EditTool:a}=await import("./edit-BV6UXJHV.js");return new a(this)}),await s(R.NOTEBOOK_EDIT,async()=>{let{NotebookEditTool:a}=await import("./notebook-edit-L6PI7HSF.js");return new a(this)}),await s(R.SHELL,async()=>{let{ShellTool:a}=await import("./shell-VENIQ6VU.js");return new a(this)}),await o(),this.debugLogger.debug(`ToolRegistry created: ${JSON.stringify(n.getAllToolNames())} (${n.getAllToolNames().length} tools)`),n;if(await s(R.TOOL_SEARCH,async()=>{let{ToolSearchTool:a}=await import("./tool-search-OWJC3UTX.js");return new a(this)}),await s(R.AGENT,async()=>{let{AgentTool:a}=await import("./agent-6WJWHK33.js");return new a(this)}),await s(R.TASK_STOP,async()=>{let{TaskStopTool:a}=await import("./task-stop-JO3CXG2K.js");return new a(this)}),await s(R.SEND_MESSAGE,async()=>{let{SendMessageTool:a}=await import("./send-message-XXRROIL7.js");return new a(this)}),await s(R.SKILL,async()=>{let{SkillTool:a}=await import("./skill-CZPMRNLD.js");return new a(this)}),await s(R.LS,async()=>{let{LSTool:a}=await import("./ls-CLDNF3YS.js");return new a(this)}),await s(R.READ_FILE,async()=>{let{ReadFileTool:a}=await import("./read-file-J5UBJYDO.js");return new a(this)}),this.getUseRipgrep()){let a=!1,l;try{a=await OK(this.getUseBuiltinRipgrep())}catch(c){l=re(c)}a?await s(R.GREP,async()=>{let{RipGrepTool:c}=await import("./ripGrep-INSEEE7H.js");return new c(this)}):(_2(this,new L2(this.getUseRipgrep(),this.getUseBuiltinRipgrep(),l||"ripgrep is not available")),await s(R.GREP,async()=>{let{GrepTool:c}=await import("./grep-XOHANNB6.js");return new c(this)}))}else await s(R.GREP,async()=>{let{GrepTool:a}=await import("./grep-XOHANNB6.js");return new a(this)});if(await s(R.GLOB,async()=>{let{GlobTool:a}=await import("./glob-72QENSN5.js");return new a(this)}),await s(R.EDIT,async()=>{let{EditTool:a}=await import("./edit-BV6UXJHV.js");return new a(this)}),await s(R.NOTEBOOK_EDIT,async()=>{let{NotebookEditTool:a}=await import("./notebook-edit-L6PI7HSF.js");return new a(this)}),await s(R.WRITE_FILE,async()=>{let{WriteFileTool:a}=await import("./write-file-ML7S4MKZ.js");return new a(this)}),await s(R.SHELL,async()=>{let{ShellTool:a}=await import("./shell-VENIQ6VU.js");return new a(this)}),await s(R.TODO_WRITE,async()=>{let{TodoWriteTool:a}=await import("./todoWrite-7BZMVNBC.js");return new a(this)}),await s(R.UPDATE_GOAL,async()=>{let{UpdateGoalTool:a}=await import("./update-goal-CF6G57J7.js");return new a(this)}),await s(R.ASK_USER_QUESTION,async()=>{let{AskUserQuestionTool:a}=await import("./askUserQuestion-MJ4FTAOQ.js");return new a(this)}),this.sdkMode||(await s(R.EXIT_PLAN_MODE,async()=>{let{ExitPlanModeTool:a}=await import("./exitPlanMode-XSANODDU.js");return new a(this)}),await s(R.ENTER_PLAN_MODE,async()=>{let{EnterPlanModeTool:a}=await import("./enterPlanMode-6XO2FCD4.js");return new a(this)})),await s(R.ENTER_WORKTREE,async()=>{let{EnterWorktreeTool:a}=await import("./enter-worktree-WFRS6DOO.js");return new a(this)}),await s(R.EXIT_WORKTREE,async()=>{let{ExitWorktreeTool:a}=await import("./exit-worktree-YRVXXUJG.js");return new a(this)}),await s(R.WEB_FETCH,async()=>{let{WebFetchTool:a}=await import("./web-fetch-K575OWZ7.js");return new a(this)}),await s(R.WEB_SEARCH,async()=>{let{WebSearchTool:a}=await import("./web-search-F6JRBXFV.js");return new a(this)}),await s(R.SYMBOL_SEARCH,async()=>{let{SymbolSearchTool:a}=await import("./symbol-search-3MVTK4KV.js");return new a(this)}),this.isLspEnabled()&&this.getLspClient()&&await s(R.LSP,async()=>{let{LspTool:a}=await import("./lsp-7SKRKR5Q.js");return new a(this)}),await o(),this.isCronEnabled()&&(await s(R.CRON_CREATE,async()=>{let{CronCreateTool:a}=await import("./cron-create-BTTPO3JC.js");return new a(this)}),await s(R.CRON_LIST,async()=>{let{CronListTool:a}=await import("./cron-list-J4HRR46K.js");return new a(this)}),await s(R.CRON_DELETE,async()=>{let{CronDeleteTool:a}=await import("./cron-delete-U55RHRID.js");return new a(this)})),this.isAgentTeamEnabled()&&(await s(R.TEAM_CREATE,async()=>{let{TeamCreateTool:a}=await import("./team-create-QFMW37FS.js");return new a(this)}),await s(R.TEAM_DELETE,async()=>{let{TeamDeleteTool:a}=await import("./team-delete-4YYLUV23.js");return new a(this)}),await s(R.TASK_CREATE,async()=>{let{TaskCreateTool:a}=await import("./task-create-AEJQ73GE.js");return new a(this)}),await s(R.TASK_UPDATE,async()=>{let{TaskUpdateTool:a}=await import("./task-update-3YY37VFN.js");return new a(this)}),await s(R.TASK_LIST,async()=>{let{TaskListTool:a}=await import("./task-list-ZEJTNZ2O.js");return new a(this)})),this.isWorkflowsEnabled()&&await s(R.WORKFLOW,async()=>{let{WorkflowTool:a}=await import("./workflow-YDVW6LM6.js");return new a(this)}),this.isComputerUseEnabled()){let{registerComputerUseTools:a}=await import("./computer-use-NPZQKWAA.js");await a(s,this)}if(await s(R.MONITOR,async()=>{let{MonitorTool:a}=await import("./monitor-KB6FBBGO.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 A5e="refs/notes/ai-attribution";function Nde(r,e){let t=JSON.stringify(r);return Buffer.byteLength(t,"utf-8")>30720?null:{command:"git",args:["notes",`--ref=${A5e}`,"add","-f","-m",t,e]}}var uhe=Ve(rl(),1);g();import*as Fde from"node:fs";var Hb=class extends Error{constructor(t,n){super(t);this.errorType=n;Object.setPrototypeOf(this,new.target.prototype)}name="StructuredToolError"};function DR(r){return r instanceof Hb||typeof r=="object"&&r!==null&&r.name==="StructuredToolError"&&"errorType"in r}async function $de(r,e,t,n={}){let s;try{s=await Fde.promises.stat(e)}catch(d){let f=d?.code;if(f==="ENOENT"){if(n.expectExisting){let w=`File ${e} disappeared after the model read it (stat now returns ENOENT). Re-read with the ${R.READ_FILE} tool \u2014 the path may have been deleted or moved \u2014 before retrying ${t} it.`;return{ok:!1,type:"file_changed_since_read",rawMessage:w,displayMessage:`file disappeared after last read; re-run ${R.READ_FILE} first.`}}return{ok:!0}}let p=`Could not stat ${e} to verify prior read (${f??"unknown error"}). Re-read with the ${R.READ_FILE} tool, then retry ${t} it.`,y=t==="editing"?"editing this file":"overwriting this file";return{ok:!1,type:"prior_read_verification_failed",rawMessage:p,displayMessage:`cannot verify prior read of ${e}; re-run ${R.READ_FILE} before ${y}.`}}if(s.isDirectory()){let d=t==="editing"?"edit":"overwrite",f=`${e} is a directory. The Edit / WriteFile tools only operate on regular files. Use a different mechanism (e.g. the shell tool) if you need to ${d} the contents of this directory.`;return{ok:!1,type:"target_is_directory",rawMessage:f,displayMessage:`path is a directory; cannot ${d} via this tool.`}}if(!s.isFile()){let d=t==="editing"?"edit":"overwrite",f=`${e} is a FIFO / socket / character or block device. The Edit / WriteFile tools only operate on regular files; the ${R.READ_FILE} tool also rejects these targets. Use a different mechanism (e.g. shell tool with the appropriate command) if you need to ${d} this path.`;return{ok:!1,type:"edit_requires_prior_read",rawMessage:f,displayMessage:`special file; cannot ${d} via this tool.`}}let o=r.check(s);if(o.state==="fresh"&&o.entry.lastReadAt!==void 0&&o.entry.lastReadCacheable)return{ok:!0};if(o.state==="stale"){let d=`File ${e} has been modified since you last read it (mtime or size changed). Re-read it with the ${R.READ_FILE} tool before ${t} it to ensure your changes are based on current content.`;return{ok:!1,type:"file_changed_since_read",rawMessage:d,displayMessage:`file changed since last read; re-run ${R.READ_FILE} first.`}}if(o.state==="fresh"&&o.entry.lastReadAt!==void 0&&!o.entry.lastReadCacheable){let d=t==="editing"?"edit":"overwrite",f=`File ${e} is a binary / image / audio / video / PDF / notebook payload that the ${R.READ_FILE} tool returns as a structured value rather than as plain text. The Edit / WriteFile tools cannot mutate that payload safely \u2014 re-reading it would not change this. If this is a Jupyter notebook (.ipynb), use the ${R.NOTEBOOK_EDIT} tool for cell-level edits after reading it. For other non-text files, use a different mechanism (e.g. shell tool with an appropriate writer) if you need to ${d} it.`;return{ok:!1,type:"edit_requires_prior_read",rawMessage:f,displayMessage:`non-text payload; cannot ${d} via this tool.`}}let a=t==="editing"?"edit":"overwrite",l=t==="editing"?"editing this file":"overwriting this file";if(t==="editing"&&n.autoStampUnread!==!1)return r.recordRead(e,s,{full:!0,cacheable:!0}),{ok:!0};let u=t==="editing"?`(a partial read with offset / limit is fine \u2014 you only need to have seen the bytes you intend to ${a})`:"(read the full file \u2014 overwriting replaces every byte, so any unseen bytes would be discarded)",h=`File ${e} has not been read in this session. Use the ${R.READ_FILE} tool first to load the current content ${u} before ${t} it.`;return{ok:!1,type:"edit_requires_prior_read",rawMessage:h,displayMessage:`${R.READ_FILE} required before ${l}.`}}g();var jde=Ve(rl(),1);var Ude=new Set(["+","?","|","(",")","{","}"]),R5e=new Set(["*","+","?"]);function zde(r){let e=r.trim(),t=e.match(/^\s*sed\s+/);if(!t)return null;let n;try{n=(0,jde.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(P5e(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||M5e(l)||c.startsWith("~")||c.includes("$"))return null;let h=$5e(l);if(h===null)return null;let d={filePath:c,...h,extendedRegex:a};return I5e(d)?d:null}function P5e(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 M5e(r){return r.includes("`")||/\$(?:[A-Za-z_][A-Za-z0-9_]*|\{|\(|\d|[#?@$!*])/u.test(r)}function I5e(r){try{let e=Gde(r);return O5e(e)||D5e(e)||(new RegExp(e),L5e(r.replacement,N5e(e)))?!1:!F5e(e)}catch{return!1}}function O5e(r){return/\[\[:[A-Za-z]+:\]\]/u.test(r)}function D5e(r){return/\\[<>dDwWsS]/u.test(r)}function L5e(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 N5e(r){let e=0;for(let t=0;t<r.length;t++){let n=r[t];if(n==="\\"){t++;continue}if(n==="["){t=qde(r,t);continue}n==="("&&r[t+1]!=="?"&&e++}return e}function F5e(r){let e=[];for(let t=0;t<r.length;t++){let n=r[t];if(n==="\\"){t++;continue}if(n==="["){t=qde(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=Hde(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=Hde(r,t);s!==null&&(e.length>0&&(e[e.length-1].hasQuantifier=!0),t=s-1)}return!1}function qde(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 Hde(r,e){let t=r[e];if(t===void 0)return null;if(R5e.has(t))return e+1;if(t!=="{")return null;let n=e+1,s=!1;for(;Bde(r[n]);)s=!0,n++;if(!s)return null;if(r[n]===",")for(n++;Bde(r[n]);)n++;return r[n]==="}"?n+1:null}function Bde(r){return r!==void 0&&r>="0"&&r<="9"}function $5e(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"||!U5e(s)||H5e(n)?null:{pattern:t,replacement:n,flags:s}}function U5e(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 H5e(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 Wde(r,e){if(r.length===0)return"";let t=Gde(e),n=j5e(e.flags),s=e.flags.includes("g");try{let o=new RegExp(t,"g"),a=r.split(/(\n)/);return(r.endsWith(`
2197
2197
  `)?a.slice(0,-1):a).map((c,u)=>u%2===1?c:z5e(c,o,e.replacement,{occurrence:n,replaceAll:s})).join("")}catch(o){throw new Error(`sed pattern simulation failed: ${re(o)}`)}}function Gde(r){let e=B5e(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];Ude.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+=Ude.has(o)?`\\${o}`:o}return t}function B5e(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 j5e(r){let e=r.match(/[1-9][0-9]*/);return e?Number(e[0]):null}function z5e(r,e,t,n){let s=0,o=!1,a=-1;return e.lastIndex=0,r.replace(e,(...l)=>{let c=String(l[0]),u=Number(l[l.length-2]);if(c.length===0&&u===a&&s>0&&o)return"";if(s++,o=c.length>0,a=u+c.length,!(n.occurrence===null?n.replaceAll||s===1:n.replaceAll?s>=n.occurrence:s===n.occurrence))return String(l[0]);let d=l.slice(1,-2).map(f=>f===void 0?"":String(f));return q5e(c,d,t)})}function q5e(r,e,t){let n="";for(let s=0;s<t.length;s++){let o=t[s];if(o==="\\"&&s+1<t.length){let a=t[s+1];a==="/"?n+="/":a==="&"?n+="&":a==="\\"?n+="\\":a>="1"&&a<="9"?n+=e[Number(a)-1]??"":n+=o+a,s++;continue}n+=o==="&"?r:o}return n}g();import{isAbsolute as W5e}from"node:path";import{fileURLToPath as G5e,pathToFileURL as V5e}from"node:url";var Kde=5e3,K5e=10,Vde=200,Y5e=5;function LR(r){let e=r.severity??"error";return e==="error"||e==="warning"?e:void 0}function J5e(r){let e=r.replace(/\s+/g," ").trim(),t=[...e];return t.length>Vde?`${t.slice(0,Vde).join("")}\u2026`:e}function Yde(r,e){let t=e.filter(c=>LR(c)==="error").length,n=e.length-t,s=[t>0?`${t} error${t===1?"":"s"}`:"",n>0?`${n} warning${n===1?"":"s"}`:""].filter(Boolean).join(", "),o=e.slice(0,K5e),a=o.map(c=>{let u=(c.range.start.line??0)+1,h=(c.range.start.character??0)+1,d=LR(c)??"error",f=c.code!==void 0?` [${c.code}]`:"",p=c.source?` (${c.source})`:"";return` [${d}] ${u}:${h} ${J5e(c.message)}${f}${p}`}),l=e.length-o.length;return l>0&&a.push(` ... and ${l} more`),`LSP diagnostics for ${r} (${s}):
2198
2198
  ${a.join(`
2199
2199
  `)}`}async function d8t(r,e){try{if(!r.isLspEnabled())return;let t=r.getLspClient();if(!t||!W5e(e))return;let n=V5e(e).toString();t.invalidateDocument?.(n);let s=t.diagnostics(n);s.catch(()=>{});let o,a;try{a=await Promise.race([s,new Promise((c,u)=>{o=setTimeout(()=>u(new Error("LSP diagnostics timed out")),Kde)})])}finally{o&&clearTimeout(o)}let l=a.filter(c=>LR(c)!==void 0);return l.length===0?void 0:Yde(e,l)}catch{return}}async function Jde(r){try{if(!r.isLspEnabled())return;let e=r.getLspClient();if(!e)return;let t=e.workspaceDiagnostics();t.catch(()=>{});let n,s;try{s=await Promise.race([t,new Promise((u,h)=>{n=setTimeout(()=>h(new Error("LSP workspace diagnostics timed out")),Kde)})])}finally{n&&clearTimeout(n)}let o=s.map(u=>({filePath:X5e(u.uri),actionable:u.diagnostics.filter(h=>LR(h)!==void 0)})).filter(u=>u.actionable.length>0);if(o.length===0)return;let a=o.slice(0,Y5e),l=a.map(u=>Yde(u.filePath,u.actionable)),c=o.length-a.length;return c>0&&l.push(`... and ${c} more file${c===1?"":"s"} with diagnostics`),l.join(`
@@ -2294,7 +2294,7 @@ ${n}
2294
2294
  - Installation commands: \`npm install\`, \`pip install\`
2295
2295
  - Git operations: \`git commit\`, \`git push\`
2296
2296
  - Test runs: \`npm test\`, \`pytest\`
2297
- `}function OKe(){let r=Zn(),e=mhe(r);switch(r.shell){case"cmd":return`Exact cmd.exe command to execute as \`${e}\``;case"powershell":return`Exact PowerShell command to execute as \`${e}\``;case"bash":return`Exact bash command to execute as \`${e}\``;default:return r.shell}}var pj=class r extends Qs{constructor(t){super(r.Name,Cn.SHELL,IKe(),"execute",{type:"object",properties:{command:{type:"string",description:OKe()},is_background:{type:"boolean",description:"Optional: Whether to run the command in background. If not specified, defaults to false (foreground execution). Explicitly set to true for long-running processes like development servers, watchers, or daemons that should continue running without blocking further commands."},timeout:{type:"number",description:"Optional timeout in milliseconds (max 600000)"},description:{type:"string",description:"Brief description of the command for the user. Be specific and concise. Ideally a single sentence. Can be up to 3 sentences for clarity. No line breaks."},directory:{type:"string",description:"(OPTIONAL) The absolute path of the directory to run the command in. If not provided, the project root directory is used. Must be a directory within the workspace and must already exist."}},required:["command"]},!1,!0);this.config=t}static Name=R.SHELL;get maxOutputChars(){return 3e4}validateToolParamValues(t){if(kKe(t),!t.command.trim())return"Command cannot be empty.";if(xKe.test(t.command))return'Command contains leaked tool-argument markup (`<arg_key>` / `<arg_value>`). Put each field in its own JSON property \u2014 e.g. `{ "command": "...", "description": "..." }` \u2014 and do not embed XML-style tags inside the command string.';let n=gr(t.command);if(t.is_background&&TKe(n))return'Background shell commands must not end with a bare "&". Remove the trailing "&" and rely on is_background: true instead.';if(U3(t.command).length===0)return"Could not identify command root to obtain permission from user.";if(t.timeout!==void 0){if(typeof t.timeout!="number"||!Number.isInteger(t.timeout))return"Timeout must be an integer number of milliseconds.";if(t.timeout<=0)return"Timeout must be a positive number.";if(t.timeout>6e5)return"Timeout cannot exceed 600000ms (10 minutes)."}if(t.directory){if(!Ss.isAbsolute(t.directory))return"Directory must be an absolute path.";let s=this.config.storage.getUserSkillsDirs(),o=Ss.resolve(t.directory);if(kj(s,o))return"Explicitly running shell commands from within the user skills directory is not allowed. Please use absolute paths for command parameter instead.";if(!this.config.getWorkspaceContext().getDirectories().some(u=>t.directory.startsWith(u)))return`Directory '${t.directory}' is not within any of the registered workspace directories.`}if(!t.is_background){let s=dhe(n);if(s!==null){let o=s.intentionalSleepRejection??(s.isStandalone?"If you genuinely need a standalone delay (rate limiting, deliberate pacing), add a trailing comment like `# intentional-sleep: wait for MCP rate limit reset` (up to 10 minutes).":"Split into two calls: first `sleep N # intentional-sleep: <reason>` (standalone), then the follow-up command.");return`Blocked: ${s.description}. Run blocking commands in the background with is_background: true. For streaming events (watching logs, polling APIs), use the Monitor tool. `+o}}return null}createInvocation(t){return new Pb(this.config,t)}toAutoClassifierInput(t){return{command:t.command,cwd:t.directory??this.config.getTargetDir()}}};export{qP as a,Zz as b,Mc as c,Ic as d,qd as e,Gt as f,am as g,_v as h,bv as i,ri as j,Gd as k,Fo as l,Vd as m,i7e as n,o7e as o,vv as p,ni as q,cm as r,VP as s,ife as t,Lc as u,Nc as v,$o as w,Fc as x,lq as y,I7e as z,cq as A,YP as B,JP as C,lfe as D,cfe as E,ufe as F,N7e as G,F7e as H,fq as I,mfe as J,Kn as K,hm as L,Nfe as M,kq as N,r0 as O,n0 as P,Uc as Q,xv as R,gm as S,ym as T,Xd as U,kYe as V,Rq as W,Pq as X,Mq as Y,Iq as Z,o0 as _,d0 as $,_m as aa,Va as ba,Yn as ca,bm as da,$Ye as ea,Oq as fa,Av as ga,UYe as ha,HYe as ia,BYe as ja,zd as ka,Pv as la,Qd as ma,Zfe as na,Qfe as oa,VYe as pa,KYe as qa,npe as ra,spe as sa,ape as ta,lpe as ua,YYe as va,Sm as wa,Iv as xa,Ov as ya,Jq as za,Mv as Aa,tW as Ba,v0 as Ca,rW as Da,nW as Ea,Ps as Fa,E0 as Ga,Spe as Ha,S0 as Ia,C0 as Ja,oW as Ka,aW as La,$v as Ma,jc as Na,Fv as Oa,TW as Pa,kW as Qa,H9e as Ra,xW as Sa,B9e as Ta,AW as Ua,Ype as Va,IW as Wa,DW as Xa,LW as Ya,nme as Za,NW as _a,ime as $a,FW as ab,$W as bb,ome as cb,N0 as db,ame as eb,F0 as fb,UW as gb,$0 as hb,U0 as ib,H0 as jb,B0 as kb,j0 as lb,Uv as mb,z0 as nb,q0 as ob,km as pb,ume as qb,dme as rb,hme as sb,fme as tb,Hv as ub,gme as vb,qW as wb,ZJe as xb,Ame as yb,Tm as zb,Ho as Ab,zc as Bb,nh as Cb,KW as Db,YW as Eb,V0 as Fb,qc as Gb,Bo as Hb,tG as Ib,Am as Jb,Gv as Kb,iG as Lb,NXe as Mb,Vv as Nb,oG as Ob,FXe as Pb,Mm as Qb,tM as Rb,bG as Sb,Jv as Tb,Qv as Ub,iM as Vb,oM as Wb,aM as Xb,lM as Yb,Uge as Zb,Bge as _b,PG as $b,jge as ac,qge as bc,IG as cc,Wge as dc,Ja as ec,tS as fc,OG as gc,DZe as hc,LG as ic,uM as jc,NG as kc,FG as lc,wM as mc,Zge as nc,Qge as oc,gM as pc,kn as qc,zG as rc,Xa as sc,lS as tc,cS as uc,ii as vc,Gc as wc,u3 as xc,Wye as yc,Gye as zc,d3 as Ac,Qa as Bc,h3 as Cc,f3 as Dc,p3 as Ec,tl as Fc,dh as Gc,CM as Hc,EM as Ic,TM as Jc,kM as Kc,Um as Lc,xM as Mc,rl as Nc,get as Oc,fh as Pc,Zn as Qc,qwe as Rc,Wm as Sc,zi as Tc,$M as Uc,U3 as Vc,gr as Wc,N3 as Xc,F3 as Yc,CS as Zc,Ret as _c,Qc as $c,Wwe as ad,HM as bd,G3 as cd,Gwe as dd,Gi as ed,Vwe as fd,qo as gd,Pet as hd,Met as id,Iet as jd,V3 as kd,Jc as ld,iwe as md,jo as nd,Xc as od,_S as pd,bS as qd,Zc as rd,Bm as sd,awe as td,M3 as ud,det as vd,hh as wd,dwe as xd,pwe as yd,mwe as zd,gwe as Ad,DM as Bd,zo as Cd,H4 as Dd,B4 as Ed,j4 as Fd,z4 as Gd,aI as Hd,q4 as Id,W4 as Jd,G4 as Kd,V4 as Ld,OS as Md,WM as Nd,LS as Od,Xm as Pd,ru as Qd,YM as Rd,gh as Sd,JM as Td,XM as Ud,NS as Vd,ZM as Wd,QM as Xd,eI as Yd,x4 as Zd,A4 as _d,nI as $d,FS as ae,P4 as be,$S as ce,US as de,HS as ee,M4 as fe,BS as ge,eL as he,tL as ie,rL as je,zK as ke,CRe as le,rmt as me,ERe as ne,TRe as oe,nmt as pe,kRe as qe,qK as re,cf as se,WK as te,nL as ue,VK as ve,zS as we,Cbe as xe,$4 as ye,Vi as ze,Hwt as Ae,EN as Be,no as Ce,nw as De,rDe as Ee,TN as Fe,fT as Ge,yi as He,mT as Ie,KJ as Je,sw as Ke,XJ as Le,xf as Me,Hb as Ne,$de as Oe,oi as Pe,c4 as Qe,ff as Re,eY as Se,ss as Te,Syt as Ue,Cyt as Ve,Eyt as We,v0e as Xe,PL as Ye,Tyt as Ze,zE as _e,d8t as $e,fKe as af,hj as bf,wKe as cf,$8t as df,kKe as ef,Pb as ff,pj as gf,mn as hf,TX as if,IN as jf,ON as kf,DN as lf,LN as mf,NN as nf,Nu as of,KDe as pf,YDe as qf,xX as rf,AX as sf,RX as tf,PX as uf,rvt as vf,nvt as wf,yl as xf,ta as yf,Jh as zf,iLe as Af,AT as Bf,Tvt as Cf,cLe as Df,z6e as Ef,Rue as Ff,vh as Gf,_i as Hf,ls as If,Ys as Jf,wae as Kf,Co as Lf,gd as Mf,sVe as Nf,Cp as Of,ur as Pf,Pr as Qf,El as Rf,qOe as Sf,rw as Tf,vN as Uf,jJ as Vf,Ewt as Wf,HJ as Xf,tw as Yf,dT as Zf,SN as _f,CN as $f,zJ as ag,as as bg,CE as cg,Tl as dg,Ia as eg,eGe as fg,H_ as gg,Oi as hg,cVe as ig,Bue as jg,kae as kg,mH as lg,Q_ as mg,Hue as ng,Js as og,FH as pg,HH as qg,J_ as rg,FA as sg,X_ as tg,jH as ug,Lle as vg,$A as wg,UA as xg,zH as yg,iGe as zg,$le as Ag,Ule as Bg,BA as Cg,Hle as Dg,jle as Eg,WH as Fg,Gle as Gg,yGe as Hg,Vle as Ig,wGe as Jg,bGe as Kg,jA as Lg,vGe as Mg,qA as Ng,zue as Og,gc as Pg,que as Qg,KH as Rg,cce as Sg,To as Tg,e4t as Ug,I8e as Vg,t4t as Wg,TR as Xg,O8e as Yg,D8e as Zg,Db as _g,r4t as $g,t5e as ah,r5e as bh,n5e as ch,AR as dh,bE as eh,BRe as fh,Ice as gh,XC as hh,In as ih,Xr as jh,eK as kh,tK as lh,$s as mh,oy as nh,oE as oh,cy as ph,lK as qh,Zi as rh,CAe as sh,cK as th,cE as uh,vl as vh,Zh as wh,uE as xh,tft as yh,rft as zh,BD as Ah,TAe as Bh,nft as Ch,Sl as Dh,kAe as Eh,dK as Fh,hK as Gh,xAe as Hh,AAe as Ih,aE as Jh,RAe as Kh,fK as Lh,PAe as Mh,KAe as Nh,af as Oh,oRe as Ph,MK as Qh,IK as Rh,kpt as Sh,OK as Th,DK as Uh,jD as Vh,Qh as Wh,zD as Xh,ef as Yh,uy as Zh,tf as _h,dy as $h,qD as ai,rf as bi,dn as ci,dE as di,hy as ei,hE as fi,mo as gi,Vx as hi,fc as ii,Cqe as ji,MH as ki,W_ as li,G_ as mi,Ym as ni,Sp as oi,B_ as pi,hX as qi,wDe as ri,lbt as si,bT as ti,_De as ui,TDe as vi,vT as wi,gX as xi,ST as yi,ky as zi,jvt as Ai,Uu as Bi,BN as Ci,IT as Di,hLe as Ei,fLe as Fi,If as Gi,OT as Hi,JX as Ii,$w as Ji,UF as Ki,MFe as Li,$t as Mi,JF as Ni,WQ as Oi,GQ as Pi,YQ as Qi,JQ as Ri,Qf as Si,ep as Ti,QQ as Ui,tp as Vi,DFe as Wi,NFe as Xi,Oee as Yi,Dee as Zi,Qkt as _i,WBe as $i,VBe as aj,xne as bj,YBe as cj,rPt as dj,Dne as ej,uae as fj,wqe as gj,cH as hj,uH as ij,hae as jj,gae as kj,$Mt as lj,Rqe as mj,QF as nj,SA as oj,Iae as pj,vA as qj,Dqe as rj,Lqe as sj,Dp as tj,wue as uj,$p as vj,gR as wj,wb as xj,cue as yj,gb as zj,aue as Aj,I4 as Bj,iI as Cj,Qm as Dj,yh as Ej,wh as Fj,oI as Gj,nu as Hj,jS as Ij,Qn as Jj,N4 as Kj,NK as Lj,FK as Mj,Kpt as Nj,UK as Oj,QOe as Pj,Dwt as Qj,hT as Rj,Lwt as Sj,Rs as Tj,yH as Uj,dj as Vj,YVt as Wj,IR as Xj,v5e as Yj,S5e as Zj,C5e as _j,JVt as $j,Ode as ak,On as bk,pK as ck,Ep as dk,U4 as ek,Ert as fk,K4 as gk,Tbe as hk,kbe as ik,xbe as jk,Art as kk,Mrt as lk,Irt as mk,Ort as nk,Drt as ok,Rbe as pk,Pbe as qk,Brt as rk,J4 as sk,Wrt as tk,YD as uk,JD as vk,Rwt as wk,vbt as xk,xDe as yk,Sbt as zk,_X as Ak,IDe as Bk,Ibt as Ck,PN as Dk,CT as Ek,DDe as Fk,Obt as Gk,Dbt as Hk,LDe as Ik,Lbt as Jk,NDe as Kk,$bt as Lk,MN as Mk,Wbt as Nk,TT as Ok,Pvt as Pk,$X as Qk,UX as Rk,HX as Sk,BX as Tk,jX as Uk,UN as Vk,$u as Wk,zX as Xk,qX as Yk,WX as Zk,MT as _k,GX as $k,VX as al,DT as bl,mw as cl,NT as dl,FT as el,nZ as fl,oZ as gl,SLe as hl,lOt as il,vOt as jl,eb as kl,bFt as ll,WA as ml,AFt as nl,GA as ol,RFt as pl,VA as ql,ace as rl,lce as sl,JFt as tl,XFt as ul,ZFt as vl,QFt as wl,KGe as xl,XA as yl,tR as zl,Ace as Al,kce as Bl,P1t as Cl,D1t as Dl,L1t as El,N1t as Fl,F1t as Gl,W1t as Hl,Y1t as Il,Q1t as Jl,eUt as Kl,tUt as Ll,Z4e as Ml,hue as Nl,mUt as Ol,gUt as Pl,CB as Ql,fue as Rl,_Ut as Sl,bUt as Tl};
2297
+ `}function OKe(){let r=Zn(),e=mhe(r);switch(r.shell){case"cmd":return`Exact cmd.exe command to execute as \`${e}\``;case"powershell":return`Exact PowerShell command to execute as \`${e}\``;case"bash":return`Exact bash command to execute as \`${e}\``;default:return r.shell}}var pj=class r extends Qs{constructor(t){super(r.Name,Cn.SHELL,IKe(),"execute",{type:"object",properties:{command:{type:"string",description:OKe()},is_background:{type:"boolean",description:"Optional: Whether to run the command in background. If not specified, defaults to false (foreground execution). Explicitly set to true for long-running processes like development servers, watchers, or daemons that should continue running without blocking further commands."},timeout:{type:"number",description:"Optional timeout in milliseconds (max 600000)"},description:{type:"string",description:"Brief description of the command for the user. Be specific and concise. Ideally a single sentence. Can be up to 3 sentences for clarity. No line breaks."},directory:{type:"string",description:"(OPTIONAL) The absolute path of the directory to run the command in. If not provided, the project root directory is used. Must be a directory within the workspace and must already exist."}},required:["command"]},!1,!0);this.config=t}static Name=R.SHELL;get maxOutputChars(){return 3e4}validateToolParamValues(t){if(kKe(t),!t.command.trim())return"Command cannot be empty.";if(xKe.test(t.command))return'Command contains leaked tool-argument markup (`<arg_key>` / `<arg_value>`). Put each field in its own JSON property \u2014 e.g. `{ "command": "...", "description": "..." }` \u2014 and do not embed XML-style tags inside the command string.';let n=gr(t.command);if(t.is_background&&TKe(n))return'Background shell commands must not end with a bare "&". Remove the trailing "&" and rely on is_background: true instead.';if(U3(t.command).length===0)return"Could not identify command root to obtain permission from user.";if(t.timeout!==void 0){if(typeof t.timeout!="number"||!Number.isInteger(t.timeout))return"Timeout must be an integer number of milliseconds.";if(t.timeout<=0)return"Timeout must be a positive number.";if(t.timeout>6e5)return"Timeout cannot exceed 600000ms (10 minutes)."}if(t.directory){if(!Ss.isAbsolute(t.directory))return"Directory must be an absolute path.";let s=this.config.storage.getUserSkillsDirs(),o=Ss.resolve(t.directory);if(kj(s,o))return"Explicitly running shell commands from within the user skills directory is not allowed. Please use absolute paths for command parameter instead.";if(!this.config.getWorkspaceContext().getDirectories().some(u=>t.directory.startsWith(u)))return`Directory '${t.directory}' is not within any of the registered workspace directories.`}if(!t.is_background){let s=dhe(n);if(s!==null){let o=s.intentionalSleepRejection??(s.isStandalone?"If you genuinely need a standalone delay (rate limiting, deliberate pacing), add a trailing comment like `# intentional-sleep: wait for MCP rate limit reset` (up to 10 minutes).":"Split into two calls: first `sleep N # intentional-sleep: <reason>` (standalone), then the follow-up command.");return`Blocked: ${s.description}. Run blocking commands in the background with is_background: true. For streaming events (watching logs, polling APIs), use the Monitor tool. `+o}}return null}createInvocation(t){return new Pb(this.config,t)}toAutoClassifierInput(t){return{command:t.command,cwd:t.directory??this.config.getTargetDir()}}};export{qP as a,Zz as b,Mc as c,Ic as d,qd as e,Gt as f,am as g,_v as h,bv as i,ri as j,Gd as k,Fo as l,Vd as m,i7e as n,o7e as o,vv as p,ni as q,cm as r,VP as s,ife as t,Lc as u,Nc as v,$o as w,Fc as x,lq as y,I7e as z,cq as A,YP as B,JP as C,lfe as D,cfe as E,ufe as F,N7e as G,F7e as H,fq as I,mfe as J,Kn as K,hm as L,Nfe as M,kq as N,r0 as O,n0 as P,Uc as Q,xv as R,gm as S,ym as T,Xd as U,kYe as V,Rq as W,Pq as X,Mq as Y,Iq as Z,o0 as _,d0 as $,_m as aa,Va as ba,Yn as ca,bm as da,$Ye as ea,Oq as fa,Av as ga,UYe as ha,HYe as ia,BYe as ja,zd as ka,Pv as la,Qd as ma,Zfe as na,Qfe as oa,VYe as pa,KYe as qa,npe as ra,spe as sa,ape as ta,lpe as ua,YYe as va,Sm as wa,Iv as xa,Ov as ya,Jq as za,Mv as Aa,tW as Ba,v0 as Ca,rW as Da,nW as Ea,Ps as Fa,E0 as Ga,Spe as Ha,S0 as Ia,C0 as Ja,oW as Ka,aW as La,$v as Ma,jc as Na,Fv as Oa,TW as Pa,kW as Qa,H9e as Ra,xW as Sa,B9e as Ta,AW as Ua,Ype as Va,IW as Wa,DW as Xa,LW as Ya,nme as Za,NW as _a,ime as $a,FW as ab,$W as bb,ome as cb,N0 as db,ame as eb,F0 as fb,UW as gb,$0 as hb,U0 as ib,H0 as jb,B0 as kb,j0 as lb,Uv as mb,z0 as nb,q0 as ob,km as pb,ume as qb,dme as rb,hme as sb,fme as tb,Hv as ub,gme as vb,qW as wb,ZJe as xb,Ame as yb,Tm as zb,Ho as Ab,zc as Bb,nh as Cb,KW as Db,YW as Eb,V0 as Fb,qc as Gb,Bo as Hb,tG as Ib,Am as Jb,Gv as Kb,iG as Lb,NXe as Mb,Vv as Nb,oG as Ob,FXe as Pb,Mm as Qb,tM as Rb,bG as Sb,Jv as Tb,Qv as Ub,iM as Vb,oM as Wb,aM as Xb,lM as Yb,Uge as Zb,Bge as _b,PG as $b,jge as ac,qge as bc,IG as cc,Wge as dc,Ja as ec,tS as fc,OG as gc,DZe as hc,LG as ic,uM as jc,NG as kc,FG as lc,wM as mc,Zge as nc,Qge as oc,gM as pc,kn as qc,zG as rc,Xa as sc,lS as tc,cS as uc,ii as vc,Gc as wc,u3 as xc,Wye as yc,Gye as zc,d3 as Ac,Qa as Bc,h3 as Cc,f3 as Dc,p3 as Ec,tl as Fc,dh as Gc,CM as Hc,EM as Ic,TM as Jc,kM as Kc,Um as Lc,xM as Mc,rl as Nc,get as Oc,fh as Pc,Zn as Qc,qwe as Rc,Wm as Sc,zi as Tc,$M as Uc,U3 as Vc,gr as Wc,N3 as Xc,F3 as Yc,CS as Zc,Ret as _c,Qc as $c,Wwe as ad,HM as bd,G3 as cd,Gwe as dd,Gi as ed,Vwe as fd,qo as gd,Pet as hd,Met as id,Iet as jd,V3 as kd,Jc as ld,iwe as md,jo as nd,Xc as od,_S as pd,bS as qd,Zc as rd,Bm as sd,awe as td,M3 as ud,det as vd,hh as wd,dwe as xd,pwe as yd,mwe as zd,gwe as Ad,DM as Bd,zo as Cd,H4 as Dd,B4 as Ed,j4 as Fd,z4 as Gd,aI as Hd,q4 as Id,W4 as Jd,G4 as Kd,V4 as Ld,OS as Md,WM as Nd,LS as Od,Xm as Pd,ru as Qd,YM as Rd,gh as Sd,JM as Td,XM as Ud,NS as Vd,ZM as Wd,QM as Xd,eI as Yd,x4 as Zd,A4 as _d,nI as $d,FS as ae,P4 as be,$S as ce,US as de,HS as ee,M4 as fe,BS as ge,eL as he,tL as ie,rL as je,zK as ke,CRe as le,rmt as me,ERe as ne,TRe as oe,nmt as pe,kRe as qe,qK as re,cf as se,WK as te,nL as ue,VK as ve,zS as we,Cbe as xe,$4 as ye,Vi as ze,Hwt as Ae,EN as Be,no as Ce,VJ as De,nw as Ee,rDe as Fe,TN as Ge,fT as He,yi as Ie,mT as Je,KJ as Ke,sw as Le,XJ as Me,xf as Ne,Hb as Oe,$de as Pe,oi as Qe,c4 as Re,ff as Se,eY as Te,ss as Ue,Syt as Ve,Cyt as We,Eyt as Xe,v0e as Ye,PL as Ze,Tyt as _e,zE as $e,d8t as af,fKe as bf,hj as cf,wKe as df,$8t as ef,kKe as ff,Pb as gf,pj as hf,mn as if,TX as jf,IN as kf,ON as lf,DN as mf,LN as nf,NN as of,Nu as pf,KDe as qf,YDe as rf,xX as sf,AX as tf,RX as uf,PX as vf,rvt as wf,nvt as xf,yl as yf,ta as zf,Jh as Af,iLe as Bf,AT as Cf,Tvt as Df,cLe as Ef,z6e as Ff,Rue as Gf,vh as Hf,_i as If,ls as Jf,Ys as Kf,wae as Lf,Co as Mf,gd as Nf,sVe as Of,Cp as Pf,ur as Qf,Pr as Rf,El as Sf,qOe as Tf,rw as Uf,vN as Vf,jJ as Wf,Ewt as Xf,HJ as Yf,tw as Zf,dT as _f,SN as $f,CN as ag,zJ as bg,as as cg,CE as dg,Tl as eg,Ia as fg,eGe as gg,H_ as hg,Oi as ig,cVe as jg,Bue as kg,kae as lg,mH as mg,Q_ as ng,Hue as og,Js as pg,FH as qg,HH as rg,J_ as sg,FA as tg,X_ as ug,jH as vg,Lle as wg,$A as xg,UA as yg,zH as zg,iGe as Ag,$le as Bg,Ule as Cg,BA as Dg,Hle as Eg,jle as Fg,WH as Gg,Gle as Hg,yGe as Ig,Vle as Jg,wGe as Kg,bGe as Lg,jA as Mg,vGe as Ng,qA as Og,zue as Pg,gc as Qg,que as Rg,KH as Sg,cce as Tg,To as Ug,e4t as Vg,I8e as Wg,t4t as Xg,TR as Yg,O8e as Zg,D8e as _g,Db as $g,r4t as ah,t5e as bh,r5e as ch,n5e as dh,AR as eh,bE as fh,BRe as gh,Ice as hh,XC as ih,In as jh,Xr as kh,eK as lh,tK as mh,$s as nh,oy as oh,oE as ph,cy as qh,lK as rh,Zi as sh,CAe as th,cK as uh,cE as vh,vl as wh,Zh as xh,uE as yh,tft as zh,rft as Ah,BD as Bh,TAe as Ch,nft as Dh,Sl as Eh,kAe as Fh,dK as Gh,hK as Hh,xAe as Ih,AAe as Jh,aE as Kh,RAe as Lh,fK as Mh,PAe as Nh,KAe as Oh,af as Ph,oRe as Qh,MK as Rh,IK as Sh,kpt as Th,OK as Uh,DK as Vh,jD as Wh,Qh as Xh,zD as Yh,ef as Zh,uy as _h,tf as $h,dy as ai,qD as bi,rf as ci,dn as di,dE as ei,hy as fi,hE as gi,mo as hi,Vx as ii,fc as ji,Cqe as ki,MH as li,W_ as mi,G_ as ni,Ym as oi,Sp as pi,B_ as qi,hX as ri,wDe as si,lbt as ti,bT as ui,_De as vi,TDe as wi,vT as xi,gX as yi,ST as zi,ky as Ai,jvt as Bi,Uu as Ci,BN as Di,IT as Ei,hLe as Fi,fLe as Gi,If as Hi,OT as Ii,JX as Ji,$w as Ki,UF as Li,MFe as Mi,$t as Ni,JF as Oi,WQ as Pi,GQ as Qi,YQ as Ri,JQ as Si,Qf as Ti,ep as Ui,QQ as Vi,tp as Wi,DFe as Xi,NFe as Yi,Oee as Zi,Dee as _i,Qkt as $i,WBe as aj,VBe as bj,xne as cj,YBe as dj,rPt as ej,Dne as fj,uae as gj,wqe as hj,cH as ij,uH as jj,hae as kj,gae as lj,$Mt as mj,Rqe as nj,QF as oj,SA as pj,Iae as qj,vA as rj,Dqe as sj,Lqe as tj,Dp as uj,wue as vj,$p as wj,gR as xj,wb as yj,cue as zj,gb as Aj,aue as Bj,I4 as Cj,iI as Dj,Qm as Ej,yh as Fj,wh as Gj,oI as Hj,nu as Ij,jS as Jj,Qn as Kj,N4 as Lj,NK as Mj,FK as Nj,Kpt as Oj,UK as Pj,QOe as Qj,Dwt as Rj,hT as Sj,Lwt as Tj,Rs as Uj,yH as Vj,dj as Wj,YVt as Xj,IR as Yj,v5e as Zj,S5e as _j,C5e as $j,JVt as ak,Ode as bk,On as ck,pK as dk,Ep as ek,U4 as fk,Ert as gk,K4 as hk,Tbe as ik,kbe as jk,xbe as kk,Art as lk,Mrt as mk,Irt as nk,Ort as ok,Drt as pk,Rbe as qk,Pbe as rk,Brt as sk,J4 as tk,Wrt as uk,YD as vk,JD as wk,Rwt as xk,vbt as yk,xDe as zk,Sbt as Ak,_X as Bk,IDe as Ck,Ibt as Dk,PN as Ek,CT as Fk,DDe as Gk,Obt as Hk,Dbt as Ik,LDe as Jk,Lbt as Kk,NDe as Lk,$bt as Mk,MN as Nk,Wbt as Ok,TT as Pk,Pvt as Qk,$X as Rk,UX as Sk,HX as Tk,BX as Uk,jX as Vk,UN as Wk,$u as Xk,zX as Yk,qX as Zk,WX as _k,MT as $k,GX as al,VX as bl,DT as cl,mw as dl,NT as el,FT as fl,nZ as gl,oZ as hl,SLe as il,lOt as jl,vOt as kl,eb as ll,bFt as ml,WA as nl,AFt as ol,GA as pl,RFt as ql,VA as rl,ace as sl,lce as tl,JFt as ul,XFt as vl,ZFt as wl,QFt as xl,KGe as yl,XA as zl,tR as Al,Ace as Bl,kce as Cl,P1t as Dl,D1t as El,L1t as Fl,N1t as Gl,F1t as Hl,W1t as Il,Y1t as Jl,Q1t as Kl,eUt as Ll,tUt as Ml,Z4e as Nl,hue as Ol,mUt as Pl,gUt as Ql,CB as Rl,fue as Sl,_Ut as Tl,bUt as Ul};
2298
2298
  /**
2299
2299
  * @license
2300
2300
  * Copyright 2025 Matilda Team