@anmol-srv/sigil 0.10.3 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +18 -12
- package/README.md +90 -82
- package/dist/cli.js +758 -507
- package/dist/daemon.js +724 -0
- package/dist/hooks/post-tool-use.js +20 -22
- package/dist/hooks/session-end.js +63 -61
- package/dist/hooks/stop.js +76 -74
- package/dist/hooks/user-prompt-submit.js +55 -47
- package/dist/server.js +45 -554
- package/integrations/hermes/README.md +4 -4
- package/integrations/hermes/plugin/README.md +8 -8
- package/knexfile.js +29 -8
- package/package.json +11 -5
- package/src/db/migrations/20260601000000_create-device-table.cjs +34 -0
- package/src/db/migrations/20260601000001_create-pairing-code-table.cjs +27 -0
- package/src/db/migrations/20260601000002_add-fact-provenance.cjs +31 -0
- package/src/db/migrations/20260601000003_add-device-revoked-reason.cjs +19 -0
- package/src/db/migrations/20260601000004_create-trace-event-table.cjs +35 -0
- package/src/db/migrations/20260601000005_add-fact-agent-provenance.cjs +25 -0
- package/src/gui/web/api.js +37 -0
- package/src/gui/web/app.css +947 -0
- package/src/gui/web/app.js +1230 -0
- package/src/gui/web/components.js +90 -0
- package/src/gui/web/design/colors_and_type.css +178 -0
- package/src/gui/web/design/sigil-mark-mono.svg +8 -0
- package/src/gui/web/design/sigil-mark.svg +26 -0
- package/src/gui/web/index.html +536 -0
- package/src/gui/web/sigil.svg +31 -0
- package/src/gui/web/toast.js +62 -0
package/dist/server.js
CHANGED
|
@@ -1,573 +1,64 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var df=Object.defineProperty;var d=(e,t)=>()=>(e&&(t=e(e=0)),t);var G=(e,t)=>{for(var r in t)df(e,r,{get:t[r],enumerable:!0})};var vp,zr,Gn=d(()=>{vp=typeof global=="object"&&global&&global.Object===Object&&global,zr=vp});var bp,Tp,B,ge=d(()=>{Gn();bp=typeof self=="object"&&self&&self.Object===Object&&self,Tp=zr||bp||Function("return this")(),B=Tp});var Sp,K,Dt=d(()=>{ge();Sp=B.Symbol,K=Sp});function Ip(e){var t=Ap.call(e,mr),r=e[mr];try{e[mr]=void 0;var n=!0}catch{}var o=Op.call(e);return n&&(t?e[mr]=r:delete e[mr]),o}var xa,Ap,Op,mr,wa,Ea=d(()=>{Dt();xa=Object.prototype,Ap=xa.hasOwnProperty,Op=xa.toString,mr=K?K.toStringTag:void 0;wa=Ip});function Rp(e){return Np.call(e)}var Cp,Np,va,ba=d(()=>{Cp=Object.prototype,Np=Cp.toString;va=Rp});function Dp(e){return e==null?e===void 0?Lp:kp:Ta&&Ta in Object(e)?wa(e):va(e)}var kp,Lp,Ta,ue,Pt=d(()=>{Dt();Ea();ba();kp="[object Null]",Lp="[object Undefined]",Ta=K?K.toStringTag:void 0;ue=Dp});function Pp(e){return e!=null&&typeof e=="object"}var le,$t=d(()=>{le=Pp});function Mp(e){return typeof e=="symbol"||le(e)&&ue(e)==$p}var $p,de,Mt=d(()=>{Pt();$t();$p="[object Symbol]";de=Mp});function Fp(e,t){for(var r=-1,n=e==null?0:e.length,o=Array(n);++r<n;)o[r]=t(e[r],r,e);return o}var Ft,Yn=d(()=>{Ft=Fp});var jp,M,oe=d(()=>{jp=Array.isArray,M=jp});function Oa(e){if(typeof e=="string")return e;if(M(e))return Ft(e,Oa)+"";if(de(e))return Aa?Aa.call(e):"";var t=e+"";return t=="0"&&1/e==-Bp?"-0":t}var Bp,Sa,Aa,Ia,Ca=d(()=>{Dt();Yn();oe();Mt();Bp=1/0,Sa=K?K.prototype:void 0,Aa=Sa?Sa.toString:void 0;Ia=Oa});function Hp(e){for(var t=e.length;t--&&Up.test(e.charAt(t)););return t}var Up,Na,Ra=d(()=>{Up=/\s/;Na=Hp});function Gp(e){return e&&e.slice(0,Na(e)+1).replace(Wp,"")}var Wp,ka,La=d(()=>{Ra();Wp=/^\s+/;ka=Gp});function Yp(e){var t=typeof e;return e!=null&&(t=="object"||t=="function")}var fe,jt=d(()=>{fe=Yp});function Zp(e){if(typeof e=="number")return e;if(de(e))return Da;if(fe(e)){var t=typeof e.valueOf=="function"?e.valueOf():e;e=fe(t)?t+"":t}if(typeof e!="string")return e===0?e:+e;e=ka(e);var r=zp.test(e);return r||Kp.test(e)?qp(e.slice(2),r?2:8):Vp.test(e)?Da:+e}var Da,Vp,zp,Kp,qp,Pa,$a=d(()=>{La();jt();Mt();Da=NaN,Vp=/^[-+]0x[0-9a-f]+$/i,zp=/^0b[01]+$/i,Kp=/^0o[0-7]+$/i,qp=parseInt;Pa=Zp});function Xp(e){if(!e)return e===0?e:0;if(e=Pa(e),e===Ma||e===-Ma){var t=e<0?-1:1;return t*Jp}return e===e?e:0}var Ma,Jp,Fa,ja=d(()=>{$a();Ma=1/0,Jp=17976931348623157e292;Fa=Xp});function Qp(e){var t=Fa(e),r=t%1;return t===t?r?t-r:t:0}var Ba,Ua=d(()=>{ja();Ba=Qp});function em(e){return e}var $e,hr=d(()=>{$e=em});function am(e){if(!fe(e))return!1;var t=ue(e);return t==rm||t==nm||t==tm||t==om}var tm,rm,nm,om,Kr,Vn=d(()=>{Pt();jt();tm="[object AsyncFunction]",rm="[object Function]",nm="[object GeneratorFunction]",om="[object Proxy]";Kr=am});var im,qr,Ha=d(()=>{ge();im=B["__core-js_shared__"],qr=im});function sm(e){return!!Wa&&Wa in e}var Wa,Ga,Ya=d(()=>{Ha();Wa=(function(){var e=/[^.]+$/.exec(qr&&qr.keys&&qr.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""})();Ga=sm});function lm(e){if(e!=null){try{return um.call(e)}catch{}try{return e+""}catch{}}return""}var cm,um,Ie,zn=d(()=>{cm=Function.prototype,um=cm.toString;Ie=lm});function _m(e){if(!fe(e)||Ga(e))return!1;var t=Kr(e)?gm:fm;return t.test(Ie(e))}var dm,fm,pm,mm,hm,ym,gm,Va,za=d(()=>{Vn();Ya();jt();zn();dm=/[\\^$.*+?()[\]{}|]/g,fm=/^\[object .+?Constructor\]$/,pm=Function.prototype,mm=Object.prototype,hm=pm.toString,ym=mm.hasOwnProperty,gm=RegExp("^"+hm.call(ym).replace(dm,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");Va=_m});function xm(e,t){return e?.[t]}var Ka,qa=d(()=>{Ka=xm});function wm(e,t){var r=Ka(e,t);return Va(r)?r:void 0}var Q,Me=d(()=>{za();qa();Q=wm});var Em,Zr,Za=d(()=>{Me();ge();Em=Q(B,"WeakMap"),Zr=Em});function vm(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}var Ja,Xa=d(()=>{Ja=vm});function bm(){}var Qa,ei=d(()=>{Qa=bm});function Om(e){var t=0,r=0;return function(){var n=Am(),o=Sm-(n-r);if(r=n,o>0){if(++t>=Tm)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var Tm,Sm,Am,ti,ri=d(()=>{Tm=800,Sm=16,Am=Date.now;ti=Om});function Im(e){return function(){return e}}var ni,oi=d(()=>{ni=Im});var Cm,Bt,Kn=d(()=>{Me();Cm=(function(){try{var e=Q(Object,"defineProperty");return e({},"",{}),e}catch{}})(),Bt=Cm});var Nm,ai,ii=d(()=>{oi();Kn();hr();Nm=Bt?function(e,t){return Bt(e,"toString",{configurable:!0,enumerable:!1,value:ni(t),writable:!0})}:$e,ai=Nm});var Rm,si,ci=d(()=>{ii();ri();Rm=ti(ai),si=Rm});function km(e,t,r,n){for(var o=e.length,a=r+(n?1:-1);n?a--:++a<o;)if(t(e[a],a,e))return a;return-1}var ui,li=d(()=>{ui=km});function Lm(e){return e!==e}var di,fi=d(()=>{di=Lm});function Dm(e,t,r){for(var n=r-1,o=e.length;++n<o;)if(e[n]===t)return n;return-1}var pi,mi=d(()=>{pi=Dm});function Pm(e,t,r){return t===t?pi(e,t,r):ui(e,di,r)}var hi,yi=d(()=>{li();fi();mi();hi=Pm});function $m(e,t){var r=e==null?0:e.length;return!!r&&hi(e,t,0)>-1}var gi,_i=d(()=>{yi();gi=$m});function jm(e,t){var r=typeof e;return t=t??Mm,!!t&&(r=="number"||r!="symbol"&&Fm.test(e))&&e>-1&&e%1==0&&e<t}var Mm,Fm,Ut,Jr=d(()=>{Mm=9007199254740991,Fm=/^(?:0|[1-9]\d*)$/;Ut=jm});function Bm(e,t,r){t=="__proto__"&&Bt?Bt(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}var xi,wi=d(()=>{Kn();xi=Bm});function Um(e,t){return e===t||e!==e&&t!==t}var Ht,Xr=d(()=>{Ht=Um});function Hm(e,t,r){return t=Ei(t===void 0?e.length-1:t,0),function(){for(var n=arguments,o=-1,a=Ei(n.length-t,0),i=Array(a);++o<a;)i[o]=n[t+o];o=-1;for(var s=Array(t+1);++o<t;)s[o]=n[o];return s[t]=r(i),Ja(e,this,s)}}var Ei,vi,bi=d(()=>{Xa();Ei=Math.max;vi=Hm});function Wm(e,t){return si(vi(e,t,$e),e+"")}var Ti,Si=d(()=>{hr();bi();ci();Ti=Wm});function Ym(e){return typeof e=="number"&&e>-1&&e%1==0&&e<=Gm}var Gm,Wt,Qr=d(()=>{Gm=9007199254740991;Wt=Ym});function Vm(e){return e!=null&&Wt(e.length)&&!Kr(e)}var Fe,yr=d(()=>{Vn();Qr();Fe=Vm});function zm(e,t,r){if(!fe(r))return!1;var n=typeof t;return(n=="number"?Fe(r)&&Ut(t,r.length):n=="string"&&t in r)?Ht(r[t],e):!1}var gr,qn=d(()=>{Xr();yr();Jr();jt();gr=zm});function qm(e){var t=e&&e.constructor,r=typeof t=="function"&&t.prototype||Km;return e===r}var Km,Ai,Oi=d(()=>{Km=Object.prototype;Ai=qm});function Zm(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}var Ii,Ci=d(()=>{Ii=Zm});function Xm(e){return le(e)&&ue(e)==Jm}var Jm,Zn,Ni=d(()=>{Pt();$t();Jm="[object Arguments]";Zn=Xm});var Ri,Qm,eh,th,Gt,en=d(()=>{Ni();$t();Ri=Object.prototype,Qm=Ri.hasOwnProperty,eh=Ri.propertyIsEnumerable,th=Zn((function(){return arguments})())?Zn:function(e){return le(e)&&Qm.call(e,"callee")&&!eh.call(e,"callee")},Gt=th});function rh(){return!1}var ki,Li=d(()=>{ki=rh});var $i,Di,nh,Pi,oh,ah,_r,Jn=d(()=>{ge();Li();$i=typeof exports=="object"&&exports&&!exports.nodeType&&exports,Di=$i&&typeof module=="object"&&module&&!module.nodeType&&module,nh=Di&&Di.exports===$i,Pi=nh?B.Buffer:void 0,oh=Pi?Pi.isBuffer:void 0,ah=oh||ki,_r=ah});function Nh(e){return le(e)&&Wt(e.length)&&!!$[ue(e)]}var ih,sh,ch,uh,lh,dh,fh,ph,mh,hh,yh,gh,_h,xh,wh,Eh,vh,bh,Th,Sh,Ah,Oh,Ih,Ch,$,Mi,Fi=d(()=>{Pt();Qr();$t();ih="[object Arguments]",sh="[object Array]",ch="[object Boolean]",uh="[object Date]",lh="[object Error]",dh="[object Function]",fh="[object Map]",ph="[object Number]",mh="[object Object]",hh="[object RegExp]",yh="[object Set]",gh="[object String]",_h="[object WeakMap]",xh="[object ArrayBuffer]",wh="[object DataView]",Eh="[object Float32Array]",vh="[object Float64Array]",bh="[object Int8Array]",Th="[object Int16Array]",Sh="[object Int32Array]",Ah="[object Uint8Array]",Oh="[object Uint8ClampedArray]",Ih="[object Uint16Array]",Ch="[object Uint32Array]",$={};$[Eh]=$[vh]=$[bh]=$[Th]=$[Sh]=$[Ah]=$[Oh]=$[Ih]=$[Ch]=!0;$[ih]=$[sh]=$[xh]=$[ch]=$[wh]=$[uh]=$[lh]=$[dh]=$[fh]=$[ph]=$[mh]=$[hh]=$[yh]=$[gh]=$[_h]=!1;Mi=Nh});function Rh(e){return function(t){return e(t)}}var tn,Xn=d(()=>{tn=Rh});var ji,xr,kh,Qn,Lh,eo,Bi=d(()=>{Gn();ji=typeof exports=="object"&&exports&&!exports.nodeType&&exports,xr=ji&&typeof module=="object"&&module&&!module.nodeType&&module,kh=xr&&xr.exports===ji,Qn=kh&&zr.process,Lh=(function(){try{var e=xr&&xr.require&&xr.require("util").types;return e||Qn&&Qn.binding&&Qn.binding("util")}catch{}})(),eo=Lh});var Ui,Dh,rn,to=d(()=>{Fi();Xn();Bi();Ui=eo&&eo.isTypedArray,Dh=Ui?tn(Ui):Mi,rn=Dh});function Mh(e,t){var r=M(e),n=!r&&Gt(e),o=!r&&!n&&_r(e),a=!r&&!n&&!o&&rn(e),i=r||n||o||a,s=i?Ii(e.length,String):[],c=s.length;for(var u in e)(t||$h.call(e,u))&&!(i&&(u=="length"||o&&(u=="offset"||u=="parent")||a&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||Ut(u,c)))&&s.push(u);return s}var Ph,$h,Hi,Wi=d(()=>{Ci();en();oe();Jn();Jr();to();Ph=Object.prototype,$h=Ph.hasOwnProperty;Hi=Mh});function Fh(e,t){return function(r){return e(t(r))}}var Gi,Yi=d(()=>{Gi=Fh});var jh,Vi,zi=d(()=>{Yi();jh=Gi(Object.keys,Object),Vi=jh});function Hh(e){if(!Ai(e))return Vi(e);var t=[];for(var r in Object(e))Uh.call(e,r)&&r!="constructor"&&t.push(r);return t}var Bh,Uh,Ki,qi=d(()=>{Oi();zi();Bh=Object.prototype,Uh=Bh.hasOwnProperty;Ki=Hh});function Wh(e){return Fe(e)?Hi(e):Ki(e)}var Yt,nn=d(()=>{Wi();qi();yr();Yt=Wh});function Vh(e,t){if(M(e))return!1;var r=typeof e;return r=="number"||r=="symbol"||r=="boolean"||e==null||de(e)?!0:Yh.test(e)||!Gh.test(e)||t!=null&&e in Object(t)}var Gh,Yh,Vt,on=d(()=>{oe();Mt();Gh=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Yh=/^\w*$/;Vt=Vh});var zh,Ce,wr=d(()=>{Me();zh=Q(Object,"create"),Ce=zh});function Kh(){this.__data__=Ce?Ce(null):{},this.size=0}var Zi,Ji=d(()=>{wr();Zi=Kh});function qh(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}var Xi,Qi=d(()=>{Xi=qh});function Qh(e){var t=this.__data__;if(Ce){var r=t[e];return r===Zh?void 0:r}return Xh.call(t,e)?t[e]:void 0}var Zh,Jh,Xh,es,ts=d(()=>{wr();Zh="__lodash_hash_undefined__",Jh=Object.prototype,Xh=Jh.hasOwnProperty;es=Qh});function ry(e){var t=this.__data__;return Ce?t[e]!==void 0:ty.call(t,e)}var ey,ty,rs,ns=d(()=>{wr();ey=Object.prototype,ty=ey.hasOwnProperty;rs=ry});function oy(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=Ce&&t===void 0?ny:t,this}var ny,os,as=d(()=>{wr();ny="__lodash_hash_undefined__";os=oy});function zt(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}var ro,is=d(()=>{Ji();Qi();ts();ns();as();zt.prototype.clear=Zi;zt.prototype.delete=Xi;zt.prototype.get=es;zt.prototype.has=rs;zt.prototype.set=os;ro=zt});function ay(){this.__data__=[],this.size=0}var ss,cs=d(()=>{ss=ay});function iy(e,t){for(var r=e.length;r--;)if(Ht(e[r][0],t))return r;return-1}var je,Er=d(()=>{Xr();je=iy});function uy(e){var t=this.__data__,r=je(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():cy.call(t,r,1),--this.size,!0}var sy,cy,us,ls=d(()=>{Er();sy=Array.prototype,cy=sy.splice;us=uy});function ly(e){var t=this.__data__,r=je(t,e);return r<0?void 0:t[r][1]}var ds,fs=d(()=>{Er();ds=ly});function dy(e){return je(this.__data__,e)>-1}var ps,ms=d(()=>{Er();ps=dy});function fy(e,t){var r=this.__data__,n=je(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}var hs,ys=d(()=>{Er();hs=fy});function Kt(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}var Be,vr=d(()=>{cs();ls();fs();ms();ys();Kt.prototype.clear=ss;Kt.prototype.delete=us;Kt.prototype.get=ds;Kt.prototype.has=ps;Kt.prototype.set=hs;Be=Kt});var py,Ue,an=d(()=>{Me();ge();py=Q(B,"Map"),Ue=py});function my(){this.size=0,this.__data__={hash:new ro,map:new(Ue||Be),string:new ro}}var gs,_s=d(()=>{is();vr();an();gs=my});function hy(e){var t=typeof e;return t=="string"||t=="number"||t=="symbol"||t=="boolean"?e!=="__proto__":e===null}var xs,ws=d(()=>{xs=hy});function yy(e,t){var r=e.__data__;return xs(t)?r[typeof t=="string"?"string":"hash"]:r.map}var He,br=d(()=>{ws();He=yy});function gy(e){var t=He(this,e).delete(e);return this.size-=t?1:0,t}var Es,vs=d(()=>{br();Es=gy});function _y(e){return He(this,e).get(e)}var bs,Ts=d(()=>{br();bs=_y});function xy(e){return He(this,e).has(e)}var Ss,As=d(()=>{br();Ss=xy});function wy(e,t){var r=He(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}var Os,Is=d(()=>{br();Os=wy});function qt(e){var t=-1,r=e==null?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}var ht,sn=d(()=>{_s();vs();Ts();As();Is();qt.prototype.clear=gs;qt.prototype.delete=Es;qt.prototype.get=bs;qt.prototype.has=Ss;qt.prototype.set=Os;ht=qt});function no(e,t){if(typeof e!="function"||t!=null&&typeof t!="function")throw new TypeError(Ey);var r=function(){var n=arguments,o=t?t.apply(this,n):n[0],a=r.cache;if(a.has(o))return a.get(o);var i=e.apply(this,n);return r.cache=a.set(o,i)||a,i};return r.cache=new(no.Cache||ht),r}var Ey,Cs,Ns=d(()=>{sn();Ey="Expected a function";no.Cache=ht;Cs=no});function by(e){var t=Cs(e,function(n){return r.size===vy&&r.clear(),n}),r=t.cache;return t}var vy,Rs,ks=d(()=>{Ns();vy=500;Rs=by});var Ty,Sy,Ay,Ls,Ds=d(()=>{ks();Ty=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Sy=/\\(\\)?/g,Ay=Rs(function(e){var t=[];return e.charCodeAt(0)===46&&t.push(""),e.replace(Ty,function(r,n,o,a){t.push(o?a.replace(Sy,"$1"):n||r)}),t}),Ls=Ay});function Oy(e){return e==null?"":Ia(e)}var Ps,$s=d(()=>{Ca();Ps=Oy});function Iy(e,t){return M(e)?e:Vt(e,t)?[e]:Ls(Ps(e))}var cn,oo=d(()=>{oe();on();Ds();$s();cn=Iy});function Ny(e){if(typeof e=="string"||de(e))return e;var t=e+"";return t=="0"&&1/e==-Cy?"-0":t}var Cy,We,Tr=d(()=>{Mt();Cy=1/0;We=Ny});function Ry(e,t){t=cn(t,e);for(var r=0,n=t.length;e!=null&&r<n;)e=e[We(t[r++])];return r&&r==n?e:void 0}var Zt,un=d(()=>{oo();Tr();Zt=Ry});function ky(e,t,r){var n=e==null?void 0:Zt(e,t);return n===void 0?r:n}var Ms,Fs=d(()=>{un();Ms=ky});function Ly(e,t){for(var r=-1,n=t.length,o=e.length;++r<n;)e[o+r]=t[r];return e}var ln,ao=d(()=>{ln=Ly});function Dy(e){return M(e)||Gt(e)||!!(js&&e&&e[js])}var js,Bs,Us=d(()=>{Dt();en();oe();js=K?K.isConcatSpreadable:void 0;Bs=Dy});function Hs(e,t,r,n,o){var a=-1,i=e.length;for(r||(r=Bs),o||(o=[]);++a<i;){var s=e[a];t>0&&r(s)?t>1?Hs(s,t-1,r,n,o):ln(o,s):n||(o[o.length]=s)}return o}var Ws,Gs=d(()=>{ao();Us();Ws=Hs});function Py(e,t,r){var n=-1,o=e.length;t<0&&(t=-t>o?0:o+t),r=r>o?o:r,r<0&&(r+=o),o=t>r?0:r-t>>>0,t>>>=0;for(var a=Array(o);++n<o;)a[n]=e[n+t];return a}var Ys,Vs=d(()=>{Ys=Py});function Fy(e,t,r){(r?gr(e,t,r):t===void 0)?t=1:t=My(Ba(t),0);var n=e==null?0:e.length;if(!n||t<1)return[];for(var o=0,a=0,i=Array($y(n/t));o<n;)i[a++]=Ys(e,o,o+=t);return i}var $y,My,io,zs=d(()=>{Vs();qn();Ua();$y=Math.ceil,My=Math.max;io=Fy});function jy(){this.__data__=new Be,this.size=0}var Ks,qs=d(()=>{vr();Ks=jy});function By(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}var Zs,Js=d(()=>{Zs=By});function Uy(e){return this.__data__.get(e)}var Xs,Qs=d(()=>{Xs=Uy});function Hy(e){return this.__data__.has(e)}var ec,tc=d(()=>{ec=Hy});function Gy(e,t){var r=this.__data__;if(r instanceof Be){var n=r.__data__;if(!Ue||n.length<Wy-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new ht(n)}return r.set(e,t),this.size=r.size,this}var Wy,rc,nc=d(()=>{vr();an();sn();Wy=200;rc=Gy});function Jt(e){var t=this.__data__=new Be(e);this.size=t.size}var Xt,so=d(()=>{vr();qs();Js();Qs();tc();nc();Jt.prototype.clear=Ks;Jt.prototype.delete=Zs;Jt.prototype.get=Xs;Jt.prototype.has=ec;Jt.prototype.set=rc;Xt=Jt});function Yy(e,t){for(var r=-1,n=e==null?0:e.length,o=0,a=[];++r<n;){var i=e[r];t(i,r,e)&&(a[o++]=i)}return a}var oc,ac=d(()=>{oc=Yy});function Vy(){return[]}var ic,sc=d(()=>{ic=Vy});var zy,Ky,cc,qy,uc,lc=d(()=>{ac();sc();zy=Object.prototype,Ky=zy.propertyIsEnumerable,cc=Object.getOwnPropertySymbols,qy=cc?function(e){return e==null?[]:(e=Object(e),oc(cc(e),function(t){return Ky.call(e,t)}))}:ic,uc=qy});function Zy(e,t,r){var n=t(e);return M(e)?n:ln(n,r(e))}var dc,fc=d(()=>{ao();oe();dc=Zy});function Jy(e){return dc(e,Yt,uc)}var co,pc=d(()=>{fc();lc();nn();co=Jy});var Xy,dn,mc=d(()=>{Me();ge();Xy=Q(B,"DataView"),dn=Xy});var Qy,fn,hc=d(()=>{Me();ge();Qy=Q(B,"Promise"),fn=Qy});var eg,Ge,uo=d(()=>{Me();ge();eg=Q(B,"Set"),Ge=eg});var yc,tg,gc,_c,xc,wc,rg,ng,og,ag,ig,yt,lo,Ec=d(()=>{mc();an();hc();uo();Za();Pt();zn();yc="[object Map]",tg="[object Object]",gc="[object Promise]",_c="[object Set]",xc="[object WeakMap]",wc="[object DataView]",rg=Ie(dn),ng=Ie(Ue),og=Ie(fn),ag=Ie(Ge),ig=Ie(Zr),yt=ue;(dn&&yt(new dn(new ArrayBuffer(1)))!=wc||Ue&&yt(new Ue)!=yc||fn&&yt(fn.resolve())!=gc||Ge&&yt(new Ge)!=_c||Zr&&yt(new Zr)!=xc)&&(yt=function(e){var t=ue(e),r=t==tg?e.constructor:void 0,n=r?Ie(r):"";if(n)switch(n){case rg:return wc;case ng:return yc;case og:return gc;case ag:return _c;case ig:return xc}return t});lo=yt});var sg,fo,vc=d(()=>{ge();sg=B.Uint8Array,fo=sg});function ug(e){return this.__data__.set(e,cg),this}var cg,bc,Tc=d(()=>{cg="__lodash_hash_undefined__";bc=ug});function lg(e){return this.__data__.has(e)}var Sc,Ac=d(()=>{Sc=lg});function pn(e){var t=-1,r=e==null?0:e.length;for(this.__data__=new ht;++t<r;)this.add(e[t])}var mn,po=d(()=>{sn();Tc();Ac();pn.prototype.add=pn.prototype.push=bc;pn.prototype.has=Sc;mn=pn});function dg(e,t){for(var r=-1,n=e==null?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}var Oc,Ic=d(()=>{Oc=dg});function fg(e,t){return e.has(t)}var hn,mo=d(()=>{hn=fg});function hg(e,t,r,n,o,a){var i=r&pg,s=e.length,c=t.length;if(s!=c&&!(i&&c>s))return!1;var u=a.get(e),l=a.get(t);if(u&&l)return u==t&&l==e;var p=-1,f=!0,h=r&mg?new mn:void 0;for(a.set(e,t),a.set(t,e);++p<s;){var _=e[p],E=t[p];if(n)var x=i?n(E,_,p,t,e,a):n(_,E,p,e,t,a);if(x!==void 0){if(x)continue;f=!1;break}if(h){if(!Oc(t,function(O,N){if(!hn(h,N)&&(_===O||o(_,O,r,n,a)))return h.push(N)})){f=!1;break}}else if(!(_===E||o(_,E,r,n,a))){f=!1;break}}return a.delete(e),a.delete(t),f}var pg,mg,yn,ho=d(()=>{po();Ic();mo();pg=1,mg=2;yn=hg});function yg(e){var t=-1,r=Array(e.size);return e.forEach(function(n,o){r[++t]=[o,n]}),r}var Cc,Nc=d(()=>{Cc=yg});function gg(e){var t=-1,r=Array(e.size);return e.forEach(function(n){r[++t]=n}),r}var Qt,gn=d(()=>{Qt=gg});function Rg(e,t,r,n,o,a,i){switch(r){case Ng:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case Cg:return!(e.byteLength!=t.byteLength||!a(new fo(e),new fo(t)));case wg:case Eg:case Tg:return Ht(+e,+t);case vg:return e.name==t.name&&e.message==t.message;case Sg:case Og:return e==t+"";case bg:var s=Cc;case Ag:var c=n&_g;if(s||(s=Qt),e.size!=t.size&&!c)return!1;var u=i.get(e);if(u)return u==t;n|=xg,i.set(e,t);var l=yn(s(e),s(t),n,o,a,i);return i.delete(e),l;case Ig:if(yo)return yo.call(e)==yo.call(t)}return!1}var _g,xg,wg,Eg,vg,bg,Tg,Sg,Ag,Og,Ig,Cg,Ng,Rc,yo,kc,Lc=d(()=>{Dt();vc();Xr();ho();Nc();gn();_g=1,xg=2,wg="[object Boolean]",Eg="[object Date]",vg="[object Error]",bg="[object Map]",Tg="[object Number]",Sg="[object RegExp]",Ag="[object Set]",Og="[object String]",Ig="[object Symbol]",Cg="[object ArrayBuffer]",Ng="[object DataView]",Rc=K?K.prototype:void 0,yo=Rc?Rc.valueOf:void 0;kc=Rg});function Pg(e,t,r,n,o,a){var i=r&kg,s=co(e),c=s.length,u=co(t),l=u.length;if(c!=l&&!i)return!1;for(var p=c;p--;){var f=s[p];if(!(i?f in t:Dg.call(t,f)))return!1}var h=a.get(e),_=a.get(t);if(h&&_)return h==t&&_==e;var E=!0;a.set(e,t),a.set(t,e);for(var x=i;++p<c;){f=s[p];var O=e[f],N=t[f];if(n)var F=i?n(N,O,f,t,e,a):n(O,N,f,e,t,a);if(!(F===void 0?O===N||o(O,N,r,n,a):F)){E=!1;break}x||(x=f=="constructor")}if(E&&!x){var j=e.constructor,k=t.constructor;j!=k&&"constructor"in e&&"constructor"in t&&!(typeof j=="function"&&j instanceof j&&typeof k=="function"&&k instanceof k)&&(E=!1)}return a.delete(e),a.delete(t),E}var kg,Lg,Dg,Dc,Pc=d(()=>{pc();kg=1,Lg=Object.prototype,Dg=Lg.hasOwnProperty;Dc=Pg});function Fg(e,t,r,n,o,a){var i=M(e),s=M(t),c=i?Mc:lo(e),u=s?Mc:lo(t);c=c==$c?_n:c,u=u==$c?_n:u;var l=c==_n,p=u==_n,f=c==u;if(f&&_r(e)){if(!_r(t))return!1;i=!0,l=!1}if(f&&!l)return a||(a=new Xt),i||rn(e)?yn(e,t,r,n,o,a):kc(e,t,c,r,n,o,a);if(!(r&$g)){var h=l&&Fc.call(e,"__wrapped__"),_=p&&Fc.call(t,"__wrapped__");if(h||_){var E=h?e.value():e,x=_?t.value():t;return a||(a=new Xt),o(E,x,r,n,a)}}return f?(a||(a=new Xt),Dc(e,t,r,n,o,a)):!1}var $g,$c,Mc,_n,Mg,Fc,jc,Bc=d(()=>{so();ho();Lc();Pc();Ec();oe();Jn();to();$g=1,$c="[object Arguments]",Mc="[object Array]",_n="[object Object]",Mg=Object.prototype,Fc=Mg.hasOwnProperty;jc=Fg});function Uc(e,t,r,n,o){return e===t?!0:e==null||t==null||!le(e)&&!le(t)?e!==e&&t!==t:jc(e,t,r,n,Uc,o)}var xn,go=d(()=>{Bc();$t();xn=Uc});function Ug(e,t,r,n){var o=r.length,a=o,i=!n;if(e==null)return!a;for(e=Object(e);o--;){var s=r[o];if(i&&s[2]?s[1]!==e[s[0]]:!(s[0]in e))return!1}for(;++o<a;){s=r[o];var c=s[0],u=e[c],l=s[1];if(i&&s[2]){if(u===void 0&&!(c in e))return!1}else{var p=new Xt;if(n)var f=n(u,l,c,e,t,p);if(!(f===void 0?xn(l,u,jg|Bg,n,p):f))return!1}}return!0}var jg,Bg,Hc,Wc=d(()=>{so();go();jg=1,Bg=2;Hc=Ug});function Hg(e){return e===e&&!fe(e)}var wn,_o=d(()=>{jt();wn=Hg});function Wg(e){for(var t=Yt(e),r=t.length;r--;){var n=t[r],o=e[n];t[r]=[n,o,wn(o)]}return t}var Gc,Yc=d(()=>{_o();nn();Gc=Wg});function Gg(e,t){return function(r){return r==null?!1:r[e]===t&&(t!==void 0||e in Object(r))}}var En,xo=d(()=>{En=Gg});function Yg(e){var t=Gc(e);return t.length==1&&t[0][2]?En(t[0][0],t[0][1]):function(r){return r===e||Hc(r,e,t)}}var Vc,zc=d(()=>{Wc();Yc();xo();Vc=Yg});function Vg(e,t){return e!=null&&t in Object(e)}var Kc,qc=d(()=>{Kc=Vg});function zg(e,t,r){t=cn(t,e);for(var n=-1,o=t.length,a=!1;++n<o;){var i=We(t[n]);if(!(a=e!=null&&r(e,i)))break;e=e[i]}return a||++n!=o?a:(o=e==null?0:e.length,!!o&&Wt(o)&&Ut(i,o)&&(M(e)||Gt(e)))}var Zc,Jc=d(()=>{oo();en();oe();Jr();Qr();Tr();Zc=zg});function Kg(e,t){return e!=null&&Zc(e,t,Kc)}var Xc,Qc=d(()=>{qc();Jc();Xc=Kg});function Jg(e,t){return Vt(e)&&wn(t)?En(We(e),t):function(r){var n=Ms(r,e);return n===void 0&&n===t?Xc(r,e):xn(t,n,qg|Zg)}}var qg,Zg,eu,tu=d(()=>{go();Fs();Qc();on();_o();xo();Tr();qg=1,Zg=2;eu=Jg});function Xg(e){return function(t){return t?.[e]}}var ru,nu=d(()=>{ru=Xg});function Qg(e){return function(t){return Zt(t,e)}}var ou,au=d(()=>{un();ou=Qg});function e_(e){return Vt(e)?ru(We(e)):ou(e)}var iu,su=d(()=>{nu();au();on();Tr();iu=e_});function t_(e){return typeof e=="function"?e:e==null?$e:typeof e=="object"?M(e)?eu(e[0],e[1]):Vc(e):iu(e)}var Ye,Sr=d(()=>{zc();tu();hr();oe();su();Ye=t_});function r_(e,t,r,n){for(var o=-1,a=e==null?0:e.length;++o<a;){var i=e[o];t(n,i,r(i),e)}return n}var cu,uu=d(()=>{cu=r_});function n_(e){return function(t,r,n){for(var o=-1,a=Object(t),i=n(t),s=i.length;s--;){var c=i[e?s:++o];if(r(a[c],c,a)===!1)break}return t}}var lu,du=d(()=>{lu=n_});var o_,fu,pu=d(()=>{du();o_=lu(),fu=o_});function a_(e,t){return e&&fu(e,t,Yt)}var mu,hu=d(()=>{pu();nn();mu=a_});function i_(e,t){return function(r,n){if(r==null)return r;if(!Fe(r))return e(r,n);for(var o=r.length,a=t?o:-1,i=Object(r);(t?a--:++a<o)&&n(i[a],a,i)!==!1;);return r}}var yu,gu=d(()=>{yr();yu=i_});var s_,vn,wo=d(()=>{hu();gu();s_=yu(mu),vn=s_});function c_(e,t,r,n){return vn(e,function(o,a,i){t(n,o,r(o),i)}),n}var _u,xu=d(()=>{wo();_u=c_});function u_(e,t){return function(r,n){var o=M(r)?cu:_u,a=t?t():{};return o(r,e,Ye(n,2),a)}}var wu,Eu=d(()=>{uu();xu();Sr();oe();wu=u_});function l_(e,t,r){for(var n=-1,o=e==null?0:e.length;++n<o;)if(r(t,e[n]))return!0;return!1}var vu,bu=d(()=>{vu=l_});function d_(e,t){var r=-1,n=Fe(e)?Array(e.length):[];return vn(e,function(o,a,i){n[++r]=t(o,a,i)}),n}var Tu,Su=d(()=>{wo();yr();Tu=d_});var f_,p_,m_,gt,Au=d(()=>{wi();Eu();f_=Object.prototype,p_=f_.hasOwnProperty,m_=wu(function(e,t,r){p_.call(e,r)?e[r].push(t):xi(e,r,[t])}),gt=m_});function h_(e,t){for(var r,n=-1,o=e.length;++n<o;){var a=t(e[n]);a!==void 0&&(r=r===void 0?a:r+a)}return r}var Ou,Iu=d(()=>{Ou=h_});function y_(e,t){var r=e.length;for(e.sort(t);r--;)e[r]=e[r].value;return e}var Cu,Nu=d(()=>{Cu=y_});function g_(e,t){if(e!==t){var r=e!==void 0,n=e===null,o=e===e,a=de(e),i=t!==void 0,s=t===null,c=t===t,u=de(t);if(!s&&!u&&!a&&e>t||a&&i&&c&&!s&&!u||n&&i&&c||!r&&c||!o)return 1;if(!n&&!a&&!u&&e<t||u&&r&&o&&!n&&!a||s&&r&&o||!i&&o||!c)return-1}return 0}var Ru,ku=d(()=>{Mt();Ru=g_});function __(e,t,r){for(var n=-1,o=e.criteria,a=t.criteria,i=o.length,s=r.length;++n<i;){var c=Ru(o[n],a[n]);if(c){if(n>=s)return c;var u=r[n];return c*(u=="desc"?-1:1)}}return e.index-t.index}var Lu,Du=d(()=>{ku();Lu=__});function x_(e,t,r){t.length?t=Ft(t,function(a){return M(a)?function(i){return Zt(i,a.length===1?a[0]:a)}:a}):t=[$e];var n=-1;t=Ft(t,tn(Ye));var o=Tu(e,function(a,i,s){var c=Ft(t,function(u){return u(a)});return{criteria:c,index:++n,value:a}});return Cu(o,function(a,i){return Lu(a,i,r)})}var Pu,$u=d(()=>{Yn();un();Sr();Su();Nu();Xn();Du();hr();oe();Pu=x_});var w_,Ar,Mu=d(()=>{Gs();$u();Si();qn();w_=Ti(function(e,t){if(e==null)return[];var r=t.length;return r>1&&gr(e,t[0],t[1])?t=[]:r>2&&gr(t[0],t[1],t[2])&&(t=[t[0]]),Pu(e,Ws(t,1),[])}),Ar=w_});function E_(e,t){return e&&e.length?Ou(e,Ye(t,2)):0}var Eo,Fu=d(()=>{Sr();Iu();Eo=E_});var v_,b_,ju,Bu=d(()=>{uo();ei();gn();v_=1/0,b_=Ge&&1/Qt(new Ge([,-0]))[1]==v_?function(e){return new Ge(e)}:Qa,ju=b_});function S_(e,t,r){var n=-1,o=gi,a=e.length,i=!0,s=[],c=s;if(r)i=!1,o=vu;else if(a>=T_){var u=t?null:ju(e);if(u)return Qt(u);i=!1,o=hn,c=new mn}else c=t?[]:s;e:for(;++n<a;){var l=e[n],p=t?t(l):l;if(l=r||l!==0?l:0,i&&p===p){for(var f=c.length;f--;)if(c[f]===p)continue e;t&&c.push(p),s.push(l)}else o(c,p,r)||(c!==s&&c.push(p),s.push(l))}return s}var T_,Uu,Hu=d(()=>{po();_i();bu();mo();Bu();gn();T_=200;Uu=S_});function A_(e,t){return e&&e.length?Uu(e,Ye(t,2)):[]}var vo,Wu=d(()=>{Sr();Hu();vo=A_});var er=d(()=>{zs();Au();Mu();Fu();Wu();});function bo(e,t){let r={};for(let n of e)r[n[t]]=n;return r}function bn(e,t){if(t<1)return[];let r=[];for(let n=0;n<e.length;n+=t)r.push(e.slice(n,n+t));return r}var Tn=d(()=>{});var H,Gu,O_,y,D=d(()=>{H=(e,t)=>process.env[e]??t,Gu=H("SIGIL_DB_TYPE","postgres");if(Gu!=="postgres")throw new Error(`SIGIL_DB_TYPE=${Gu} is no longer supported. Sigil 0.10.0+ is Postgres-only.
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
Run \`sigil init\` for an interactive setup.`);O_={db:{type:"postgres",host:H("SIGIL_DB_HOST","localhost"),port:Number(H("SIGIL_DB_PORT",5432)),database:H("SIGIL_DB_NAME","sigil"),user:H("SIGIL_DB_USER","sigil_app"),password:H("SIGIL_DB_PASSWORD","")},embedding:{provider:process.env.EMBEDDING_PROVIDER||"",model:process.env.EMBEDDING_MODEL||"nomic-embed-text",dimensions:Number(process.env.EMBEDDING_DIMENSIONS)||768,ollamaHost:process.env.OLLAMA_HOST||"http://localhost:11434",openaiApiKey:process.env.OPENAI_API_KEY||"",voyageApiKey:process.env.VOYAGE_API_KEY||"",openrouterApiKey:process.env.OPENROUTER_API_KEY||"",openrouterBaseUrl:process.env.EMBEDDING_OPENROUTER_BASE_URL||process.env.LLM_OPENROUTER_BASE_URL||"",openrouterReferer:process.env.EMBEDDING_OPENROUTER_REFERER||process.env.LLM_OPENROUTER_REFERER||"https://github.com/Anmol-Srv/sigil",openrouterTitle:process.env.EMBEDDING_OPENROUTER_TITLE||process.env.LLM_OPENROUTER_TITLE||"Sigil"},llm:{provider:process.env.LLM_PROVIDER||"",openaiApiKey:process.env.OPENAI_API_KEY||"",openaiModel:process.env.LLM_OPENAI_MODEL||"gpt-4o-mini",ollamaHost:process.env.LLM_OLLAMA_HOST||process.env.OLLAMA_HOST||"http://localhost:11434",ollamaModel:process.env.LLM_OLLAMA_MODEL||"qwen2.5:7b",cliModel:process.env.LLM_CLI_MODEL||"haiku",apiKey:process.env.ANTHROPIC_API_KEY||"",openrouterApiKey:process.env.OPENROUTER_API_KEY||"",openrouterModel:process.env.LLM_OPENROUTER_MODEL||"google/gemini-flash-latest",openrouterBaseUrl:process.env.LLM_OPENROUTER_BASE_URL||"",openrouterReferer:process.env.LLM_OPENROUTER_REFERER||"https://github.com/Anmol-Srv/sigil",openrouterTitle:process.env.LLM_OPENROUTER_TITLE||"Sigil",extractionModel:process.env.LLM_EXTRACTION_MODEL||"",decisionModel:process.env.LLM_DECISION_MODEL||"",entityModel:process.env.LLM_ENTITY_MODEL||"",maxRetries:Number(process.env.LLM_MAX_RETRIES)||3,cliTimeout:Number(process.env.LLM_CLI_TIMEOUT)||12e4},output:{storage:process.env.OUTPUT_STORAGE||"local",dir:process.env.OUTPUT_DIR||"./output",s3:{endpoint:process.env.S3_ENDPOINT||"",bucket:process.env.S3_BUCKET||"",region:process.env.S3_REGION||"us-east-1",accessKey:process.env.S3_ACCESS_KEY||"",secretKey:process.env.S3_SECRET_KEY||"",publicUrl:process.env.S3_PUBLIC_URL||""}},server:{port:Number(process.env.PORT)||4e3,host:process.env.HOST||"0.0.0.0",logLevel:process.env.LOG_LEVEL||"info"},defaults:{namespace:process.env.DEFAULT_NAMESPACE||"default"},memory:{skipThreshold:Number(process.env.MEMORY_SKIP_THRESHOLD)||.88,ambiguousThreshold:Number(process.env.MEMORY_AMBIGUOUS_THRESHOLD)||.78,minFactSimilarity:Number(process.env.MEMORY_MIN_FACT_SIMILARITY)||.45},search:{synthesize:H("SIGIL_SYNTHESIZE","true")!=="false",synthesizeModel:H("SIGIL_SYNTH_MODEL","")},ingest:{eagerExtract:H("SIGIL_EAGER_EXTRACT","true")!=="false"},hebbian:{entity:{enabled:H("SIGIL_HEBBIAN_ENTITY_ENABLED",null,"true")!=="false",eta:Number(H("SIGIL_HEBBIAN_ENTITY_ETA",null,1)),cap:Number(H("SIGIL_HEBBIAN_ENTITY_CAP",null,50)),halfLifeDays:Number(H("SIGIL_HEBBIAN_ENTITY_HALF_LIFE_DAYS",null,30)),minEffective:Number(H("SIGIL_HEBBIAN_ENTITY_MIN_EFFECTIVE",null,.5)),rrfWeight:Number(H("SIGIL_HEBBIAN_ENTITY_RRF_WEIGHT",null,.3)),maxWriteEntities:Number(H("SIGIL_HEBBIAN_ENTITY_MAX_WRITE",null,12)),expandPerSeed:Number(H("SIGIL_HEBBIAN_ENTITY_EXPAND_PER_SEED",null,3))}}},y=O_});var Yu={};G(Yu,{chat:()=>I_,meta:()=>C_,setup:()=>N_});async function I_(e,{model:t,jsonMode:r=!1}={}){let n=t||y.llm.openaiModel,o=[{role:"user",content:e}];r&&!e.toLowerCase().includes("json")&&o.unshift({role:"system",content:"Respond with valid JSON."});let a={model:n,messages:o};r&&(a.response_format={type:"json_object"});let i=await fetch("https://api.openai.com/v1/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${y.llm.openaiApiKey}`},body:JSON.stringify(a)});if(!i.ok){let l=await i.text();throw new Error(`OpenAI error ${i.status}: ${l}`)}let s=await i.json(),c=s.choices[0].message.content.trim(),u=s.usage||{};return{text:c,inputTokens:u.prompt_tokens||0,outputTokens:u.completion_tokens||0,model:n}}async function N_({existing:e,clack:t}){let r=e.OPENAI_API_KEY||"",n=await t.text({message:"OpenAI API key (paste, then Enter)",placeholder:r?"(keep existing \u2014 press Enter)":"sk-proj-...",validate:o=>{if(!o&&!r)return"API key is required";if(o&&!o.startsWith("sk-"))return'OpenAI keys start with "sk-" \u2014 check paste'}});return t.isCancel(n)?null:{env:{OPENAI_API_KEY:n||r}}}var C_,Vu=d(()=>{D();C_={id:"openai",label:"OpenAI",hint:"gpt-4o-mini"}});import R_ from"knex";function L_(e){return Array.isArray(e)?e.map(To):e&&typeof e=="object"?To(e):e}function D_(e,t){return t(P_(e))}function To(e){if(!e||typeof e!="object"||e instanceof Date)return e;if(Array.isArray(e))return e.map(To);let t={};for(let[r,n]of Object.entries(e))t[r.replace(/_([a-z])/g,(o,a)=>a.toUpperCase())]=n;return t}function P_(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}var k_,m,P=d(()=>{D();k_=R_({client:"pg",connection:{host:y.db.host,port:y.db.port,database:y.db.database,user:y.db.user,password:y.db.password},pool:{min:2,max:10},postProcessResponse:L_,wrapIdentifier:D_});m=k_});function pe(e){return Math.ceil((e||"").length/4)}function So(e,t,r){let n=$_[e];return n?(t*n.input+r*n.output)/1e6:0}function Or({provider:e,model:t,caller:r,input:n,response:o,inputTokens:a,outputTokens:i,cost:s,durationMs:c,status:u,error:l}){m("llm_log").insert({provider:e,model:t,caller:r,input:n?.slice(0,1e4),response:o?.slice(0,1e4),inputTokens:a,outputTokens:i,cost:s,durationMs:c,status:u,error:l?.slice(0,2e3)}).catch(p=>console.error("[llm-log] Write failed:",p.message))}async function Ao(e,t=3){for(let r=1;r<=t;r++)try{return await e()}catch(n){if(r===t)throw n;let o=Math.min(1e3*2**(r-1),1e4);await new Promise(a=>setTimeout(a,o))}}var $_,Ir=d(()=>{P();$_={"gpt-4o-mini":{input:.15,output:.6},"gpt-4o":{input:2.5,output:10},"gpt-4.1-nano":{input:.1,output:.4},"gpt-4.1-mini":{input:.4,output:1.6},"claude-haiku-4-5-20251001":{input:.8,output:4},"claude-sonnet-4-6":{input:3,output:15},"claude-opus-4-6":{input:15,output:75}}});var zu={};G(zu,{chat:()=>F_,meta:()=>j_,setup:()=>B_});async function M_(){if(!Oo){let{default:e}=await import("@anthropic-ai/sdk");Oo=new e({apiKey:y.llm.apiKey})}return Oo}async function F_(e,{model:t,jsonMode:r=!1}={}){let n=t||"claude-haiku-4-5-20251001",o=await M_(),a=[{role:"user",content:e}],i=r?"Respond with valid JSON only. No explanation or wrapping.":void 0,s=await o.messages.create({model:n,max_tokens:4096,messages:a,...i&&{system:i}});return{text:s.content[0].text.trim(),inputTokens:s.usage?.input_tokens||pe(e),outputTokens:s.usage?.output_tokens||pe(s.content[0].text),model:n}}async function B_({existing:e,clack:t}){let r=e.ANTHROPIC_API_KEY||"",n=await t.text({message:"Anthropic API key (paste, then Enter)",placeholder:r?"(keep existing \u2014 press Enter)":"sk-ant-...",validate:o=>{if(!o&&!r)return"API key is required";if(o&&!o.startsWith("sk-ant-"))return'Anthropic keys start with "sk-ant-" \u2014 check paste'}});return t.isCancel(n)?null:{env:{ANTHROPIC_API_KEY:n||r}}}var Oo,j_,Ku=d(()=>{D();Ir();Oo=null;j_={id:"anthropic",label:"Anthropic",hint:"Claude Haiku \u2014 requires API key"}});var Zu={};G(Zu,{chat:()=>H_,meta:()=>W_,setup:()=>G_});async function H_(e,{model:t,jsonMode:r=!1}={}){let n=t||y.llm.openrouterModel;if(!y.llm.openrouterApiKey)throw new Error("OPENROUTER_API_KEY is not set");if(!n)throw new Error("No OpenRouter model resolved. Set LLM_OPENROUTER_MODEL or pass `model`.");let o=[{role:"user",content:e}];r&&!e.toLowerCase().includes("json")&&o.unshift({role:"system",content:"Respond with valid JSON."});let a={model:n,messages:o};r&&(a.response_format={type:"json_object"});let i=(y.llm.openrouterBaseUrl||U_).replace(/\/+$/,""),s={"Content-Type":"application/json",Authorization:`Bearer ${y.llm.openrouterApiKey}`};y.llm.openrouterReferer&&(s["HTTP-Referer"]=y.llm.openrouterReferer),y.llm.openrouterTitle&&(s["X-Title"]=y.llm.openrouterTitle);let c=await fetch(`${i}/chat/completions`,{method:"POST",headers:s,body:JSON.stringify(a)});if(!c.ok){let h=await c.text();throw new Error(`OpenRouter error ${c.status}: ${h}`)}let u=await c.json(),p=(u.choices?.[0]?.message?.content||"").trim(),f=u.usage||{};return{text:p,inputTokens:f.prompt_tokens||0,outputTokens:f.completion_tokens||0,model:u.model||n}}async function G_({existing:e,clack:t}){let r={},n=e.OPENROUTER_API_KEY||"",o=await t.text({message:"OpenRouter API key (paste, then Enter)",placeholder:n?"(keep existing \u2014 press Enter)":"sk-or-v1-...",validate:c=>{if(!c&&!n)return"API key is required";if(c&&!c.startsWith("sk-or-"))return'OpenRouter keys start with "sk-or-" \u2014 check paste'}});if(t.isCancel(o))return null;r.OPENROUTER_API_KEY=o||n;let a=e.LLM_OPENROUTER_MODEL||"",i=await t.text({message:"OpenRouter model (vendor/model)",placeholder:a||qu,validate:c=>{if(c&&!c.includes("/"))return'OpenRouter models are "vendor/model" \u2014 e.g. google/gemini-flash-latest'}});if(t.isCancel(i))return null;r.LLM_OPENROUTER_MODEL=i||a||qu;let s=await t.select({message:"Configure per-task model overrides? (advanced \u2014 better quality / cost)",options:[{value:"no",label:"No, use one model everywhere",hint:"simpler \u2014 debug one model"},{value:"yes",label:"Yes, configure smart split",hint:"~5\xD7 cheaper extraction + better AUDM/synthesis"}],initialValue:"no"});if(t.isCancel(s))return null;if(s==="yes"){let c=await t.text({message:"Extraction model (high-volume; cheap matters)",placeholder:e.LLM_EXTRACTION_MODEL||tr.extraction});if(t.isCancel(c))return null;r.LLM_EXTRACTION_MODEL=c||e.LLM_EXTRACTION_MODEL||tr.extraction;let u=await t.text({message:"Decision model (AUDM; smart matters)",placeholder:e.LLM_DECISION_MODEL||tr.decision});if(t.isCancel(u))return null;r.LLM_DECISION_MODEL=u||e.LLM_DECISION_MODEL||tr.decision;let l=await t.text({message:"Synthesis model (read-time answer composition)",placeholder:e.SIGIL_SYNTH_MODEL||tr.synthesis});if(t.isCancel(l))return null;r.SIGIL_SYNTH_MODEL=l||e.SIGIL_SYNTH_MODEL||tr.synthesis}return t.note(`OpenRouter can drive both LLM calls and embeddings.
|
|
6
|
-
You will pick an embedding provider in the next step \u2014 "openrouter" is an option,
|
|
7
|
-
or you can use a direct provider (Ollama / OpenAI / Voyage) for embeddings.`,"OpenRouter scope"),{env:r}}var U_,W_,qu,tr,Ju=d(()=>{D();U_="https://openrouter.ai/api/v1";W_={id:"openrouter",label:"OpenRouter",hint:"one key, many models (Anthropic / OpenAI / Meta / ...)"},qu="google/gemini-flash-latest",tr={extraction:"openrouter:qwen/qwen3.5-flash",decision:"openrouter:anthropic/claude-sonnet-latest",synthesis:"openrouter:anthropic/claude-sonnet-latest"}});var Xu={};G(Xu,{chat:()=>q_,meta:()=>Z_,setup:()=>J_});import{spawn as Y_}from"node:child_process";function K_(e,t){let r=y.llm.cliTimeout||12e4;return new Promise((n,o)=>{let a=Y_("claude",e,{stdio:["pipe","pipe","pipe"]}),i=setTimeout(()=>{a.kill("SIGTERM"),o(new Error(`claude CLI timed out after ${r}ms`))},r),s="",c="";a.stdout.on("data",u=>{s+=u}),a.stderr.on("data",u=>{c+=u}),a.on("error",u=>{clearTimeout(i),o(new Error(`Failed to spawn claude CLI: ${u.message}`))}),a.on("close",u=>{clearTimeout(i),n({stdout:s,stderr:c,code:u})}),a.stdin.write(t),a.stdin.end()})}async function q_(e,{model:t,jsonMode:r=!1}={}){let n=t||y.llm.cliModel||"haiku",o=V_[n]||n,a=["-p","--model",o,"--output-format","json"];r&&a.push("--json-schema",z_);let{stdout:i,stderr:s,code:c}=await K_(a,e);if(c!==0)throw new Error(`claude CLI exited ${c}: ${(s||i).slice(0,500)}`);let u;try{u=JSON.parse(i)}catch{return{text:i.trim(),inputTokens:pe(e),outputTokens:pe(i),model:o}}if(u.is_error)throw new Error(`claude CLI error: ${u.result||"unknown error"}`);let l=r&&u.structured_output?JSON.stringify(u.structured_output):(u.result||"").trim(),p=u.usage||{};return{text:l,inputTokens:p.input_tokens||pe(e),outputTokens:p.output_tokens||pe(l),model:o,cost:u.total_cost_usd||0}}async function J_(){return{env:{}}}var V_,z_,Z_,Qu=d(()=>{D();Ir();V_={"claude-haiku-4-5-20251001":"haiku","claude-sonnet-4-6":"sonnet","claude-opus-4-6":"opus"},z_=JSON.stringify({type:"object",additionalProperties:!0});Z_={id:"claude-cli",label:"Claude Code",hint:"uses your existing subscription \u2014 no extra API key"}});var el={};G(el,{chat:()=>X_,meta:()=>Q_,setup:()=>ex});async function X_(e,{model:t,jsonMode:r=!1}={}){let n=t||y.llm.ollamaModel,o=`${y.llm.ollamaHost}/api/chat`,a={model:n,messages:[{role:"user",content:e}],stream:!1};r&&(a.format="json");let i=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!i.ok){let c=await i.text();throw new Error(`Ollama error ${i.status}: ${c}`)}let s=await i.json();return{text:s.message.content.trim(),inputTokens:s.prompt_eval_count||pe(e),outputTokens:s.eval_count||pe(s.message.content),model:n}}async function ex({existing:e,clack:t}){let r=e.OLLAMA_HOST||"http://localhost:11434",n=await t.text({message:"Ollama host",placeholder:r,initialValue:r,validate:o=>{if(o&&!/^https?:\/\//.test(o))return"Must start with http:// or https://"}});return t.isCancel(n)?null:{env:{OLLAMA_HOST:n||r}}}var Q_,tl=d(()=>{D();Ir();Q_={id:"ollama",label:"Ollama",hint:"local models \u2014 no API cost"}});var rl={};G(rl,{embedBatch:()=>rx});async function rx(e,{model:t,ollamaHost:r}){let n=bn(e,tx),o=[];for(let a of n){let i=await fetch(`${r}/api/embed`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:t,input:a})});if(!i.ok)throw new Error(`Ollama embed failed: ${i.status} ${await i.text()}`);let s=await i.json();o.push(...s.embeddings)}return o}var tx,nl=d(()=>{Tn();tx=50});var ol={};G(ol,{embedBatch:()=>nx});async function nx(e,{model:t,openaiApiKey:r,dimensions:n}={}){let o={model:t,input:e};n&&/^text-embedding-3/.test(t)&&(o.dimensions=n);let a=await fetch("https://api.openai.com/v1/embeddings",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify(o)});if(!a.ok)throw new Error(`OpenAI embed failed: ${a.status} ${await a.text()}`);return(await a.json()).data.map(s=>s.embedding)}var al=d(()=>{});var il={};G(il,{embedBatch:()=>ax});async function ax(e,{model:t,voyageApiKey:r,inputType:n="document",dimensions:o}={}){if(!r)throw new Error("VOYAGE_API_KEY is not set. Get one at dashboard.voyageai.com.");let a=bn(e,ox),i=[];for(let s of a){let c={input:s,model:t||"voyage-3-large",input_type:n==="query"?"query":"document"};o&&(c.output_dimension=o);let u=await fetch("https://api.voyageai.com/v1/embeddings",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify(c)});if(!u.ok){let f=await u.text();throw new Error(`Voyage embed failed: ${u.status} ${f}`)}let p=[...(await u.json()).data].sort((f,h)=>f.index-h.index);i.push(...p.map(f=>f.embedding))}return i}var ox,sl=d(()=>{Tn();ox=50});var cl={};G(cl,{embedBatch:()=>sx});async function sx(e,{model:t,openrouterApiKey:r,openrouterBaseUrl:n,openrouterReferer:o,openrouterTitle:a,dimensions:i}={}){if(!r)throw new Error("OPENROUTER_API_KEY is not set");if(!t)throw new Error('No OpenRouter embedding model resolved. Set EMBEDDING_MODEL (e.g. "openai/text-embedding-3-large").');let s={model:t,input:e};i&&/(^|\/)text-embedding-3/.test(t)&&(s.dimensions=i);let c=(n||ix).replace(/\/+$/,""),u={"Content-Type":"application/json",Authorization:`Bearer ${r}`};o&&(u["HTTP-Referer"]=o),a&&(u["X-Title"]=a);let l=await fetch(`${c}/embeddings`,{method:"POST",headers:u,body:JSON.stringify(s)});if(!l.ok)throw new Error(`OpenRouter embed failed: ${l.status} ${await l.text()}`);return[...(await l.json()).data].sort((h,_)=>h.index-_.index).map(h=>h.embedding)}var ix,ul=d(()=>{ix="https://openrouter.ai/api/v1"});function V(e){return e?`[${e.join(",")}]`:null}function yl(){let e=Number(y.embedding.dimensions)||768;if(!Number.isInteger(e)||e<=0)throw new Error(`Invalid EMBEDDING_DIMENSIONS: ${y.embedding.dimensions}`);return e}function _e(e="embedding"){return`(${e}::halfvec(${yl()}))`}function xe(){return`?::halfvec(${yl()})`}var Ve=d(()=>{D()});var wl,El=d(()=>{wl="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"});import{webcrypto as vl}from"node:crypto";function wx(e){!_t||_t.length<e?(_t=Buffer.allocUnsafe(e*xx),vl.getRandomValues(_t),nr=0):nr+e>_t.length&&(vl.getRandomValues(_t),nr=0),nr+=e}function Ke(e=21){wx(e|=0);let t="";for(let r=nr-e;r<nr;r++)t+=wl[_t[r]&63];return t}var xx,_t,nr,Cr=d(()=>{El();xx=128});var bl={};G(bl,{findById:()=>q,findByName:()=>xt,findByUid:()=>Ex,findSimilar:()=>vx,getCanonicalEntity:()=>vt,getEntityCount:()=>Rr,incrementMentionCount:()=>Nr,insertEntity:()=>ko,listByType:()=>Do,pushAlias:()=>Sn,searchByName:()=>wt,updateDescription:()=>bx,updateEntityTypes:()=>Et,updateName:()=>Lo});async function ko({name:e,entityType:t,description:r,namespace:n,externalId:o,embedding:a}){let i=`ent-${Ke(16)}`,[s]=await m("entity").insert({uid:i,name:e,entityType:t,description:r||null,namespace:n||y.defaults.namespace,externalId:o||null,mentionCount:1,embedding:V(a)}).returning("*");return s}async function xt(e,t){let r=t||y.defaults.namespace,n=e.toLowerCase();return m("entity").where({namespace:r}).whereNull("mergedWith").where(function(){this.whereRaw("LOWER(name) = ?",[n]).orWhereRaw("aliases @> ARRAY[?]::text[]",[n])}).first()||null}async function Sn(e,t){if(!t)return;let r=t.toLowerCase();await m.raw(`
|
|
8
|
-
UPDATE entity
|
|
9
|
-
SET aliases = (
|
|
10
|
-
SELECT ARRAY(SELECT DISTINCT unnest(aliases || ARRAY[?]::text[]))
|
|
11
|
-
)
|
|
12
|
-
WHERE id = ?
|
|
13
|
-
`,[r,e])}async function Lo(e,t){await m("entity").where({id:e}).update({name:t})}async function Ex(e){return m("entity").where({uid:e}).first()||null}async function q(e){return m("entity").where({id:e}).first()||null}async function vx(e,{entityType:t,namespace:r,threshold:n=.85,limit:o=3}){let a=V(e),i=`${_e("embedding")} <=> ${xe()}`,{rows:s}=await m.raw(`
|
|
14
|
-
SELECT id, uid, name, entity_type AS "entityType", description,
|
|
15
|
-
mention_count AS "mentionCount",
|
|
16
|
-
1 - (${i}) AS similarity
|
|
17
|
-
FROM entity
|
|
18
|
-
WHERE entity_type = ?
|
|
19
|
-
AND namespace = COALESCE(?, ?)
|
|
20
|
-
AND embedding IS NOT NULL
|
|
21
|
-
AND merged_with IS NULL
|
|
22
|
-
AND 1 - (${i}) >= ?
|
|
23
|
-
ORDER BY ${i}
|
|
24
|
-
LIMIT ?
|
|
25
|
-
`,[a,t,r,y.defaults.namespace,a,n,a,o]);return s}async function Nr(e){await m("entity").where({id:e}).increment("mentionCount",1)}async function bx(e,t){await m("entity").where({id:e}).update({description:t})}async function Do(e,{namespace:t,limit:r=50}={}){let n=m("entity").where({entityType:e}).whereNull("mergedWith").orderBy("mentionCount","desc").limit(r);return t&&n.where({namespace:t}),n}async function Rr(e){let[{count:t}]=await m("entity").where({entityType:e}).whereNull("mergedWith").count("id as count");return Number(t)}async function wt(e,{entityType:t,namespace:r,limit:n=10}={}){let o=m("entity").whereRaw("LOWER(name) LIKE ?",[`%${e.toLowerCase()}%`]).whereNull("mergedWith").orderBy("mentionCount","desc").limit(n);return t&&o.where({entityType:t}),r&&o.where({namespace:r}),o}async function Et(e,t){let r=await q(e);if(!r)return;let n;try{n=r.entityTypes?JSON.parse(r.entityTypes):[r.entityType]}catch{n=[r.entityType]}n.includes(t)||(n.push(t),await m("entity").where({id:e}).update({entityTypes:JSON.stringify(n)}))}async function vt(e){let t=await q(e);for(;t?.mergedWith;)t=await q(t.mergedWith);return t}var we=d(()=>{Cr();P();Ve();D()});async function kr({podType:e,externalId:t,name:r,namespace:n,attrs:o={},entityId:a=null,connectionId:i=null,startedAt:s=null}){if(!t)throw new Error("upsertPod requires externalId; use insertPod for custom pods");let c=`pod-${Ke(16)}`,u=n||y.defaults.namespace,{rows:[l]}=await m.raw(`
|
|
26
|
-
INSERT INTO pod (uid, pod_type, name, namespace, attrs, entity_id, connection_id, external_id, started_at, created_at, updated_at)
|
|
27
|
-
VALUES (?, ?, ?, ?, ?::jsonb, ?, ?, ?, ?, NOW(), NOW())
|
|
28
|
-
ON CONFLICT (pod_type, external_id, namespace) WHERE external_id IS NOT NULL DO UPDATE SET
|
|
29
|
-
attrs = pod.attrs || EXCLUDED.attrs,
|
|
30
|
-
updated_at = NOW()
|
|
31
|
-
RETURNING *, (xmax = 0) AS "isNew"
|
|
32
|
-
`,[c,e,r,u,JSON.stringify(o),a,i,t,s]);return{pod:l,isNew:l.isNew}}async function bt(e){return m("pod").where({uid:e}).first()||null}async function Lr({podType:e,externalId:t,namespace:r}){return m("pod").where({podType:e,externalId:t,namespace:r||y.defaults.namespace}).first()||null}async function Tl({podType:e,namespace:t,status:r="active",limit:n=20}={}){let o=m("pod").where({status:r}).orderBy("updatedAt","desc").limit(n);return e&&o.where({podType:e}),t&&o.where({namespace:t}),o}async function An(e,t){await m.raw("UPDATE pod SET attrs = attrs || ?::jsonb, updated_at = NOW() WHERE id = ?",[JSON.stringify(t),e])}async function Sl(e,t=new Date){await m("pod").where({id:e}).update({endedAt:t,updatedAt:m.fn.now()})}async function Dr(e,{docs:t=0,facts:r=0}){!t&&!r||await m.raw(`UPDATE pod
|
|
33
|
-
SET member_doc_count = member_doc_count + ?,
|
|
34
|
-
member_fact_count = member_fact_count + ?,
|
|
35
|
-
updated_at = NOW()
|
|
36
|
-
WHERE id = ?`,[t,r,e])}var qe=d(()=>{Cr();P();D()});var $r={};G($r,{attach:()=>In,attachDocument:()=>Po,attachEntity:()=>Tx,attachFact:()=>Pr,detach:()=>Sx,factIdsInPod:()=>Ox,listMembers:()=>Cn,listPodsForMember:()=>Ax});async function In(e,t,r,n="primary"){let{rowCount:o}=await m.raw(`INSERT INTO pod_membership (pod_id, member_type, member_id, role)
|
|
37
|
-
VALUES (?, ?, ?, ?)
|
|
38
|
-
ON CONFLICT (pod_id, member_type, member_id) DO NOTHING`,[e,t,r,n]);return o>0&&(t==="fact"?await Dr(e,{facts:1}):t==="document"&&await Dr(e,{docs:1})),{attached:o>0}}async function Sx(e,t,r){let n=await m("pod_membership").where({podId:e,memberType:t,memberId:r}).del();return n>0&&(t==="fact"?await Dr(e,{facts:-1}):t==="document"&&await Dr(e,{docs:-1})),{detached:n>0}}async function Cn(e,{memberType:t,limit:r=20}={}){if(!t)throw new Error("listMembers requires a memberType filter");return m(`${t} as t`).join("pod_membership as pm",function(){this.on("pm.member_id","=","t.id").andOnVal("pm.member_type","=",t)}).where("pm.pod_id",e).orderBy("pm.createdAt","desc").limit(r).select("t.*","pm.role as podRole","pm.createdAt as attachedAt")}async function Ax(e,t){return m("pod as p").join("pod_membership as pm","pm.pod_id","p.id").where("pm.memberType",e).where("pm.memberId",t).select("p.*","pm.role as podRole")}async function Ox(e){return await m("pod_membership").where({podId:e,memberType:"fact"}).pluck("memberId")}var Pr,Po,Tx,Mr=d(()=>{P();qe();Pr=(e,t,r)=>In(e,"fact",t,r),Po=(e,t,r)=>In(e,"document",t,r),Tx=(e,t,r)=>In(e,"entity",t,r)});import{fileURLToPath as Cx}from"node:url";import{dirname as Il,join as W}from"node:path";import{existsSync as Cl}from"node:fs";import{homedir as Nx}from"node:os";function Rx(){let e=Il(Cx(import.meta.url));for(let t=0;t<10;t++){if(Cl(W(e,"package.json"))&&Cl(W(e,"prompts")))return e;let r=Il(e);if(r===e)break;e=r}return process.cwd()}var Nl,ie,UN,Rl,Ne,HN,WN,GN,kx,YN,VN,kl,zN,KN,Ll,qN,ZN,Re=d(()=>{Nl=Rx(),ie=W(Nl,"prompts"),UN=W(Nl,"src","db","migrations"),Rl=Nx(),Ne=W(Rl,".sigil"),HN=W(Ne,".env"),WN=W(Ne,"db"),GN=W(Ne,"CLAUDE.md"),kx=W(Ne,"schemas"),YN=W(Ne,".hook-errors.log"),VN=W(Ne,".last-clean-doctor"),kl=W(Ne,".active-session.json"),zN=W(Ne,".stop-cursor.json"),KN=W(Ne,".hook-dedup.json"),Ll=W(Rl,".claude"),qN=W(Ll,"settings.json"),ZN=W(Ll,"CLAUDE.md")});var Hl={};G(Hl,{consolidateEntityCoRetrievalEdges:()=>Wx,getCoRetrievedEntities:()=>Hx,getEdgeStrengthsForRanking:()=>Fo,getEntityHebbianStats:()=>Gx,strengthenEntityEdges:()=>Mo});function Ln(e){return Ux/Math.max(e,1)}async function Mo(e,t={}){if(!y.hebbian.entity.enabled||!e||e.length<2)return;let r=t.eta??y.hebbian.entity.eta,n=t.cap??y.hebbian.entity.cap,o=[...new Set(e.filter(c=>Number.isInteger(c)))].sort((c,u)=>c-u);if(o.length<2)return;let a=[];for(let c=0;c<o.length;c++)for(let u=c+1;u<o.length;u++)a.push([o[c],o[u]]);let i=a.map(()=>"(?, ?, ?, NOW(), NOW())").join(", "),s=a.flatMap(([c,u])=>[c,u,r]);await m.raw(`
|
|
39
|
-
INSERT INTO entity_hebbian_edge (entity_a_id, entity_b_id, strength, first_seen_at, last_seen_at)
|
|
40
|
-
VALUES ${i}
|
|
41
|
-
ON CONFLICT (entity_a_id, entity_b_id)
|
|
42
|
-
DO UPDATE SET
|
|
43
|
-
strength = LEAST(entity_hebbian_edge.strength + ?, ?),
|
|
44
|
-
last_seen_at = NOW()
|
|
45
|
-
`,[...s,r,n])}async function Hx(e,t={}){if(!y.hebbian.entity.enabled)return[];let r=t.limit??10,n=t.minEffectiveStrength??y.hebbian.entity.minEffective,o=Ln(t.halfLifeDays??y.hebbian.entity.halfLifeDays),{rows:a}=await m.raw(`
|
|
46
|
-
SELECT
|
|
47
|
-
CASE WHEN entity_a_id = ? THEN entity_b_id ELSE entity_a_id END AS "partnerId",
|
|
48
|
-
(strength * EXP(-1.0 * ?::float8 * EXTRACT(EPOCH FROM (NOW() - last_seen_at)) / 86400.0))::float8 AS "effectiveStrength",
|
|
49
|
-
strength::float8 AS "rawStrength",
|
|
50
|
-
last_seen_at AS "lastSeenAt"
|
|
51
|
-
FROM entity_hebbian_edge
|
|
52
|
-
WHERE entity_a_id = ? OR entity_b_id = ?
|
|
53
|
-
ORDER BY "effectiveStrength" DESC
|
|
54
|
-
LIMIT ?
|
|
55
|
-
`,[e,o,e,e,r*3]);return a.filter(i=>i.effectiveStrength>=n).slice(0,r)}async function Fo(e,t,r={}){if(!y.hebbian.entity.enabled)return new Map;if(!e.length||!t.length)return new Map;let n=Ln(r.halfLifeDays??y.hebbian.entity.halfLifeDays),o=[...new Set(e)],a=[...new Set(t)].filter(c=>!o.includes(c));if(!a.length)return new Map;let{rows:i}=await m.raw(`
|
|
56
|
-
SELECT
|
|
57
|
-
CASE
|
|
58
|
-
WHEN entity_a_id = ANY(?::bigint[]) THEN entity_b_id
|
|
59
|
-
ELSE entity_a_id
|
|
60
|
-
END AS "candidateId",
|
|
61
|
-
SUM(strength * EXP(-1.0 * ?::float8 * EXTRACT(EPOCH FROM (NOW() - last_seen_at)) / 86400.0))::float8 AS "summedStrength"
|
|
62
|
-
FROM entity_hebbian_edge
|
|
63
|
-
WHERE
|
|
64
|
-
(entity_a_id = ANY(?::bigint[]) AND entity_b_id = ANY(?::bigint[]))
|
|
65
|
-
OR
|
|
66
|
-
(entity_b_id = ANY(?::bigint[]) AND entity_a_id = ANY(?::bigint[]))
|
|
67
|
-
GROUP BY "candidateId"
|
|
68
|
-
`,[o,n,o,a,o,a]),s=new Map;for(let c of i)s.set(Number(c.candidateId),c.summedStrength);return s}async function Wx({floor:e=.5,decayDays:t=90}={}){let r=Ln(y.hebbian.entity.halfLifeDays),{rows:n}=await m.raw(`
|
|
69
|
-
DELETE FROM entity_hebbian_edge
|
|
70
|
-
WHERE (strength * EXP(-1.0 * ?::float8 * EXTRACT(EPOCH FROM (NOW() - last_seen_at)) / 86400.0)) <= ?
|
|
71
|
-
AND last_seen_at < NOW() - (INTERVAL '1 day' * ?)
|
|
72
|
-
RETURNING entity_a_id
|
|
73
|
-
`,[r,e,t]);return n.length}async function Gx({topN:e=5}={}){let t=Ln(y.hebbian.entity.halfLifeDays),r=await m.raw(`
|
|
74
|
-
SELECT
|
|
75
|
-
COUNT(*)::int AS "edgeCount",
|
|
76
|
-
COALESCE(AVG(strength)::float8, 0) AS "avgStrength",
|
|
77
|
-
COALESCE(MAX(strength)::float8, 0) AS "maxStrength"
|
|
78
|
-
FROM entity_hebbian_edge
|
|
79
|
-
`),n=await m.raw(`
|
|
80
|
-
SELECT
|
|
81
|
-
ea.name AS "aName",
|
|
82
|
-
eb.name AS "bName",
|
|
83
|
-
strength::float8 AS "strength",
|
|
84
|
-
(strength * EXP(-1.0 * ?::float8 * EXTRACT(EPOCH FROM (NOW() - last_seen_at)) / 86400.0))::float8 AS "decayed"
|
|
85
|
-
FROM entity_hebbian_edge
|
|
86
|
-
JOIN entity ea ON ea.id = entity_a_id
|
|
87
|
-
JOIN entity eb ON eb.id = entity_b_id
|
|
88
|
-
ORDER BY "decayed" DESC
|
|
89
|
-
LIMIT ?
|
|
90
|
-
`,[t,e]);return{edgeCount:r.rows[0]?.edgeCount??0,avgStrength:r.rows[0]?.avgStrength??0,maxStrength:r.rows[0]?.maxStrength??0,topPairs:n.rows??[]}}var Ux,jo=d(()=>{P();D();Ux=Math.log(2)});var Ho={};G(Ho,{CURSOR_PATH:()=>ir,endActiveSession:()=>ww,ensureActiveSession:()=>gw,getActiveCursor:()=>xw,getActiveSessionPodUid:()=>Uo});import{writeFile as dw,readFile as fw,unlink as pw}from"node:fs/promises";import{existsSync as mw,mkdirSync as hw}from"node:fs";import{dirname as id}from"node:path";async function $n(){try{let e=await fw(ir,"utf8");return JSON.parse(e)}catch{return null}}async function sd(e){mw(id(ir))||hw(id(ir),{recursive:!0}),await dw(ir,JSON.stringify(e,null,2),"utf8")}async function gw({sessionId:e,transcriptPath:t=null,cwd:r=null,model:n=null,namespace:o=null}){if(!e)throw new Error("ensureActiveSession requires sessionId from hook stdin");let a=o||y.defaults.namespace,i=await $n();if(i&&i.session_id===e&&i.namespace===a){let u=await bt(i.pod_uid);if(u)return await An(u.id,{turn_count:(Ew(u.attrs)||0)+1}),await _w(i),u}let s=new Date,{pod:c}=await kr({podType:cd,externalId:e,name:ld({sessionId:e,startedAt:s}),namespace:a,attrs:ud({sessionId:e,transcriptPath:t,cwd:r,turnCount:1,model:n}),startedAt:s});return await sd({session_id:e,pod_uid:c.uid,namespace:a,started_at:c.startedAt??s.toISOString(),last_seen_at:new Date().toISOString()}),c}async function _w(e){await sd({...e,last_seen_at:new Date().toISOString()})}async function Uo({allowStale:e=!1}={}){let t=await $n();return!t||!t.pod_uid||!e&&t.started_at&&Date.now()-new Date(t.started_at).getTime()>yw?null:t.pod_uid}async function xw(){return $n()}async function ww({conclusion:e=null,summary:t=null}={}){let r=await $n();if(!r)return null;let n=await bt(r.pod_uid);if(n){if(e||t){let o={};e&&(o.conclusion=e),t&&(o.summary=t),await An(n.id,o)}await Sl(n.id)}try{await pw(ir)}catch{}return n}function Ew(e){if(!e)return 0;if(typeof e=="object")return e.turn_count??0;try{return JSON.parse(e).turn_count??0}catch{return 0}}var ir,yw,Mn=d(()=>{qe();Wo();D();Re();ir=kl,yw=360*60*1e3});function ud({sessionId:e,transcriptPath:t=null,cwd:r=null,turnCount:n=0,model:o=null,conclusion:a=null,summary:i=null}){return{session_id:e,transcript_path:t,cwd:r,turn_count:n,model:o,conclusion:a,summary:i}}function ld({sessionId:e,startedAt:t=new Date}={}){let n=(t instanceof Date?t:new Date(t)).toISOString().replace("T"," ").slice(0,16),o=e?e.slice(0,8):"unknown";return`claude-session ${n} (${o})`}var cd,dd,Wo=d(()=>{Mn();cd="claude_session",dd={name:"claude_session",description:"Claude Code session",identityField:"session_id",attrsSchema:{session_id:"string",transcript_path:"string",cwd:"string",turn_count:"number",model:"string",conclusion:"string",summary:"string"},visibility:"private",activeMode:"singleton-live",hotContextBudget:6,retrievalWeights:{recency:1,relevance:.7},importanceDefault:2,ttlDays:90,schemaDocPath:"kinds/claude_session.schema.md",writePolicy:"origin-only",resolveActiveScope:async()=>{try{let e=await Uo();return e?[e]:[]}catch{return[]}}}});var md={};G(md,{POD_TYPE:()=>Yo,deriveProjectRoot:()=>zo,ensureProjectPod:()=>Aw,formatForDisplay:()=>Iw,membership:()=>$r,projectKind:()=>Vo});import{execFileSync as Sw}from"node:child_process";import{basename as pd}from"node:path";async function Aw({cwd:e,namespace:t=null}){if(!e)return null;let r=zo(e),n=t||y.defaults.namespace,a=(r!==e?!1:Go(e)===e)?r:Go(e),{pod:i}=await kr({podType:Yo,externalId:r,name:pd(r)||r,namespace:n,attrs:{root_path:r,git_root:a||null,display_name:pd(r)||r,discovered_at:new Date().toISOString()},startedAt:new Date});return i}function zo(e){return Go(e)||e}function Go(e){try{return Sw("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",stdio:["ignore","pipe","ignore"]}).trim()||null}catch{return null}}async function Ow(){try{let{getActiveCursor:e}=await Promise.resolve().then(()=>(Mn(),Ho));return(await e())?.cwd||null}catch{return null}}function Iw(e){let t=Cw(e.attrs);return{uid:e.uid,name:e.name,rootPath:t.root_path,gitRoot:t.git_root,displayName:t.display_name,discoveredAt:t.discovered_at,memberFactCount:e.memberFactCount,memberDocCount:e.memberDocCount}}function Cw(e){if(!e)return{};if(typeof e=="object")return e;try{return JSON.parse(e)}catch{return{}}}var Yo,Vo,Ko=d(()=>{qe();Mr();D();Yo="project",Vo={name:"project",description:"Code project rooted at a git repo or directory",identityField:"root_path",attrsSchema:{root_path:"string",git_root:"string",display_name:"string",discovered_at:"string"},visibility:"shared",activeMode:"multi-active",hotContextBudget:4,retrievalWeights:{recency:.6,relevance:1},importanceDefault:3,ttlDays:null,schemaDocPath:"kinds/project.schema.md",writePolicy:"origin-only",resolveActiveScope:async(e={})=>{let t=e.cwd||await Ow();if(!t)return[];try{let r=e.namespace||y.defaults.namespace,n=zo(t),o=await Lr({podType:Yo,externalId:n,namespace:r});return o?[o.uid]:[]}catch{return[]}}}});var Vd={};G(Vd,{followMergeChain:()=>jE,mergeEntities:()=>$E});async function $E(e,t){let[r,n]=await Promise.all([q(e),q(t)]);if(!r||!n)throw new Error(`Entity ${e} or ${t} not found`);if(e===t)return r;let o=(r.mentionCount||0)+(n.mentionCount||0);await m.transaction(async i=>{await i("relation").where({sourceId:t}).update({sourceId:e}),await i("relation").where({targetId:t}).update({targetId:e}),await i("relation").whereRaw("source_id = target_id").del(),await i.raw(`
|
|
91
|
-
INSERT INTO fact_entity (fact_id, entity_id, mention_type, mention_count, created_at, updated_at)
|
|
92
|
-
SELECT fact_id, ?, mention_type, mention_count, NOW(), NOW()
|
|
93
|
-
FROM fact_entity
|
|
94
|
-
WHERE entity_id = ?
|
|
95
|
-
ON CONFLICT (fact_id, entity_id, mention_type)
|
|
96
|
-
DO UPDATE SET mention_count = fact_entity.mention_count + EXCLUDED.mention_count
|
|
97
|
-
`,[e,t]),await i("fact_entity").where({entityId:t}).del(),await i("entity").where({id:e}).update({mentionCount:o}),await i("pod").where({entityId:e,status:"active"}).first()?await i("pod").where({entityId:t}).update({status:"archived",updatedAt:i.fn.now()}):await i("pod").where({entityId:t}).update({entityId:e,updatedAt:i.fn.now()}),await i("entity").where({id:t}).update({mergedWith:e})}),await FE(e);let a=ME(n);for(let i of a)await Et(e,i);return console.log(`[entity-merge] Merged ${t} (${n.name}) into ${e} (${r.name})`),{...r,mentionCount:o}}function ME(e){if(!e.entityTypes)return[e.entityType];try{return JSON.parse(e.entityTypes)}catch{return[e.entityType]}}async function FE(e){let t=await m("relation").where(function(){this.where({sourceId:e}).orWhere({targetId:e})}).whereNull("invalidAt"),r=gt(t,n=>`${n.sourceId}-${n.targetId}-${n.relationType}`);for(let n of Object.values(r)){if(n.length<=1)continue;let[o,...a]=Ar(n,"id"),i=Eo(n,"mentionCount");await m("relation").where({id:o.id}).update({mentionCount:i}),await m("relation").whereIn("id",a.map(s=>s.id)).del()}}async function jE(e){let t=await q(e),r=[t?.id];for(;t?.mergedWith;)t=await q(t.mergedWith),t&&r.push(t.id);return{canonical:t,chain:r}}var zd=d(()=>{er();P();we()});import{config as lv}from"dotenv";import{resolve as sa,dirname as uf}from"node:path";import{fileURLToPath as dv}from"node:url";import{existsSync as fv}from"node:fs";import"dotenv/config";import{McpServer as sv}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as cv}from"@modelcontextprotocol/sdk/server/stdio.js";var T={};G(T,{BRAND:()=>Mf,DIRTY:()=>Qe,EMPTY_PATH:()=>hf,INVALID:()=>S,NEVER:()=>Ep,OK:()=>Y,ParseStatus:()=>U,Schema:()=>C,ZodAny:()=>De,ZodArray:()=>Oe,ZodBigInt:()=>tt,ZodBoolean:()=>rt,ZodBranded:()=>fr,ZodCatch:()=>pt,ZodDate:()=>nt,ZodDefault:()=>ft,ZodDiscriminatedUnion:()=>Gr,ZodEffects:()=>ne,ZodEnum:()=>lt,ZodError:()=>J,ZodFirstPartyTypeKind:()=>A,ZodFunction:()=>Vr,ZodIntersection:()=>st,ZodIssueCode:()=>g,ZodLazy:()=>ct,ZodLiteral:()=>ut,ZodMap:()=>Rt,ZodNaN:()=>Lt,ZodNativeEnum:()=>dt,ZodNever:()=>ce,ZodNull:()=>at,ZodNullable:()=>ye,ZodNumber:()=>et,ZodObject:()=>X,ZodOptional:()=>te,ZodParsedType:()=>v,ZodPipeline:()=>pr,ZodPromise:()=>Pe,ZodReadonly:()=>mt,ZodRecord:()=>Yr,ZodSchema:()=>C,ZodSet:()=>kt,ZodString:()=>Le,ZodSymbol:()=>Ct,ZodTransformer:()=>ne,ZodTuple:()=>he,ZodType:()=>C,ZodUndefined:()=>ot,ZodUnion:()=>it,ZodUnknown:()=>Ae,ZodVoid:()=>Nt,addIssueToContext:()=>w,any:()=>Vf,array:()=>Zf,bigint:()=>Uf,boolean:()=>_a,coerce:()=>wp,custom:()=>ha,date:()=>Hf,datetimeRegex:()=>pa,defaultErrorMap:()=>Te,discriminatedUnion:()=>ep,effect:()=>fp,enum:()=>up,function:()=>ip,getErrorMap:()=>At,getParsedType:()=>me,instanceof:()=>jf,intersection:()=>tp,isAborted:()=>Hr,isAsync:()=>Ot,isDirty:()=>Wr,isValid:()=>ke,late:()=>Ff,lazy:()=>sp,literal:()=>cp,makeIssue:()=>dr,map:()=>op,nan:()=>Bf,nativeEnum:()=>lp,never:()=>Kf,null:()=>Yf,nullable:()=>mp,number:()=>ga,object:()=>Jf,objectUtil:()=>Un,oboolean:()=>xp,onumber:()=>_p,optional:()=>pp,ostring:()=>gp,pipeline:()=>yp,preprocess:()=>hp,promise:()=>dp,quotelessJson:()=>ff,record:()=>np,set:()=>ap,setErrorMap:()=>mf,strictObject:()=>Xf,string:()=>ya,symbol:()=>Wf,transformer:()=>fp,tuple:()=>rp,undefined:()=>Gf,union:()=>Qf,unknown:()=>zf,util:()=>R,void:()=>qf});var R;(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function r(o){throw new Error}e.assertNever=r,e.arrayToEnum=o=>{let a={};for(let i of o)a[i]=i;return a},e.getValidEnumValues=o=>{let a=e.objectKeys(o).filter(s=>typeof o[o[s]]!="number"),i={};for(let s of a)i[s]=o[s];return e.objectValues(i)},e.objectValues=o=>e.objectKeys(o).map(function(a){return o[a]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let a=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&a.push(i);return a},e.find=(o,a)=>{for(let i of o)if(a(i))return i},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,a=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}e.joinValues=n,e.jsonStringifyReplacer=(o,a)=>typeof a=="bigint"?a.toString():a})(R||(R={}));var Un;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(Un||(Un={}));var v=R.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),me=e=>{switch(typeof e){case"undefined":return v.undefined;case"string":return v.string;case"number":return Number.isNaN(e)?v.nan:v.number;case"boolean":return v.boolean;case"function":return v.function;case"bigint":return v.bigint;case"symbol":return v.symbol;case"object":return Array.isArray(e)?v.array:e===null?v.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?v.promise:typeof Map<"u"&&e instanceof Map?v.map:typeof Set<"u"&&e instanceof Set?v.set:typeof Date<"u"&&e instanceof Date?v.date:v.object;default:return v.unknown}};var g=R.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),ff=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),J=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(a){return a.message},n={_errors:[]},o=a=>{for(let i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let s=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(s[u]=s[u]||{_errors:[]},s[u]._errors.push(r(i))):s[u]=s[u]||{_errors:[]},s=s[u],c++}}};return o(this),n}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,R.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let a=o.path[0];r[a]=r[a]||[],r[a].push(t(o))}else n.push(t(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};J.create=e=>new J(e);var pf=(e,t)=>{let r;switch(e.code){case g.invalid_type:e.received===v.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case g.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,R.jsonStringifyReplacer)}`;break;case g.unrecognized_keys:r=`Unrecognized key(s) in object: ${R.joinValues(e.keys,", ")}`;break;case g.invalid_union:r="Invalid input";break;case g.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${R.joinValues(e.options)}`;break;case g.invalid_enum_value:r=`Invalid enum value. Expected ${R.joinValues(e.options)}, received '${e.received}'`;break;case g.invalid_arguments:r="Invalid function arguments";break;case g.invalid_return_type:r="Invalid function return type";break;case g.invalid_date:r="Invalid date";break;case g.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:R.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case g.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case g.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case g.custom:r="Invalid input";break;case g.invalid_intersection_types:r="Intersection results could not be merged";break;case g.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case g.not_finite:r="Number must be finite";break;default:r=t.defaultError,R.assertNever(e)}return{message:r}},Te=pf;var ca=Te;function mf(e){ca=e}function At(){return ca}var dr=e=>{let{data:t,path:r,errorMaps:n,issueData:o}=e,a=[...r,...o.path||[]],i={...o,path:a};if(o.message!==void 0)return{...o,path:a,message:o.message};let s="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)s=u(i,{data:t,defaultError:s}).message;return{...o,path:a,message:s}},hf=[];function w(e,t){let r=At(),n=dr({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===Te?void 0:Te].filter(o=>!!o)});e.common.issues.push(n)}var U=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){let n=[];for(let o of r){if(o.status==="aborted")return S;o.status==="dirty"&&t.dirty(),n.push(o.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){let n=[];for(let o of r){let a=await o.key,i=await o.value;n.push({key:a,value:i})}return e.mergeObjectSync(t,n)}static mergeObjectSync(t,r){let n={};for(let o of r){let{key:a,value:i}=o;if(a.status==="aborted"||i.status==="aborted")return S;a.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[a.value]=i.value)}return{status:t.value,value:n}}},S=Object.freeze({status:"aborted"}),Qe=e=>({status:"dirty",value:e}),Y=e=>({status:"valid",value:e}),Hr=e=>e.status==="aborted",Wr=e=>e.status==="dirty",ke=e=>e.status==="valid",Ot=e=>typeof Promise<"u"&&e instanceof Promise;var b;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(b||(b={}));var re=class{constructor(t,r,n,o){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},ua=(e,t)=>{if(ke(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new J(e.common.issues);return this._error=r,this._error}}};function I(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:o}=e;if(t&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(i,s)=>{let{message:c}=e;return i.code==="invalid_enum_value"?{message:c??s.defaultError}:typeof s.data>"u"?{message:c??n??s.defaultError}:i.code!=="invalid_type"?{message:s.defaultError}:{message:c??r??s.defaultError}},description:o}}var C=class{get description(){return this._def.description}_getType(t){return me(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:me(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new U,ctx:{common:t.parent.common,data:t.data,parsedType:me(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(Ot(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){let r=this._parse(t);return Promise.resolve(r)}parse(t,r){let n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:me(t)},o=this._parseSync({data:t,path:n.path,parent:n});return ua(n,o)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:me(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return ke(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(n=>ke(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(t,r){let n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:me(t)},o=this._parse({data:t,path:n.path,parent:n}),a=await(Ot(o)?o:Promise.resolve(o));return ua(n,a)}refine(t,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,a)=>{let i=t(o),s=()=>a.addIssue({code:g.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(s(),!1)):i?!0:(s(),!1)})}refinement(t,r){return this._refinement((n,o)=>t(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(t){return new ne({schema:this,typeName:A.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return te.create(this,this._def)}nullable(){return ye.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Oe.create(this)}promise(){return Pe.create(this,this._def)}or(t){return it.create([this,t],this._def)}and(t){return st.create(this,t,this._def)}transform(t){return new ne({...I(this._def),schema:this,typeName:A.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new ft({...I(this._def),innerType:this,defaultValue:r,typeName:A.ZodDefault})}brand(){return new fr({typeName:A.ZodBranded,type:this,...I(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new pt({...I(this._def),innerType:this,catchValue:r,typeName:A.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return pr.create(this,t)}readonly(){return mt.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},yf=/^c[^\s-]{8,}$/i,gf=/^[0-9a-z]+$/,_f=/^[0-9A-HJKMNP-TV-Z]{26}$/i,xf=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,wf=/^[a-z0-9_-]{21}$/i,Ef=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,vf=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,bf=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Tf="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Hn,Sf=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Af=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Of=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,If=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Cf=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Nf=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,da="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Rf=new RegExp(`^${da}$`);function fa(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function kf(e){return new RegExp(`^${fa(e)}$`)}function pa(e){let t=`${da}T${fa(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function Lf(e,t){return!!((t==="v4"||!t)&&Sf.test(e)||(t==="v6"||!t)&&Of.test(e))}function Df(e,t){if(!Ef.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function Pf(e,t){return!!((t==="v4"||!t)&&Af.test(e)||(t==="v6"||!t)&&If.test(e))}var Le=class e extends C{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==v.string){let a=this._getOrReturnCtx(t);return w(a,{code:g.invalid_type,expected:v.string,received:a.parsedType}),S}let n=new U,o;for(let a of this._def.checks)if(a.kind==="min")t.data.length<a.value&&(o=this._getOrReturnCtx(t,o),w(o,{code:g.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="max")t.data.length>a.value&&(o=this._getOrReturnCtx(t,o),w(o,{code:g.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="length"){let i=t.data.length>a.value,s=t.data.length<a.value;(i||s)&&(o=this._getOrReturnCtx(t,o),i?w(o,{code:g.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):s&&w(o,{code:g.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),n.dirty())}else if(a.kind==="email")bf.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"email",code:g.invalid_string,message:a.message}),n.dirty());else if(a.kind==="emoji")Hn||(Hn=new RegExp(Tf,"u")),Hn.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"emoji",code:g.invalid_string,message:a.message}),n.dirty());else if(a.kind==="uuid")xf.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"uuid",code:g.invalid_string,message:a.message}),n.dirty());else if(a.kind==="nanoid")wf.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"nanoid",code:g.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid")yf.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"cuid",code:g.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid2")gf.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"cuid2",code:g.invalid_string,message:a.message}),n.dirty());else if(a.kind==="ulid")_f.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"ulid",code:g.invalid_string,message:a.message}),n.dirty());else if(a.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),w(o,{validation:"url",code:g.invalid_string,message:a.message}),n.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"regex",code:g.invalid_string,message:a.message}),n.dirty())):a.kind==="trim"?t.data=t.data.trim():a.kind==="includes"?t.data.includes(a.value,a.position)||(o=this._getOrReturnCtx(t,o),w(o,{code:g.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),n.dirty()):a.kind==="toLowerCase"?t.data=t.data.toLowerCase():a.kind==="toUpperCase"?t.data=t.data.toUpperCase():a.kind==="startsWith"?t.data.startsWith(a.value)||(o=this._getOrReturnCtx(t,o),w(o,{code:g.invalid_string,validation:{startsWith:a.value},message:a.message}),n.dirty()):a.kind==="endsWith"?t.data.endsWith(a.value)||(o=this._getOrReturnCtx(t,o),w(o,{code:g.invalid_string,validation:{endsWith:a.value},message:a.message}),n.dirty()):a.kind==="datetime"?pa(a).test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{code:g.invalid_string,validation:"datetime",message:a.message}),n.dirty()):a.kind==="date"?Rf.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{code:g.invalid_string,validation:"date",message:a.message}),n.dirty()):a.kind==="time"?kf(a).test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{code:g.invalid_string,validation:"time",message:a.message}),n.dirty()):a.kind==="duration"?vf.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"duration",code:g.invalid_string,message:a.message}),n.dirty()):a.kind==="ip"?Lf(t.data,a.version)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"ip",code:g.invalid_string,message:a.message}),n.dirty()):a.kind==="jwt"?Df(t.data,a.alg)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"jwt",code:g.invalid_string,message:a.message}),n.dirty()):a.kind==="cidr"?Pf(t.data,a.version)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"cidr",code:g.invalid_string,message:a.message}),n.dirty()):a.kind==="base64"?Cf.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"base64",code:g.invalid_string,message:a.message}),n.dirty()):a.kind==="base64url"?Nf.test(t.data)||(o=this._getOrReturnCtx(t,o),w(o,{validation:"base64url",code:g.invalid_string,message:a.message}),n.dirty()):R.assertNever(a);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(o=>t.test(o),{validation:r,code:g.invalid_string,...b.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...b.errToObj(t)})}url(t){return this._addCheck({kind:"url",...b.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...b.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...b.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...b.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...b.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...b.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...b.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...b.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...b.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...b.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...b.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...b.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...b.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...b.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...b.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...b.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...b.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...b.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...b.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...b.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...b.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...b.errToObj(r)})}nonempty(t){return this.min(1,b.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};Le.create=e=>new Le({checks:[],typeName:A.ZodString,coerce:e?.coerce??!1,...I(e)});function $f(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,o=r>n?r:n,a=Number.parseInt(e.toFixed(o).replace(".","")),i=Number.parseInt(t.toFixed(o).replace(".",""));return a%i/10**o}var et=class e extends C{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==v.number){let a=this._getOrReturnCtx(t);return w(a,{code:g.invalid_type,expected:v.number,received:a.parsedType}),S}let n,o=new U;for(let a of this._def.checks)a.kind==="int"?R.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),w(n,{code:g.invalid_type,expected:"integer",received:"float",message:a.message}),o.dirty()):a.kind==="min"?(a.inclusive?t.data<a.value:t.data<=a.value)&&(n=this._getOrReturnCtx(t,n),w(n,{code:g.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),o.dirty()):a.kind==="max"?(a.inclusive?t.data>a.value:t.data>=a.value)&&(n=this._getOrReturnCtx(t,n),w(n,{code:g.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),o.dirty()):a.kind==="multipleOf"?$f(t.data,a.value)!==0&&(n=this._getOrReturnCtx(t,n),w(n,{code:g.not_multiple_of,multipleOf:a.value,message:a.message}),o.dirty()):a.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),w(n,{code:g.not_finite,message:a.message}),o.dirty()):R.assertNever(a);return{status:o.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,b.toString(r))}gt(t,r){return this.setLimit("min",t,!1,b.toString(r))}lte(t,r){return this.setLimit("max",t,!0,b.toString(r))}lt(t,r){return this.setLimit("max",t,!1,b.toString(r))}setLimit(t,r,n,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:b.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:b.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:b.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:b.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:b.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:b.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:b.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:b.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:b.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:b.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&R.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value)}return Number.isFinite(r)&&Number.isFinite(t)}};et.create=e=>new et({checks:[],typeName:A.ZodNumber,coerce:e?.coerce||!1,...I(e)});var tt=class e extends C{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==v.bigint)return this._getInvalidInput(t);let n,o=new U;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?t.data<a.value:t.data<=a.value)&&(n=this._getOrReturnCtx(t,n),w(n,{code:g.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),o.dirty()):a.kind==="max"?(a.inclusive?t.data>a.value:t.data>=a.value)&&(n=this._getOrReturnCtx(t,n),w(n,{code:g.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),o.dirty()):a.kind==="multipleOf"?t.data%a.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),w(n,{code:g.not_multiple_of,multipleOf:a.value,message:a.message}),o.dirty()):R.assertNever(a);return{status:o.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return w(r,{code:g.invalid_type,expected:v.bigint,received:r.parsedType}),S}gte(t,r){return this.setLimit("min",t,!0,b.toString(r))}gt(t,r){return this.setLimit("min",t,!1,b.toString(r))}lte(t,r){return this.setLimit("max",t,!0,b.toString(r))}lt(t,r){return this.setLimit("max",t,!1,b.toString(r))}setLimit(t,r,n,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:b.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:b.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:b.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:b.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:b.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:b.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};tt.create=e=>new tt({checks:[],typeName:A.ZodBigInt,coerce:e?.coerce??!1,...I(e)});var rt=class extends C{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==v.boolean){let n=this._getOrReturnCtx(t);return w(n,{code:g.invalid_type,expected:v.boolean,received:n.parsedType}),S}return Y(t.data)}};rt.create=e=>new rt({typeName:A.ZodBoolean,coerce:e?.coerce||!1,...I(e)});var nt=class e extends C{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==v.date){let a=this._getOrReturnCtx(t);return w(a,{code:g.invalid_type,expected:v.date,received:a.parsedType}),S}if(Number.isNaN(t.data.getTime())){let a=this._getOrReturnCtx(t);return w(a,{code:g.invalid_date}),S}let n=new U,o;for(let a of this._def.checks)a.kind==="min"?t.data.getTime()<a.value&&(o=this._getOrReturnCtx(t,o),w(o,{code:g.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),n.dirty()):a.kind==="max"?t.data.getTime()>a.value&&(o=this._getOrReturnCtx(t,o),w(o,{code:g.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):R.assertNever(a);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:b.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:b.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}};nt.create=e=>new nt({checks:[],coerce:e?.coerce||!1,typeName:A.ZodDate,...I(e)});var Ct=class extends C{_parse(t){if(this._getType(t)!==v.symbol){let n=this._getOrReturnCtx(t);return w(n,{code:g.invalid_type,expected:v.symbol,received:n.parsedType}),S}return Y(t.data)}};Ct.create=e=>new Ct({typeName:A.ZodSymbol,...I(e)});var ot=class extends C{_parse(t){if(this._getType(t)!==v.undefined){let n=this._getOrReturnCtx(t);return w(n,{code:g.invalid_type,expected:v.undefined,received:n.parsedType}),S}return Y(t.data)}};ot.create=e=>new ot({typeName:A.ZodUndefined,...I(e)});var at=class extends C{_parse(t){if(this._getType(t)!==v.null){let n=this._getOrReturnCtx(t);return w(n,{code:g.invalid_type,expected:v.null,received:n.parsedType}),S}return Y(t.data)}};at.create=e=>new at({typeName:A.ZodNull,...I(e)});var De=class extends C{constructor(){super(...arguments),this._any=!0}_parse(t){return Y(t.data)}};De.create=e=>new De({typeName:A.ZodAny,...I(e)});var Ae=class extends C{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Y(t.data)}};Ae.create=e=>new Ae({typeName:A.ZodUnknown,...I(e)});var ce=class extends C{_parse(t){let r=this._getOrReturnCtx(t);return w(r,{code:g.invalid_type,expected:v.never,received:r.parsedType}),S}};ce.create=e=>new ce({typeName:A.ZodNever,...I(e)});var Nt=class extends C{_parse(t){if(this._getType(t)!==v.undefined){let n=this._getOrReturnCtx(t);return w(n,{code:g.invalid_type,expected:v.void,received:n.parsedType}),S}return Y(t.data)}};Nt.create=e=>new Nt({typeName:A.ZodVoid,...I(e)});var Oe=class e extends C{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),o=this._def;if(r.parsedType!==v.array)return w(r,{code:g.invalid_type,expected:v.array,received:r.parsedType}),S;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,s=r.data.length<o.exactLength.value;(i||s)&&(w(r,{code:i?g.too_big:g.too_small,minimum:s?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(w(r,{code:g.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(w(r,{code:g.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,s)=>o.type._parseAsync(new re(r,i,r.path,s)))).then(i=>U.mergeArray(n,i));let a=[...r.data].map((i,s)=>o.type._parseSync(new re(r,i,r.path,s)));return U.mergeArray(n,a)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:b.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:b.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:b.toString(r)}})}nonempty(t){return this.min(1,t)}};Oe.create=(e,t)=>new Oe({type:e,minLength:null,maxLength:null,exactLength:null,typeName:A.ZodArray,...I(t)});function It(e){if(e instanceof X){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=te.create(It(n))}return new X({...e._def,shape:()=>t})}else return e instanceof Oe?new Oe({...e._def,type:It(e.element)}):e instanceof te?te.create(It(e.unwrap())):e instanceof ye?ye.create(It(e.unwrap())):e instanceof he?he.create(e.items.map(t=>It(t))):e}var X=class e extends C{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),r=R.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==v.object){let u=this._getOrReturnCtx(t);return w(u,{code:g.invalid_type,expected:v.object,received:u.parsedType}),S}let{status:n,ctx:o}=this._processInputParams(t),{shape:a,keys:i}=this._getCached(),s=[];if(!(this._def.catchall instanceof ce&&this._def.unknownKeys==="strip"))for(let u in o.data)i.includes(u)||s.push(u);let c=[];for(let u of i){let l=a[u],p=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new re(o,p,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof ce){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of s)c.push({key:{status:"valid",value:l},value:{status:"valid",value:o.data[l]}});else if(u==="strict")s.length>0&&(w(o,{code:g.unrecognized_keys,keys:s}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of s){let p=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new re(o,p,o.path,l)),alwaysSet:l in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let p=await l.key,f=await l.value;u.push({key:p,value:f,alwaysSet:l.alwaysSet})}return u}).then(u=>U.mergeObjectSync(n,u)):U.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(t){return b.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:b.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:A.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let r={};for(let n of R.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}omit(t){let r={};for(let n of R.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return It(this)}partial(t){let r={};for(let n of R.objectKeys(this.shape)){let o=this.shape[n];t&&!t[n]?r[n]=o:r[n]=o.optional()}return new e({...this._def,shape:()=>r})}required(t){let r={};for(let n of R.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let a=this.shape[n];for(;a instanceof te;)a=a._def.innerType;r[n]=a}return new e({...this._def,shape:()=>r})}keyof(){return ma(R.objectKeys(this.shape))}};X.create=(e,t)=>new X({shape:()=>e,unknownKeys:"strip",catchall:ce.create(),typeName:A.ZodObject,...I(t)});X.strictCreate=(e,t)=>new X({shape:()=>e,unknownKeys:"strict",catchall:ce.create(),typeName:A.ZodObject,...I(t)});X.lazycreate=(e,t)=>new X({shape:e,unknownKeys:"strip",catchall:ce.create(),typeName:A.ZodObject,...I(t)});var it=class extends C{_parse(t){let{ctx:r}=this._processInputParams(t),n=this._def.options;function o(a){for(let s of a)if(s.result.status==="valid")return s.result;for(let s of a)if(s.result.status==="dirty")return r.common.issues.push(...s.ctx.common.issues),s.result;let i=a.map(s=>new J(s.ctx.common.issues));return w(r,{code:g.invalid_union,unionErrors:i}),S}if(r.common.async)return Promise.all(n.map(async a=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await a._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let a,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!a&&(a={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(a)return r.common.issues.push(...a.ctx.common.issues),a.result;let s=i.map(c=>new J(c));return w(r,{code:g.invalid_union,unionErrors:s}),S}}get options(){return this._def.options}};it.create=(e,t)=>new it({options:e,typeName:A.ZodUnion,...I(t)});var Se=e=>e instanceof ct?Se(e.schema):e instanceof ne?Se(e.innerType()):e instanceof ut?[e.value]:e instanceof lt?e.options:e instanceof dt?R.objectValues(e.enum):e instanceof ft?Se(e._def.innerType):e instanceof ot?[void 0]:e instanceof at?[null]:e instanceof te?[void 0,...Se(e.unwrap())]:e instanceof ye?[null,...Se(e.unwrap())]:e instanceof fr||e instanceof mt?Se(e.unwrap()):e instanceof pt?Se(e._def.innerType):[],Gr=class e extends C{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==v.object)return w(r,{code:g.invalid_type,expected:v.object,received:r.parsedType}),S;let n=this.discriminator,o=r.data[n],a=this.optionsMap.get(o);return a?r.common.async?a._parseAsync({data:r.data,path:r.path,parent:r}):a._parseSync({data:r.data,path:r.path,parent:r}):(w(r,{code:g.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),S)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){let o=new Map;for(let a of r){let i=Se(a.shape[t]);if(!i.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let s of i){if(o.has(s))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(s)}`);o.set(s,a)}}return new e({typeName:A.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:o,...I(n)})}};function Wn(e,t){let r=me(e),n=me(t);if(e===t)return{valid:!0,data:e};if(r===v.object&&n===v.object){let o=R.objectKeys(t),a=R.objectKeys(e).filter(s=>o.indexOf(s)!==-1),i={...e,...t};for(let s of a){let c=Wn(e[s],t[s]);if(!c.valid)return{valid:!1};i[s]=c.data}return{valid:!0,data:i}}else if(r===v.array&&n===v.array){if(e.length!==t.length)return{valid:!1};let o=[];for(let a=0;a<e.length;a++){let i=e[a],s=t[a],c=Wn(i,s);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===v.date&&n===v.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var st=class extends C{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),o=(a,i)=>{if(Hr(a)||Hr(i))return S;let s=Wn(a.value,i.value);return s.valid?((Wr(a)||Wr(i))&&r.dirty(),{status:r.value,value:s.data}):(w(n,{code:g.invalid_intersection_types}),S)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([a,i])=>o(a,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};st.create=(e,t,r)=>new st({left:e,right:t,typeName:A.ZodIntersection,...I(r)});var he=class e extends C{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==v.array)return w(n,{code:g.invalid_type,expected:v.array,received:n.parsedType}),S;if(n.data.length<this._def.items.length)return w(n,{code:g.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),S;!this._def.rest&&n.data.length>this._def.items.length&&(w(n,{code:g.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let a=[...n.data].map((i,s)=>{let c=this._def.items[s]||this._def.rest;return c?c._parse(new re(n,i,n.path,s)):null}).filter(i=>!!i);return n.common.async?Promise.all(a).then(i=>U.mergeArray(r,i)):U.mergeArray(r,a)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};he.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new he({items:e,typeName:A.ZodTuple,rest:null,...I(t)})};var Yr=class e extends C{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==v.object)return w(n,{code:g.invalid_type,expected:v.object,received:n.parsedType}),S;let o=[],a=this._def.keyType,i=this._def.valueType;for(let s in n.data)o.push({key:a._parse(new re(n,s,n.path,s)),value:i._parse(new re(n,n.data[s],n.path,s)),alwaysSet:s in n.data});return n.common.async?U.mergeObjectAsync(r,o):U.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof C?new e({keyType:t,valueType:r,typeName:A.ZodRecord,...I(n)}):new e({keyType:Le.create(),valueType:t,typeName:A.ZodRecord,...I(r)})}},Rt=class extends C{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==v.map)return w(n,{code:g.invalid_type,expected:v.map,received:n.parsedType}),S;let o=this._def.keyType,a=this._def.valueType,i=[...n.data.entries()].map(([s,c],u)=>({key:o._parse(new re(n,s,n.path,[u,"key"])),value:a._parse(new re(n,c,n.path,[u,"value"]))}));if(n.common.async){let s=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return S;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),s.set(u.value,l.value)}return{status:r.value,value:s}})}else{let s=new Map;for(let c of i){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return S;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),s.set(u.value,l.value)}return{status:r.value,value:s}}}};Rt.create=(e,t,r)=>new Rt({valueType:t,keyType:e,typeName:A.ZodMap,...I(r)});var kt=class e extends C{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==v.set)return w(n,{code:g.invalid_type,expected:v.set,received:n.parsedType}),S;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(w(n,{code:g.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(w(n,{code:g.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let a=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return S;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let s=[...n.data.values()].map((c,u)=>a._parse(new re(n,c,n.path,u)));return n.common.async?Promise.all(s).then(c=>i(c)):i(s)}min(t,r){return new e({...this._def,minSize:{value:t,message:b.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:b.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};kt.create=(e,t)=>new kt({valueType:e,minSize:null,maxSize:null,typeName:A.ZodSet,...I(t)});var Vr=class e extends C{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==v.function)return w(r,{code:g.invalid_type,expected:v.function,received:r.parsedType}),S;function n(s,c){return dr({data:s,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,At(),Te].filter(u=>!!u),issueData:{code:g.invalid_arguments,argumentsError:c}})}function o(s,c){return dr({data:s,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,At(),Te].filter(u=>!!u),issueData:{code:g.invalid_return_type,returnTypeError:c}})}let a={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Pe){let s=this;return Y(async function(...c){let u=new J([]),l=await s._def.args.parseAsync(c,a).catch(h=>{throw u.addIssue(n(c,h)),u}),p=await Reflect.apply(i,this,l);return await s._def.returns._def.type.parseAsync(p,a).catch(h=>{throw u.addIssue(o(p,h)),u})})}else{let s=this;return Y(function(...c){let u=s._def.args.safeParse(c,a);if(!u.success)throw new J([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),p=s._def.returns.safeParse(l,a);if(!p.success)throw new J([o(l,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:he.create(t).rest(Ae.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,r,n){return new e({args:t||he.create([]).rest(Ae.create()),returns:r||Ae.create(),typeName:A.ZodFunction,...I(n)})}},ct=class extends C{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};ct.create=(e,t)=>new ct({getter:e,typeName:A.ZodLazy,...I(t)});var ut=class extends C{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return w(r,{received:r.data,code:g.invalid_literal,expected:this._def.value}),S}return{status:"valid",value:t.data}}get value(){return this._def.value}};ut.create=(e,t)=>new ut({value:e,typeName:A.ZodLiteral,...I(t)});function ma(e,t){return new lt({values:e,typeName:A.ZodEnum,...I(t)})}var lt=class e extends C{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return w(r,{expected:R.joinValues(n),received:r.parsedType,code:g.invalid_type}),S}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),n=this._def.values;return w(r,{received:r.data,code:g.invalid_enum_value,options:n}),S}return Y(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return e.create(t,{...this._def,...r})}exclude(t,r=this._def){return e.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}};lt.create=ma;var dt=class extends C{_parse(t){let r=R.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==v.string&&n.parsedType!==v.number){let o=R.objectValues(r);return w(n,{expected:R.joinValues(o),received:n.parsedType,code:g.invalid_type}),S}if(this._cache||(this._cache=new Set(R.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let o=R.objectValues(r);return w(n,{received:n.data,code:g.invalid_enum_value,options:o}),S}return Y(t.data)}get enum(){return this._def.values}};dt.create=(e,t)=>new dt({values:e,typeName:A.ZodNativeEnum,...I(t)});var Pe=class extends C{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==v.promise&&r.common.async===!1)return w(r,{code:g.invalid_type,expected:v.promise,received:r.parsedType}),S;let n=r.parsedType===v.promise?r.data:Promise.resolve(r.data);return Y(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Pe.create=(e,t)=>new Pe({type:e,typeName:A.ZodPromise,...I(t)});var ne=class extends C{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===A.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:n}=this._processInputParams(t),o=this._def.effect||null,a={addIssue:i=>{w(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),o.type==="preprocess"){let i=o.transform(n.data,a);if(n.common.async)return Promise.resolve(i).then(async s=>{if(r.value==="aborted")return S;let c=await this._def.schema._parseAsync({data:s,path:n.path,parent:n});return c.status==="aborted"?S:c.status==="dirty"?Qe(c.value):r.value==="dirty"?Qe(c.value):c});{if(r.value==="aborted")return S;let s=this._def.schema._parseSync({data:i,path:n.path,parent:n});return s.status==="aborted"?S:s.status==="dirty"?Qe(s.value):r.value==="dirty"?Qe(s.value):s}}if(o.type==="refinement"){let i=s=>{let c=o.refinement(s,a);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return s};if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?S:(s.status==="dirty"&&r.dirty(),i(s.value),{status:r.value,value:s.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>s.status==="aborted"?S:(s.status==="dirty"&&r.dirty(),i(s.value).then(()=>({status:r.value,value:s.value}))))}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!ke(i))return S;let s=o.transform(i.value,a);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:s}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>ke(i)?Promise.resolve(o.transform(i.value,a)).then(s=>({status:r.value,value:s})):S);R.assertNever(o)}};ne.create=(e,t,r)=>new ne({schema:e,typeName:A.ZodEffects,effect:t,...I(r)});ne.createWithPreprocess=(e,t,r)=>new ne({schema:t,effect:{type:"preprocess",transform:e},typeName:A.ZodEffects,...I(r)});var te=class extends C{_parse(t){return this._getType(t)===v.undefined?Y(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};te.create=(e,t)=>new te({innerType:e,typeName:A.ZodOptional,...I(t)});var ye=class extends C{_parse(t){return this._getType(t)===v.null?Y(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};ye.create=(e,t)=>new ye({innerType:e,typeName:A.ZodNullable,...I(t)});var ft=class extends C{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return r.parsedType===v.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};ft.create=(e,t)=>new ft({innerType:e,typeName:A.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...I(t)});var pt=class extends C{_parse(t){let{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Ot(o)?o.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new J(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new J(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};pt.create=(e,t)=>new pt({innerType:e,typeName:A.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...I(t)});var Lt=class extends C{_parse(t){if(this._getType(t)!==v.nan){let n=this._getOrReturnCtx(t);return w(n,{code:g.invalid_type,expected:v.nan,received:n.parsedType}),S}return{status:"valid",value:t.data}}};Lt.create=e=>new Lt({typeName:A.ZodNaN,...I(e)});var Mf=Symbol("zod_brand"),fr=class extends C{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},pr=class e extends C{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?S:a.status==="dirty"?(r.dirty(),Qe(a.value)):this._def.out._parseAsync({data:a.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?S:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(t,r){return new e({in:t,out:r,typeName:A.ZodPipeline})}},mt=class extends C{_parse(t){let r=this._def.innerType._parse(t),n=o=>(ke(o)&&(o.value=Object.freeze(o.value)),o);return Ot(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};mt.create=(e,t)=>new mt({innerType:e,typeName:A.ZodReadonly,...I(t)});function la(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function ha(e,t={},r){return e?De.create().superRefine((n,o)=>{let a=e(n);if(a instanceof Promise)return a.then(i=>{if(!i){let s=la(t,n),c=s.fatal??r??!0;o.addIssue({code:"custom",...s,fatal:c})}});if(!a){let i=la(t,n),s=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:s})}}):De.create()}var Ff={object:X.lazycreate},A;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(A||(A={}));var jf=(e,t={message:`Input not instance of ${e.name}`})=>ha(r=>r instanceof e,t),ya=Le.create,ga=et.create,Bf=Lt.create,Uf=tt.create,_a=rt.create,Hf=nt.create,Wf=Ct.create,Gf=ot.create,Yf=at.create,Vf=De.create,zf=Ae.create,Kf=ce.create,qf=Nt.create,Zf=Oe.create,Jf=X.create,Xf=X.strictCreate,Qf=it.create,ep=Gr.create,tp=st.create,rp=he.create,np=Yr.create,op=Rt.create,ap=kt.create,ip=Vr.create,sp=ct.create,cp=ut.create,up=lt.create,lp=dt.create,dp=Pe.create,fp=ne.create,pp=te.create,mp=ye.create,hp=ne.createWithPreprocess,yp=pr.create,gp=()=>ya().optional(),_p=()=>ga().optional(),xp=()=>_a().optional(),wp={string:(e=>Le.create({...e,coerce:!0})),number:(e=>et.create({...e,coerce:!0})),boolean:(e=>rt.create({...e,coerce:!0})),bigint:(e=>tt.create({...e,coerce:!0})),date:(e=>nt.create({...e,coerce:!0}))};var Ep=S;er();Tn();D();D();import{spawn as cx}from"node:child_process";var No={openai:()=>Promise.resolve().then(()=>(Vu(),Yu)),anthropic:()=>Promise.resolve().then(()=>(Ku(),zu)),openrouter:()=>Promise.resolve().then(()=>(Ju(),Zu)),"claude-cli":()=>Promise.resolve().then(()=>(Qu(),Xu)),ollama:()=>Promise.resolve().then(()=>(tl(),el))},ll={ollama:()=>Promise.resolve().then(()=>(nl(),rl)),openai:()=>Promise.resolve().then(()=>(al(),ol)),voyage:()=>Promise.resolve().then(()=>(sl(),il)),openrouter:()=>Promise.resolve().then(()=>(ul(),cl))},Io={},Co={};async function Ro(e){if(!Io[e]){let t=No[e];if(!t)throw new Error(`Unknown LLM provider: "${e}". Available: ${Object.keys(No).join(", ")}`);let r=await t();Io[e]=r.chat}return Io[e]}async function dl(e){if(!Co[e]){let t=ll[e];if(!t)throw new Error(`Unknown embedding provider: "${e}". Available: ${Object.keys(ll).join(", ")}`);let r=await t();Co[e]=r.embedBatch}return Co[e]}function fl(e,t){if(!e)return{provider:t,model:null};let r=e.indexOf(":");return r>0&&No[e.slice(0,r)]?{provider:e.slice(0,r),model:e.slice(r+1)}:{provider:t,model:e}}var ee=null,ae=null;async function pl(){let e=y.llm.ollamaHost||y.embedding.ollamaHost||"http://localhost:11434";try{return(await fetch(`${e}/api/tags`,{signal:AbortSignal.timeout(2e3)})).ok}catch{return!1}}function ux(){return new Promise(e=>{let t=cx("claude",["--version"],{stdio:"pipe"});t.on("error",()=>e(!1)),t.on("close",r=>e(r===0)),setTimeout(()=>{t.kill(),e(!1)},3e3)})}async function ml(){if(ee)return ee;if(y.llm.provider)return ee=y.llm.provider,ee;if(y.llm.openrouterApiKey)return ee="openrouter",ee;if(y.llm.apiKey)return ee="anthropic",ee;if(y.llm.openaiApiKey)return ee="openai",ee;if(await pl())return ee="ollama",ee;if(await ux())return ee="claude-cli",ee;throw new Error(`No LLM provider available. Either:
|
|
98
|
-
- Set LLM_PROVIDER (openai, anthropic, openrouter, ollama, claude-cli)
|
|
99
|
-
- Set ANTHROPIC_API_KEY, OPENAI_API_KEY, or OPENROUTER_API_KEY
|
|
100
|
-
- Start Ollama locally
|
|
101
|
-
- Install the Claude CLI (claude)`)}async function hl(){if(ae)return ae;if(y.embedding.provider)return ae=y.embedding.provider,ae;if(y.embedding.voyageApiKey)return ae="voyage",ae;if(await pl())return ae="ollama",ae;if(y.embedding.openaiApiKey)return ae="openai",ae;if(y.embedding.openrouterApiKey)return ae="openrouter",ae;throw new Error(`No embedding provider available. Either:
|
|
102
|
-
- Set EMBEDDING_PROVIDER (voyage, ollama, openai, openrouter)
|
|
103
|
-
- Set VOYAGE_API_KEY (recommended \u2014 best quality)
|
|
104
|
-
- Start Ollama locally
|
|
105
|
-
- Set OPENAI_API_KEY
|
|
106
|
-
- Set OPENROUTER_API_KEY (and EMBEDDING_MODEL like "openai/text-embedding-3-large")`)}Ve();P();import{createHash as lx}from"node:crypto";var gl=1e4,dx=500;function fx(e,t,r,n="document"){let o=lx("sha256");return o.update(e),o.update("\0"),o.update(t),o.update("\0"),o.update(n),o.update("\0"),o.update(r),o.digest("hex")}async function px(e){if(!e.length)return new Map;let t=await m("embedding_cache").whereIn("key",e).select("key","embedding");return new Map(t.map(r=>[r.key,mx(r.embedding)]))}function mx(e){return Array.isArray(e)||typeof e!="string"?e:(e.startsWith("[")?e.slice(1,-1):e).split(",").map(Number)}async function hx(e){e.length&&await m("embedding_cache").whereIn("key",e).update({hits:m.raw("hits + 1"),lastUsedAt:m.fn.now()})}async function yx(e,t,r){if(e.length){for(let{key:n,embedding:o}of e)await m.raw(`
|
|
107
|
-
INSERT INTO embedding_cache (key, provider, model, embedding, hits, created_at, last_used_at)
|
|
108
|
-
VALUES (?, ?, ?, ?, 0, NOW(), NOW())
|
|
109
|
-
ON CONFLICT (key) DO UPDATE
|
|
110
|
-
SET last_used_at = NOW(),
|
|
111
|
-
hits = embedding_cache.hits + 1
|
|
112
|
-
`,[n,t,r,V(o)]);await _x()}}var _l=0,gx=6e4;async function _x(){let e=Date.now();if(e-_l<gx)return;_l=e;let[{count:t}]=await m("embedding_cache").count("key as count"),r=Number(t);if(r<=gl)return;let n=Math.min(r-gl,dx);await m.raw(`
|
|
113
|
-
DELETE FROM embedding_cache WHERE key IN (
|
|
114
|
-
SELECT key FROM embedding_cache ORDER BY last_used_at ASC LIMIT ?
|
|
115
|
-
)
|
|
116
|
-
`,[n])}async function xl(e,t,r,n,o,a={}){if(!e.length)return[];let i=a.inputType||o?.inputType||"document",s=e.map(h=>fx(t,r,h,i)),c=await px(s),u=[],l=[],p=new Array(e.length);for(let h=0;h<e.length;h++){let _=c.get(s[h]);_?p[h]=_:(u.push(e[h]),l.push(h))}if(u.length){let h=await n(u,o),_=[];for(let E=0;E<u.length;E++){let x=l[E];p[x]=h[E],_.push({key:s[x],embedding:h[E]})}yx(_,t,r).catch(E=>{process.stderr.write(`[embedding-cache] store failed: ${E.message}
|
|
117
|
-
`)})}let f=s.filter(h=>c.has(h));return f.length&&hx(f).catch(()=>{}),p}var{dimensions:hN}=y.embedding;async function rr(e,t={}){let[r]=await ze([e],t);return r}async function ze(e,{inputType:t="document"}={}){if(!e.length)return[];let r=await hl(),n=await dl(r),o=y.embedding.model,a={...y.embedding,inputType:t};return xl(e,r,o,n,a,{inputType:t})}D();we();er();P();Mr();async function Nn(e,t){if(!t.length)return;let r=vo(t,"id"),n=r.map(o=>({factId:e,entityId:o.id,mentionType:"content",mentionCount:1}));await m("fact_entity").insert(n).onConflict(m.raw("(fact_id, entity_id, mention_type)")).merge({mentionCount:m.raw("fact_entity.mention_count + 1")}),await Ix(e,r)}async function Ix(e,t){let r=t.map(o=>o.id).filter(Boolean);if(!r.length)return;let n=await m("pod").whereIn("entityId",r).where({status:"active"}).select("id");for(let{id:o}of n)await Pr(o,e,"mention")}async function Rn(e,{limit:t=50}={}){return m("fact").join("fact_entity","fact.id","fact_entity.fact_id").where("fact_entity.entity_id",e).where("fact.status","active").select("fact.*","fact_entity.mention_count as entityMentionCount").orderBy("fact_entity.mention_count","desc").limit(t)}async function Al(e){return m("entity").join("fact_entity","entity.id","fact_entity.entity_id").where("fact_entity.fact_id",e).whereNull("entity.mergedWith").select("entity.id","entity.uid","entity.name","entity.entityType","entity.description")}async function Fr(e){if(!e.length)return new Map;let t=await m("fact_entity").whereIn("factId",e).select("factId","entityId"),r=new Map;for(let n of t)r.has(n.factId)||r.set(n.factId,[]),r.get(n.factId).push(n.entityId);return r}Cr();P();import{readFile as Lx}from"node:fs/promises";import Dx from"node:path";D();Ir();async function Ol(e){let t=await ml();return fl(e,t)}async function Ze(e,{model:t,caller:r}={}){let{provider:n,model:o}=await Ol(t),a=await Ro(n),i=Date.now();try{let s=await Ao(()=>a(e,{model:o,jsonMode:!1}),y.llm.maxRetries),c=s.cost||So(s.model,s.inputTokens,s.outputTokens);return Or({provider:n,model:s.model,caller:r,input:e,response:s.text,inputTokens:s.inputTokens,outputTokens:s.outputTokens,cost:c,durationMs:Date.now()-i,status:"success"}),s.text}catch(s){throw Or({provider:n,model:o,caller:r,input:e,response:null,inputTokens:0,outputTokens:0,cost:0,durationMs:Date.now()-i,status:"error",error:s.message}),s}}async function Ee(e,{model:t,caller:r}={}){let{provider:n,model:o}=await Ol(t),a=await Ro(n),i=Date.now();try{let s=await Ao(()=>a(e,{model:o,jsonMode:!0}),y.llm.maxRetries),c=s.cost||So(s.model,s.inputTokens,s.outputTokens);return Or({provider:n,model:s.model,caller:r,input:e,response:s.text,inputTokens:s.inputTokens,outputTokens:s.outputTokens,cost:c,durationMs:Date.now()-i,status:"success"}),$o(s.text)}catch(s){throw Or({provider:n,model:o,caller:r,input:e,response:null,inputTokens:0,outputTokens:0,cost:0,durationMs:Date.now()-i,status:"error",error:s.message}),s}}function $o(e){try{return JSON.parse(e.trim())}catch{}let t=e.match(/```(?:json)?\s*([\s\S]*?)```/);if(t)try{return JSON.parse(t[1].trim())}catch{}let r=e.match(/[\[{][\s\S]*[\]}]/);if(r)try{return JSON.parse(r[0])}catch{}return null}Ve();D();Re();var Px=Dx.join(ie,"audm-decision.md"),$x=y.memory.skipThreshold,Pl=y.memory.ambiguousThreshold;async function $l({content:e,category:t,confidence:r,importance:n,namespace:o,sourceDocumentIds:a,sourceSection:i,embedding:s}){let c=s||await rr(e),u=await Bx(c,{namespace:o});if(!u.length)return{action:"ADD",fact:await kn({content:e,category:t,confidence:r,importance:n,namespace:o,sourceDocumentIds:a,sourceSection:i,embedding:c})};let l=u[0];if(l.similarity>=$x)return{action:"SKIP",existing:l};if(l.similarity>=Pl){let f=await Mx(e,l.content);if(f==="UPDATE"){let h=await kn({content:e,category:t,confidence:r,importance:n,namespace:o,sourceDocumentIds:a,sourceSection:i,embedding:c});return await jx(l.id,h.id),await Dl({targetType:"fact",targetId:l.id,event:"UPDATE",oldContent:l.content,newContent:e,triggeredBy:`audm:sim=${l.similarity.toFixed(3)}`}),{action:"UPDATE",fact:h,supersededId:l.id}}if(f==="CONTRADICT"){let h=await kn({content:e,category:t,confidence:r,importance:n,namespace:o,sourceDocumentIds:a,sourceSection:i,embedding:c});return await Fx(l.id,h.id),await Dl({targetType:"fact",targetId:l.id,event:"CONTRADICT",oldContent:l.content,newContent:e,triggeredBy:`audm:sim=${l.similarity.toFixed(3)}`}),{action:"CONTRADICT",fact:h,contradictedId:l.id}}}return{action:"ADD",fact:await kn({content:e,category:t,confidence:r,importance:n,namespace:o,sourceDocumentIds:a,sourceSection:i,embedding:c})}}async function Mx(e,t){let n=`${await Lx(Px,"utf8")}
|
|
118
|
-
|
|
119
|
-
**EXISTING FACT:** ${t}
|
|
120
|
-
|
|
121
|
-
**NEW FACT:** ${e}`,a=(await Ze(n,{model:y.llm.decisionModel,caller:"audm"})).trim().toUpperCase();return a.includes("UPDATE")?"UPDATE":a.includes("CONTRADICT")?"CONTRADICT":"ADD"}async function kn({content:e,category:t,confidence:r,importance:n,namespace:o,sourceDocumentIds:a,sourceSection:i,embedding:s}){let c=`fact-${Ke(16)}`,[u]=await m("fact").insert({uid:c,content:e,category:t,confidence:r||"medium",importance:n||"supplementary",namespace:o,status:"active",sourceDocumentIds:a||[],sourceSection:i||null,embedding:V(s),validFrom:new Date}).returning("*");return await m.raw(`
|
|
122
|
-
UPDATE fact
|
|
123
|
-
SET search_vector = to_tsvector('english', content)
|
|
124
|
-
WHERE id = ?
|
|
125
|
-
`,[u.id]),u}async function Ml(e){let[t]=await m("fact").where({uid:e});return t||null}async function Fx(e,t){await m("fact").where({id:e}).update({status:"contradicted",contradictedById:t,validUntil:m.fn.now()})}async function jx(e,t){await m("fact").where({id:e}).update({status:"superseded",supersededById:t,validUntil:m.fn.now()})}async function Bx(e,{namespace:t,threshold:r=Pl,limit:n=5}){let o=V(e),a=`${_e("embedding")} <=> ${xe()}`;return m.transaction(async i=>{await i.raw("SET LOCAL hnsw.ef_search = 40");let{rows:s}=await i.raw(`
|
|
126
|
-
SELECT id, uid, content, category, status,
|
|
127
|
-
1 - (${a}) as similarity
|
|
128
|
-
FROM fact
|
|
129
|
-
WHERE namespace = ?
|
|
130
|
-
AND status = 'active'
|
|
131
|
-
AND embedding IS NOT NULL
|
|
132
|
-
AND 1 - (${a}) >= ?
|
|
133
|
-
ORDER BY ${a}
|
|
134
|
-
LIMIT ?
|
|
135
|
-
`,[o,t,o,r,o,n]);return s})}async function Dl({targetType:e,targetId:t,event:r,oldContent:n,newContent:o,triggeredBy:a}){await m("history").insert({targetType:e,targetId:t,event:r,oldContent:n||null,newContent:o||null,triggeredBy:a||null})}async function Fl(e){e.length&&await m.raw(`UPDATE fact_lifecycle
|
|
136
|
-
SET access_count = access_count + 1,
|
|
137
|
-
last_accessed_at = NOW(),
|
|
138
|
-
stage = CASE WHEN stage = 'stable' THEN 'editing' ELSE stage END,
|
|
139
|
-
stage_entered_at = CASE WHEN stage = 'stable' THEN NOW() ELSE stage_entered_at END
|
|
140
|
-
WHERE fact_id = ANY(?)`,[e])}async function jl(e,{limit:t=10,since:r}={}){let n=m("fact as f").join("fact_lifecycle as fl","fl.fact_id","f.id").where({"f.status":"active"}).where("fl.access_count",">",0).orderBy("fl.access_count","desc").limit(t).select("f.*");return e&&n.where({"f.namespace":e}),r&&n.where("fl.last_accessed_at",">=",r),n}async function Bl(e){let t=m("fact").where({status:"active"});e&&t.where({namespace:e});let[{count:r}]=await t.count("id as count");return Number(r)}P();async function Ul(e){if(!e||e.length<2)return;let t=[...new Set(e.filter(a=>Number.isInteger(a)))].sort((a,i)=>a-i);if(t.length<2)return;let r=[];for(let a=0;a<t.length;a++)for(let i=a+1;i<t.length;i++)r.push([t[a],t[i]]);let n=r.map(()=>"(?, ?, 1, NOW(), NOW())").join(", "),o=r.flat();await m.raw(`
|
|
141
|
-
INSERT INTO hebbian_edge (fact_a_id, fact_b_id, strength, first_seen_at, last_seen_at)
|
|
142
|
-
VALUES ${n}
|
|
143
|
-
ON CONFLICT (fact_a_id, fact_b_id)
|
|
144
|
-
DO UPDATE SET
|
|
145
|
-
strength = hebbian_edge.strength + 1,
|
|
146
|
-
last_seen_at = NOW()
|
|
147
|
-
`,o)}jo();P();async function Dn({sourceId:e,targetId:t,relationType:r,sourceFactId:n,validAt:o}){let{rows:[a]}=await m.raw(`
|
|
148
|
-
INSERT INTO relation (source_id, target_id, relation_type, source_fact_id, mention_count, valid_at, created_at, updated_at)
|
|
149
|
-
VALUES (?, ?, ?, ?, 1, ?, NOW(), NOW())
|
|
150
|
-
ON CONFLICT (source_id, target_id, relation_type) DO UPDATE SET
|
|
151
|
-
mention_count = relation.mention_count + 1,
|
|
152
|
-
source_fact_id = COALESCE(EXCLUDED.source_fact_id, relation.source_fact_id),
|
|
153
|
-
updated_at = NOW()
|
|
154
|
-
RETURNING *
|
|
155
|
-
`,[e,t,r,n||null,o||null]);return a}async function or(e,{direction:t="both",relationType:r,limit:n=50}={}){let o=s=>{let c=s==="outgoing"?"source_id":"target_id",u=s==="outgoing"?"target_id":"source_id";return m.raw(`
|
|
156
|
-
SELECT r.id AS "relationId", r.relation_type AS "relationType",
|
|
157
|
-
r.mention_count AS "mentionCount", r.valid_at AS "validAt",
|
|
158
|
-
e.id AS "entityId", e.uid, e.name, e.entity_type AS "entityType",
|
|
159
|
-
e.description, '${s}' AS direction
|
|
160
|
-
FROM relation r
|
|
161
|
-
JOIN entity e ON e.id = r.${u}
|
|
162
|
-
WHERE r.${c} = ?
|
|
163
|
-
AND r.invalid_at IS NULL
|
|
164
|
-
AND e.merged_with IS NULL
|
|
165
|
-
${r?"AND r.relation_type = ?":""}
|
|
166
|
-
ORDER BY r.mention_count DESC
|
|
167
|
-
LIMIT ?
|
|
168
|
-
`,r?[e,r,n]:[e,n])};if(t==="outgoing"){let{rows:s}=await o("outgoing");return s}if(t==="incoming"){let{rows:s}=await o("incoming");return s}let[a,i]=await Promise.all([o("outgoing"),o("incoming")]);return[...a.rows,...i.rows]}async function Wl(e){let{rows:t}=await m.raw(`
|
|
169
|
-
SELECT r.id, r.relation_type AS "relationType",
|
|
170
|
-
r.mention_count AS "mentionCount",
|
|
171
|
-
s.name AS "sourceName", s.entity_type AS "sourceType",
|
|
172
|
-
t.name AS "targetName", t.entity_type AS "targetType"
|
|
173
|
-
FROM relation r
|
|
174
|
-
JOIN entity s ON s.id = r.source_id
|
|
175
|
-
JOIN entity t ON t.id = r.target_id
|
|
176
|
-
WHERE r.source_fact_id = ?
|
|
177
|
-
AND r.invalid_at IS NULL
|
|
178
|
-
AND s.merged_with IS NULL
|
|
179
|
-
AND t.merged_with IS NULL
|
|
180
|
-
`,[e]);return t}async function Gl(){let[{count:e}]=await m("relation").whereNull("invalidAt").count("id as count");return Number(e)}P();Ve();D();var Yx={low:0,medium:1,high:2},jr=`CASE confidence
|
|
181
|
-
WHEN 'high' THEN 2
|
|
182
|
-
WHEN 'medium' THEN 1
|
|
183
|
-
ELSE 0
|
|
184
|
-
END`;function Pn({minConfidence:e="medium",pointInTime:t,categories:r}){let n=Yx[e]??1,o=[n],a="",i="";return t&&(a="AND valid_from <= ? AND (valid_until IS NULL OR valid_until > ?)",o.push(t,t)),r?.length&&(i="AND category = ANY(?)",o.push(r)),{minRank:n,temporalClause:a,categoryClause:i,filterParams:o}}async function Yl(e,{namespaces:t,limit:r=20}){let n=V(e),o=`${_e("embedding")} <=> ${xe()}`,{rows:a}=await m.raw(`
|
|
185
|
-
SELECT id, document_id AS "documentId", chunk_index AS "chunkIndex",
|
|
186
|
-
content, section_heading AS "sectionHeading", namespace,
|
|
187
|
-
1 - (${o}) as similarity
|
|
188
|
-
FROM chunk
|
|
189
|
-
WHERE namespace = ANY(?)
|
|
190
|
-
AND embedding IS NOT NULL
|
|
191
|
-
ORDER BY ${o}
|
|
192
|
-
LIMIT ?
|
|
193
|
-
`,[n,t,n,r]);return a}P();async function Vl(e,{namespaces:t,limit:r=20}){let{rows:n}=await m.raw(`
|
|
194
|
-
SELECT id, document_id AS "documentId", chunk_index AS "chunkIndex",
|
|
195
|
-
content, section_heading AS "sectionHeading", namespace,
|
|
196
|
-
ts_rank(search_vector, plainto_tsquery('english', ?)) as rank
|
|
197
|
-
FROM chunk
|
|
198
|
-
WHERE namespace = ANY(?)
|
|
199
|
-
AND search_vector @@ plainto_tsquery('english', ?)
|
|
200
|
-
ORDER BY rank DESC
|
|
201
|
-
LIMIT ?
|
|
202
|
-
`,[e,t,e,r]);return n}P();Ve();D();var zl=20,Kx=1,qx=.7,Zx=3,Jx=1.5,Xx=1,Qx=.85,ew=.7;async function Kl(e,t,{namespaces:r,limit:n=5,minConfidence:o="medium",pointInTime:a,categories:i,podIds:s=null}){let c=V(t),u=`${_e("embedding")} <=> ${xe()}`,{temporalClause:l,categoryClause:p,filterParams:f}=Pn({minConfidence:o,pointInTime:a,categories:i}),h=n*Zx,_=Array.isArray(s)&&s.length>0,E=_?`AND id = ANY(
|
|
203
|
-
SELECT member_id FROM pod_membership
|
|
204
|
-
WHERE member_type = 'fact' AND pod_id = ANY(?::int[])
|
|
205
|
-
)`:"",x=_?[s]:[],[O,...N]=f,F=[c,c,r,O,...N,...x,c,h],j=[e,e,r,O,e,...N,...x,h],k=[h,h,n],Je=`
|
|
206
|
-
WITH semantic AS (
|
|
207
|
-
SELECT id,
|
|
208
|
-
uid,
|
|
209
|
-
content, category, confidence, importance, namespace, status,
|
|
210
|
-
source_document_ids AS "sourceDocumentIds",
|
|
211
|
-
source_section AS "sourceSection",
|
|
212
|
-
created_at,
|
|
213
|
-
1 - (${u}) AS similarity,
|
|
214
|
-
ROW_NUMBER() OVER (ORDER BY ${u}) AS rank_ix
|
|
215
|
-
FROM fact
|
|
216
|
-
WHERE namespace = ANY(?)
|
|
217
|
-
AND status = 'active'
|
|
218
|
-
AND embedding IS NOT NULL
|
|
219
|
-
AND ${jr} >= ?
|
|
220
|
-
${l}
|
|
221
|
-
${p}
|
|
222
|
-
${E}
|
|
223
|
-
ORDER BY ${u}
|
|
224
|
-
LIMIT ?
|
|
225
|
-
),
|
|
226
|
-
keyword AS (
|
|
227
|
-
SELECT id,
|
|
228
|
-
uid,
|
|
229
|
-
content, category, confidence, importance, namespace, status,
|
|
230
|
-
source_document_ids AS "sourceDocumentIds",
|
|
231
|
-
source_section AS "sourceSection",
|
|
232
|
-
created_at,
|
|
233
|
-
ts_rank_cd(search_vector, plainto_tsquery('english', ?)) AS keyword_rank,
|
|
234
|
-
ROW_NUMBER() OVER (ORDER BY ts_rank_cd(search_vector, plainto_tsquery('english', ?)) DESC) AS rank_ix
|
|
235
|
-
FROM fact
|
|
236
|
-
WHERE namespace = ANY(?)
|
|
237
|
-
AND status = 'active'
|
|
238
|
-
AND ${jr} >= ?
|
|
239
|
-
AND search_vector @@ plainto_tsquery('english', ?)
|
|
240
|
-
${l}
|
|
241
|
-
${p}
|
|
242
|
-
${E}
|
|
243
|
-
ORDER BY keyword_rank DESC
|
|
244
|
-
LIMIT ?
|
|
245
|
-
),
|
|
246
|
-
fused AS (
|
|
247
|
-
SELECT COALESCE(s.id, k.id) AS id,
|
|
248
|
-
COALESCE(s.uid, k.uid) AS uid,
|
|
249
|
-
COALESCE(s.content, k.content) AS content,
|
|
250
|
-
COALESCE(s.category, k.category) AS category,
|
|
251
|
-
COALESCE(s.confidence, k.confidence) AS confidence,
|
|
252
|
-
COALESCE(s.importance, k.importance) AS importance,
|
|
253
|
-
COALESCE(s.namespace, k.namespace) AS namespace,
|
|
254
|
-
COALESCE(s.status, k.status) AS status,
|
|
255
|
-
COALESCE(s."sourceDocumentIds", k."sourceDocumentIds") AS "sourceDocumentIds",
|
|
256
|
-
COALESCE(s."sourceSection", k."sourceSection") AS "sourceSection",
|
|
257
|
-
COALESCE(s.created_at, k.created_at) AS created_at,
|
|
258
|
-
COALESCE(s.similarity, 0) AS similarity,
|
|
259
|
-
(
|
|
260
|
-
${Kx} * (1.0 / (${zl} + COALESCE(s.rank_ix, ?)))
|
|
261
|
-
+ ${qx} * (1.0 / (${zl} + COALESCE(k.rank_ix, ?)))
|
|
262
|
-
) AS rrf_raw
|
|
263
|
-
FROM semantic s
|
|
264
|
-
FULL OUTER JOIN keyword k ON s.id = k.id
|
|
265
|
-
),
|
|
266
|
-
ranked AS (
|
|
267
|
-
SELECT f.*,
|
|
268
|
-
COALESCE(fl.access_count, 0) AS access_count,
|
|
269
|
-
fl.last_accessed_at,
|
|
270
|
-
-- ACT-R activation: ln(n+1) - 0.5*ln(t_days), softplus to keep >= 0.
|
|
271
|
-
-- t_days floor of 0.01 prevents log(0). Recently-accessed facts win ties.
|
|
272
|
-
ln(1.0 + exp(
|
|
273
|
-
ln(COALESCE(fl.access_count, 0) + 1.0)
|
|
274
|
-
- 0.5 * ln(
|
|
275
|
-
GREATEST(
|
|
276
|
-
EXTRACT(epoch FROM (now() - COALESCE(fl.last_accessed_at, f.created_at))) / 86400.0,
|
|
277
|
-
0.01
|
|
278
|
-
)
|
|
279
|
-
)
|
|
280
|
-
)) AS activation,
|
|
281
|
-
CASE f.importance WHEN 'vital' THEN ${Jx} ELSE 1.0 END AS importance_mult,
|
|
282
|
-
CASE f.confidence
|
|
283
|
-
WHEN 'high' THEN ${Xx}
|
|
284
|
-
WHEN 'medium' THEN ${Qx}
|
|
285
|
-
WHEN 'low' THEN ${ew}
|
|
286
|
-
ELSE 1.0
|
|
287
|
-
END AS confidence_mult
|
|
288
|
-
FROM fused f
|
|
289
|
-
LEFT JOIN fact_lifecycle fl ON fl.fact_id = f.id
|
|
290
|
-
)
|
|
291
|
-
SELECT id, uid, content, category, confidence, importance, namespace, status,
|
|
292
|
-
"sourceDocumentIds", "sourceSection", similarity,
|
|
293
|
-
rrf_raw,
|
|
294
|
-
access_count,
|
|
295
|
-
last_accessed_at AS "lastAccessedAt",
|
|
296
|
-
activation,
|
|
297
|
-
(rrf_raw * activation * importance_mult * confidence_mult) AS final_score
|
|
298
|
-
FROM ranked
|
|
299
|
-
ORDER BY final_score DESC,
|
|
300
|
-
CASE WHEN importance = 'vital' THEN 0 ELSE 1 END
|
|
301
|
-
LIMIT ?
|
|
302
|
-
`,z=[...F,...j,...k],{rows:Tt}=await m.raw(Je,z);if(!Tt.length)return[];let cr=Tt[0].final_score||Tt[0].rrf_raw||1;return Tt.map(Xe=>({...Xe,rrfScore:Math.round(Number(Xe.final_score||Xe.rrf_raw)/Number(cr)*100)/100}))}P();async function ql(e){let t=e.map(o=>o.id),r=await Fr(t),n=new Set;for(let o of r.values())for(let a of o)n.add(a);return n.size?m("entity").whereIn("id",[...n]).whereNull("mergedWith").select("id","uid","name","entityType","description"):[]}async function Zl(e,{limit:t=10}={}){if(!e.length)return[];let r=await m("relation").where(function(){this.whereIn("sourceId",e).orWhereIn("targetId",e)}).whereNull("invalidAt").select("*").limit(t*3),n=new Set(e),o=new Set,a=new Map;for(let p of r){let f=n.has(p.sourceId)?p.targetId:p.sourceId;o.add(f),a.has(f)||a.set(f,p)}if(!o.size)return[];let i=await m("entity").whereIn("id",[...o]).whereNull("mergedWith").select("id","name"),s=new Map(i.map(p=>[p.id,p.name])),c=await m("fact").join("fact_entity","fact.id","fact_entity.factId").whereIn("fact_entity.entityId",[...o]).where("fact.status","active").select("fact.*","fact_entity.entityId").orderBy("fact_entity.mentionCount","desc").limit(t*3),u=new Set,l=[];for(let p of c){if(u.has(p.id))continue;u.add(p.id);let f=a.get(p.entityId),h=s.get(p.entityId)||"unknown",_=f?.relationType||"related";if(l.push({...p,relationPath:`${h} (${_})`,graphDistance:1}),l.length>=t)break}return l}function Jl(e,t,r,n){let o=new Set(r),a=e.map(s=>({...s,resultType:"direct"})),i=t.filter(s=>!e.some(c=>c.id===s.id)).map(s=>({...s,rrfScore:(s.rrfScore||.1)*.5,resultType:"related"}));return[...a,...i].slice(0,n)}var ar=class{#e=new Map;#t;#r;constructor({maxSize:t=100,ttlMs:r=300*1e3}={}){this.#t=t,this.#r=r}get(t){let r=this.#e.get(t);if(r){if(Date.now()-r.timestamp>this.#r){this.#e.delete(t);return}return r.value}}set(t,r){if(this.#e.size>=this.#t){let n=this.#e.keys().next().value;this.#e.delete(n)}this.#e.set(t,{value:r,timestamp:Date.now()})}};D();var tw=5,Xl=new ar({maxSize:100,ttlMs:300*1e3});async function Ql(e){let t=Xl.get(e);if(t)return t;let r=`You are a search query expander for a personal knowledge base.
|
|
303
|
-
|
|
304
|
-
Given the user's query, generate 3-5 alternative search queries that would help find ALL relevant information \u2014 including facts that don't literally match the query but are semantically related.
|
|
305
|
-
|
|
306
|
-
Think about:
|
|
307
|
-
- Synonyms and rephrased versions
|
|
308
|
-
- Inverse/negative framings (if someone asks "what should I use", also search for "what to avoid")
|
|
309
|
-
- Related concepts that would inform the answer
|
|
310
|
-
- Specific terms someone might have used when storing this knowledge
|
|
311
|
-
|
|
312
|
-
User query: "${e}"
|
|
313
|
-
|
|
314
|
-
Respond with ONLY a JSON array of strings. Do not include the original query.`;try{let n=await Ee(r,{model:y.llm.extractionModel,caller:"query-expander"});if(!Array.isArray(n))return[e];let o=n.filter(i=>typeof i=="string"&&i.trim()).slice(0,tw),a=o.length?[e,...o]:[e];return Xl.set(e,a),a}catch(n){return console.error("[query-expander] Failed:",n.message),[e]}}import{readFile as rw}from"node:fs/promises";import{join as nw}from"node:path";D();Re();var ow=nw(ie,"query-router.md"),Bo=new ar({maxSize:200,ttlMs:600*1e3}),aw=["preference","factual","entity_lookup","exploratory","temporal"],td={preference:{categories:["preference","opinion","personal"],expand:!1,useGraph:!1,limit:null},factual:{categories:[],expand:!1,useGraph:!1,limit:null},entity_lookup:{categories:[],expand:!1,useGraph:!0,limit:null},exploratory:{categories:[],expand:!0,useGraph:!0,limit:15},temporal:{categories:[],expand:!1,useGraph:!1,limit:null}};async function rd(e){let t=e.trim().toLowerCase(),r=Bo.get(t);if(r)return r;let o=`${await rw(ow,"utf8")}
|
|
315
|
-
|
|
316
|
-
---
|
|
317
|
-
|
|
318
|
-
Query: ${e}
|
|
319
|
-
|
|
320
|
-
---
|
|
321
|
-
|
|
322
|
-
Respond with ONLY a JSON object: { "intent": "preference|factual|entity_lookup|exploratory|temporal", "categories": [...], "entities": [...], "expand": bool, "pointInTime": null or "YYYY-MM-DD", "reasoning": "..." }`;try{let a=await Ee(o,{model:y.llm.extractionModel,caller:"query-router"});if(!a||!aw.includes(a.intent)){let c=ed("factual",{});return Bo.set(t,c),c}let i=td[a.intent],s={intent:a.intent,categories:Array.isArray(a.categories)&&a.categories.length?a.categories:i.categories,entities:Array.isArray(a.entities)?a.entities:[],expand:typeof a.expand=="boolean"?a.expand:i.expand,useGraph:i.useGraph,limit:i.limit,pointInTime:a.pointInTime||null,reasoning:a.reasoning||""};return Bo.set(t,s),s}catch(a){return console.error("[query-router] Failed:",a.message),ed("factual",{reasoning:`Fallback \u2014 ${a.message}`})}}function ed(e,t={}){let r=td[e];return{intent:e,categories:r.categories,entities:[],expand:r.expand,useGraph:r.useGraph,limit:r.limit,pointInTime:null,reasoning:"",...t}}Re();var iw=["name"],sw=new Set(["private","shared","public"]),cw=new Set(["singleton-live","multi-active","rolling-window","always"]),uw=new Set(["origin-only","shared-allowlist","open"]),nd=new Map;function od(e){for(let t of iw)if(!e[t])throw new Error(`Pod kind missing required field: ${t}`);if(e.visibility&&!sw.has(e.visibility))throw new Error(`Pod kind ${e.name}: invalid visibility ${e.visibility}`);if(e.activeMode&&!cw.has(e.activeMode))throw new Error(`Pod kind ${e.name}: invalid activeMode ${e.activeMode}`);if(e.writePolicy&&!uw.has(e.writePolicy))throw new Error(`Pod kind ${e.name}: invalid writePolicy ${e.writePolicy}`);nd.set(e.name,lw(e))}function lw(e){return{visibility:"private",activeMode:"multi-active",hotContextBudget:0,retrievalWeights:{recency:1,relevance:1},importanceDefault:2,ttlDays:null,writePolicy:"origin-only",lifecycle:{},...e}}async function ad(e={}){let t=[];for(let r of nd.values())if(typeof r.resolveActiveScope=="function")try{let n=await r.resolveActiveScope(e);Array.isArray(n)&&n.length>0&&t.push({kind:r,scope:n})}catch{}return t}Wo();P();D();var bw=1440*60*1e3,fd={name:"person",description:"A person you have a working relationship with",identityField:"primary_handle",attrsSchema:{platforms:"object",role:"string",relationship:"string",notes:"string"},visibility:"private",activeMode:"rolling-window",hotContextBudget:4,retrievalWeights:{recency:1,relevance:.8},importanceDefault:3,ttlDays:null,schemaDocPath:"kinds/person.schema.md",writePolicy:"origin-only",resolveActiveScope:async(e={})=>{let t=e.namespace||y.defaults.namespace;try{let r=new Date(Date.now()-bw);return(await m("pod as p").join("pod_membership as pm","pm.pod_id","p.id").join("fact_lifecycle as fl","fl.fact_id","pm.member_id").where("pm.memberType","fact").where("p.podType","person").where("p.namespace",t).where("p.status","active").where("fl.lastAccessedAt",">=",r).distinct("p.uid")).map(o=>o.uid)}catch{return[]}}};Ko();P();D();var Nw="playbook",hd={name:"playbook",description:"A reusable workflow or debug recipe (procedural memory)",identityField:"slug",attrsSchema:{slug:"string",project:"string",description:"string",tags:"array"},visibility:"shared",activeMode:"always",hotContextBudget:3,retrievalWeights:{recency:.3,relevance:1},importanceDefault:3,ttlDays:null,schemaDocPath:"kinds/playbook.schema.md",writePolicy:"origin-only",resolveActiveScope:async(e={})=>{let t=e.namespace||y.defaults.namespace,r=await Rw(e);try{let o=await m("pod").where({podType:Nw,namespace:t,status:"active"}).select("uid","attrs");return r?o.filter(i=>{let s=kw(i.attrs);return!s.project||s.project===r}).map(i=>i.uid):o.map(i=>i.uid)}catch{return[]}}};async function Rw(e){if(e.project)return e.project;if(!e.cwd)try{let{getActiveCursor:t}=await Promise.resolve().then(()=>(Mn(),Ho)),r=await t();e={...e,cwd:r?.cwd}}catch{return null}if(!e.cwd)return null;try{let{deriveProjectRoot:t}=await Promise.resolve().then(()=>(Ko(),md)),r=t(e.cwd);return r?r.split("/").pop():null}catch{return null}}function kw(e){if(!e)return{};if(typeof e=="object")return e;try{return JSON.parse(e)}catch{return{}}}P();D();var Lw=["__virtual:vital__"],yd={name:"vital",description:"Facts marked importance=5 (vital), surfaced globally",identityField:null,attrsSchema:{},visibility:"public",activeMode:"always",hotContextBudget:6,retrievalWeights:{recency:.5,relevance:1},importanceDefault:5,ttlDays:null,schemaDocPath:"kinds/vital.schema.md",writePolicy:"open",resolveActiveScope:async()=>Lw,fetchFacts:async(e={},{slots:t=8,namespace:r}={})=>{let n=r||e.namespace||y.defaults.namespace;return m("fact as f").leftJoin("fact_lifecycle as fl","fl.fact_id","f.id").where({"f.status":"active","f.namespace":n}).where(o=>{o.where("f.importance","vital").orWhere("f.importance_score",5)}).orderByRaw("COALESCE(fl.access_count, 0) DESC, f.created_at DESC").limit(t).pluck("f.content")}};var Dw=[dd,Vo,fd,hd,yd],gd=!1;function Pw(){if(!gd){for(let e of Dw)od(e);gd=!0}}Pw();P();var qo=20,$w=1,Mw=.7,Fw=60;async function _d(e,{namespaces:t,limit:r=5,minConfidence:n="medium",useGraph:o=!1,includeChunks:a=!1,pointInTime:i,expand:s=!1,route:c=!0,categories:u,synthesize:l=y.search.synthesize,podScope:p=null,ctx:f={}}={}){if(!jw(e))return Bw();l&&(a=!0);let h=null;c&&(h=await rd(e),o=o||h.useGraph,s=s||h.expand,r=h.limit||r,i=i||h.pointInTime,u=u||(h.categories.length?h.categories:void 0));let _=await Gw(e,t),E=await Ww(p,{...f,namespace:t?.[0]}),x;_?x=await Yw(_,e,{namespaces:t,limit:r,minConfidence:n,includeChunks:a,pointInTime:i,categories:u,podIds:E}):x=await Kw(e,{namespaces:t,limit:r,minConfidence:n,useGraph:o,includeChunks:a,pointInTime:i,expand:s,categories:u,podIds:E});let O=x.facts.map(N=>N.id).filter(Boolean);if(Fl(O).catch(N=>console.error("[access-tracking]",N.message)),Ul(O.slice(0,8)).catch(N=>console.error("[hebbian]",N.message)),y.hebbian.entity.enabled&&O.length>=2&&Hw(O).catch(N=>console.error("[hebbian-entity]",N.message)),l)try{x.synthesized=await Uw(e,x)}catch(N){console.error("[synthesizer] failed:",N.message),x.synthesized=null}return x}function jw(e){let t=String(e||"").trim();return t?!/^[*%_?\s]+$/.test(t):!1}function Bw(){return{facts:[],chunks:[],matchedEntity:null,relatedEntities:[]}}async function Uw(e,{facts:t,chunks:r}){let n=[];if(t.slice(0,10).forEach((i,s)=>{n.push(`[F${s+1}] (${i.category}) ${i.content}`)}),r.length&&r.slice(0,15).forEach((i,s)=>{let c=(i.content||"").replace(/\s+/g," ").trim();c&&n.push(`[C${s+1}] ${c.slice(0,2e3)}`)}),!n.length)return"No retrieved evidence \u2014 nothing to synthesize.";let o=`You are answering a question from a personal-memory system.
|
|
323
|
-
Each retrieved item is labeled [F#] (a stored fact) or [C#] (a raw conversation chunk
|
|
324
|
-
that may include user/assistant turns and dates).
|
|
325
|
-
|
|
326
|
-
Question: ${e}
|
|
327
|
-
|
|
328
|
-
Retrieved memory items:
|
|
329
|
-
${n.join(`
|
|
330
|
-
`)}
|
|
331
|
-
|
|
332
|
-
Instructions:
|
|
333
|
-
- Read the chunks carefully \u2014 the answer is often a specific phrase or date inside one of them, not always pre-summarized as a fact.
|
|
334
|
-
- Reason step-by-step internally for temporal questions ("first", "before", "after", "how many days") \u2014 compare the dates explicitly.
|
|
335
|
-
- Cite items in square brackets where they directly support the answer, e.g. [C2].
|
|
336
|
-
- Only respond "Not in retrieved memory." if you genuinely cannot find the information after carefully reading every chunk. Prefer a careful answer with citation over refusal.
|
|
337
|
-
- Plain text only, no headers. Direct answer first, then a short justification if needed. 1-4 sentences total.`,a=y.search.synthesizeModel||y.llm.extractionModel||void 0;return Ze(o,{model:a,caller:"synthesizer"})}async function Hw(e){let t=await Fr(e.slice(0,8)),r=[];for(let o of t.values())for(let a of o)r.push(a);let n=[...new Set(r)].slice(0,y.hebbian.entity.maxWriteEntities);await Mo(n)}async function Ww(e,t={}){if(e==null||e==="global")return null;if(e==="auto"){let n=(await ad(t)).flatMap(a=>a.scope).filter(a=>typeof a=="string"&&!a.startsWith("__virtual:"));return n.length===0?[]:(await m("pod").whereIn("uid",n).select("id")).map(a=>a.id)}if(Array.isArray(e)){if(e.length===0)return[];if(e.every(o=>typeof o=="number"))return e;let r=e.filter(o=>typeof o=="string");return r.length===0?[]:(await m("pod").where(function(){this.whereIn("uid",r).orWhereIn("name",r)}).select("id")).map(o=>o.id)}return null}async function Gw(e,t){if(e.length<2||e.length>Fw)return null;let r=t[0]||y.defaults.namespace,n=await xt(e,r);return n||(await wt(e,{namespace:r,limit:1}))[0]||null}async function Yw(e,t,{namespaces:r,limit:n,minConfidence:o,includeChunks:a,pointInTime:i,categories:s,podIds:c}){let u=Vw(t,e),l=await ze(u,{inputType:"query"}),[p,f,...h]=await Promise.all([Rn(e.id,{limit:n}),or(e.id,{limit:15}),...u.map((k,Je)=>wd(k,{queryEmbedding:l[Je],namespaces:r,limit:n,minConfidence:o,includeChunks:a,pointInTime:i,categories:s,podIds:c}))]),_=p.map(k=>({...k,source:"entity"})),E=Fn(h.map(k=>k.facts),n*2),x=new Set(_.map(k=>k.id)),O=E.filter(k=>!x.has(k.id)).map(k=>({...k,source:"search"})),N=[..._,...O].slice(0,n);if(y.hebbian.entity.enabled&&N.length>=2)try{N=await xd(N,{seedEntityIds:[e.id]})}catch(k){console.error("[hebbian-entity-boost]",k.message)}let F=a?Fn(h.map(k=>k.chunks||[]),n):[],j=f.map(k=>({id:k.entityId,name:k.name,type:k.entityType,relation:k.relationType,direction:k.direction,mentions:k.mentionCount}));return{facts:N,chunks:F,matchedEntity:{id:e.id,name:e.name,type:e.entityType,mentions:e.mentionCount,description:e.description||null,aliases:e.aliases||[]},relatedEntities:j}}function Vw(e,t){let r=[e],n=(t.aliases||[]).filter(i=>typeof i=="string"&&i.trim());if(!n.length)return r;let o=(t.name||"").trim(),a=new Set([e.toLowerCase()]);for(let i of n){let s=e;if(o){let c=new RegExp(`\\b${zw(o)}\\b`,"gi");if(c.test(s))s=s.replace(c,i);else{a.has(i.toLowerCase())||(r.push(i),a.add(i.toLowerCase()));continue}}a.has(s.toLowerCase())||(r.push(s),a.add(s.toLowerCase()))}return r}function zw(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}async function Kw(e,{namespaces:t,limit:r,minConfidence:n,useGraph:o,includeChunks:a,pointInTime:i,expand:s=!1,categories:c,podIds:u}){let l=s?await Ql(e):[e],p=await ze(l,{inputType:"query"}),f=await Promise.all(l.map((E,x)=>wd(E,{queryEmbedding:p[x],namespaces:t,limit:r,minConfidence:n,includeChunks:a,pointInTime:i,categories:c,podIds:u}))),h=Fn(f.map(E=>E.facts),r);if(h=h.map(E=>({...E,source:"search"})),y.hebbian.entity.enabled&&h.length>=2)try{h=await xd(h)}catch(E){console.error("[hebbian-entity-boost]",E.message)}if(o&&h.length)try{let E=await ql(h.slice(0,5));if(E.length){let x=await qw(E.map(N=>N.id)),O=await Zl(x,{limit:5});h=Jl(h,O,x,r)}}catch(E){console.error("[graph-enhancement] Failed:",E.message)}let _=a?Fn(f.map(E=>E.chunks),r):[];return{facts:h,chunks:_,matchedEntity:null,relatedEntities:[]}}async function xd(e,t={}){let r=e.map(f=>f.id).filter(Boolean);if(r.length<2)return e;let n=await Fr(r);if(!n.size)return e;let o,a;if(t.seedEntityIds?.length)o=t.seedEntityIds,a=e;else{let f=t.seedFactCount??3,h=[];for(let _ of e.slice(0,f)){let E=n.get(_.id)||[];for(let x of E)h.push(x)}o=h,a=e.slice(f)}if(!o.length)return e;let i=new Set;for(let f of a){let h=n.get(f.id)||[];for(let _ of h)i.add(_)}if(!i.size)return e;let s=await Fo([...new Set(o)],[...i]);if(!s.size)return e;let c=new Map,u=0;for(let f of e){let h=n.get(f.id)||[],_=0;for(let E of h){let x=s.get(E)||0;x>_&&(_=x)}c.set(f.id,_),_>u&&(u=_)}if(u===0)return e;let l=y.hebbian.entity.rrfWeight;return e.map(f=>{let h=(c.get(f.id)||0)/u,_=(f.rrfScore||0)+l*h;return{...f,rrfScore:Math.round(_*100)/100,coRetrievalBoost:Math.round(h*100)/100}}).sort((f,h)=>(h.rrfScore||0)-(f.rrfScore||0))}async function qw(e){let t=y.hebbian.entity.expandPerSeed;if(!t||!e.length)return e;let{getCoRetrievedEntities:r}=await Promise.resolve().then(()=>(jo(),Hl)),n=await Promise.all(e.map(a=>r(a,{limit:t}).catch(()=>[]))),o=new Set(e);for(let a of n)for(let i of a)o.add(Number(i.partnerId));return[...o]}function Fn(e,t){let r={},n={};for(let i of e)for(let[s,c]of i.entries())n[c.id]=c,r[c.id]=(r[c.id]||0)+1/(qo+s+1);let o=Object.entries(r).sort(([,i],[,s])=>s-i),a=o.length?o[0][1]:1;return o.slice(0,t).map(([i,s])=>({...n[i],rrfScore:Math.round(s/a*100)/100}))}async function wd(e,{queryEmbedding:t,namespaces:r,limit:n,minConfidence:o,includeChunks:a=!1,pointInTime:i,categories:s,podIds:c}){let u=t||await rr(e,{inputType:"query"}),l=Kl(e,u,{namespaces:r,limit:n,minConfidence:o,pointInTime:i,categories:s,podIds:c}),p=a?[Yl(u,{namespaces:r,limit:n}),Vl(e,{namespaces:r,limit:n})]:[],[f,...h]=await Promise.all([l,...p]),_=a&&h.length===2?Zw(h[0],h[1],n):[];return{facts:f,chunks:_}}function Zw(e,t,r){let n={},o={...bo(e,"id"),...bo(t,"id")};e.forEach((s,c)=>{n[s.id]=(n[s.id]||0)+$w/(qo+c+1)}),t.forEach((s,c)=>{n[s.id]=(n[s.id]||0)+Mw/(qo+c+1)});let a=Object.entries(n).sort(([s,c],[u,l])=>{if(c!==l)return l-c;let p=o[s]?.importance==="vital"?1:0;return(o[u]?.importance==="vital"?1:0)-p}),i=a.length?a[0][1]:1;return a.slice(0,r).map(([s,c])=>({...o[s],rrfScore:Math.round(c/i*100)/100}))}D();function L(e){return{content:[{type:"text",text:e}]}}function ve(e,t){return!e||e.length<=t?e:e.slice(0,t)+"..."}var sr=200;function Ed(e){e.tool("search",`Search Sigil knowledge base for facts across all ingested documents.
|
|
2
|
+
import { createRequire as __sigilCreateRequire } from 'node:module'; const require = __sigilCreateRequire(import.meta.url);
|
|
3
|
+
var no=Object.defineProperty;var Fe=(t,e)=>()=>(t&&(e=t(t=0)),e);var dr=(t,e)=>{for(var r in e)no(t,r,{get:e[r],enumerable:!0})};import{fileURLToPath as Wc}from"node:url";import{dirname as In,join as I}from"node:path";import{existsSync as Cn}from"node:fs";import{homedir as Hc}from"node:os";function qc(){let t=In(Wc(import.meta.url));for(let e=0;e<10;e++){if(Cn(I(t,"package.json"))&&Cn(I(t,"prompts")))return t;let r=In(t);if(r===t)break;t=r}return process.cwd()}var Me,o_,s_,En,$,i_,f_,u_,c_,d_,l_,p_,m_,h_,De,Vt,Wt,g_,y_,x_,__,v_,b_,w_,$n,T_,k_,xt=Fe(()=>{Me=qc(),o_=I(Me,"prompts"),s_=I(Me,"src","db","migrations"),En=Hc(),$=I(En,".sigil"),i_=I($,".env"),f_=I($,"db"),u_=I($,"CLAUDE.md"),c_=I($,"schemas"),d_=I($,".hook-errors.log"),l_=I($,".last-clean-doctor"),p_=I($,".active-session.json"),m_=I($,".stop-cursor.json"),h_=I($,".hook-dedup.json"),De=I($,"sock"),Vt=I($,"sigild.pid"),Wt=I($,"sigild.log"),g_=I($,"heartbeat.json"),y_=I($,"onboarding-state.json"),x_=I($,"gui.token"),__=I(Me,"dist","gui"),v_=I(Me,"src","gui","web"),b_=I($,"iroh"),w_=I($,"identity.key"),$n=I(En,".claude"),T_=I($n,"settings.json"),k_=I($n,"CLAUDE.md")});import{readFile as Kc,writeFile as A_,unlink as Rn,mkdir as I_}from"node:fs/promises";import{existsSync as Pn}from"node:fs";function Yc(t){if(!t||!Number.isFinite(t))return!1;try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}async function Jc(){if(!Pn(Vt))return null;try{let t=(await Kc(Vt,"utf8")).trim(),e=Number(t);return Number.isFinite(e)?e:null}catch{return null}}async function Xc(){try{await Rn(Vt)}catch{}}async function Qc(){try{await Rn(De)}catch{}}async function Nn(){let t=await Jc();return t&&Yc(t)?t:(t&&await Xc(),Pn(De)&&await Qc(),null)}var jn=Fe(()=>{xt()});import{existsSync as ed}from"node:fs";import{dirname as td,join as fr}from"node:path";import{fileURLToPath as rd}from"node:url";function Mn(){let t=[fr(Me,"dist","daemon.js"),fr(Me,"src","daemon","index.js"),fr(td(rd(import.meta.url)),"..","daemon","index.js")];for(let e of t)if(ed(e))return e;throw new Error("cannot locate daemon entry point (looked in dist/ and src/daemon/)")}var Dn=Fe(()=>{xt()});import{connect as ad}from"node:net";import{randomUUID as nd}from"node:crypto";function Ht({path:t=De,timeoutMs:e=3e4}={}){return new Promise((r,a)=>{let n=ad(t),o=new Map,s="",i=!1;n.setEncoding("utf8"),n.once("connect",()=>{n.off("error",f),r(u())});function f(d){a(d)}n.once("error",f),n.on("data",d=>{s+=d;let m;for(;(m=s.indexOf(`
|
|
4
|
+
`))!==-1;){let g=s.slice(0,m);if(s=s.slice(m+1),!g.trim())continue;let _;try{_=JSON.parse(g)}catch{continue}let A=o.get(_.id);A&&(o.delete(_.id),clearTimeout(A.timer),_.ok?A.resolve(_):A.reject(new ur(_.error||{})))}}),n.on("close",()=>{i=!0;for(let[,d]of o)clearTimeout(d.timer),d.reject(new Error("daemon connection closed"));o.clear()}),n.on("error",()=>{});function u(){return{call(d,m){if(i)return Promise.reject(new Error("client is closed"));let g=nd(),_=process.env.SIGIL_AGENT||null,A=JSON.stringify({id:g,method:d,params:m,agent:_})+`
|
|
5
|
+
`;return new Promise((k,S)=>{let P=setTimeout(()=>{o.delete(g)&&S(new Error(`rpc timeout after ${e}ms: ${d}`))},e);o.set(g,{resolve:k,reject:S,timer:P}),n.write(A)})},close(){return new Promise(d=>{if(i)return d();n.end(()=>d())})}}}})}var ur,Ln=Fe(()=>{xt();ur=class extends Error{constructor({code:e,message:r,stack:a}){super(r||e||"rpc error"),this.name="SigilRpcError",this.code=e||"handler_error",a&&(this.remoteStack=a)}}});import{spawn as od}from"node:child_process";import{existsSync as sd,openSync as Fn,closeSync as Gn,mkdirSync as id}from"node:fs";import{setTimeout as fd}from"node:timers/promises";async function Bn({quiet:t=!1}={}){return await zn()?Ht():(t||process.stderr.write(`[sigil] daemon not running, starting it...
|
|
6
|
+
`),await dd(),await ld(),Ht())}async function zn(){if(!sd(De))return!1;try{let t=await Ht({timeoutMs:1e3});return await t.call("ping",{}),await t.close(),!0}catch{return!1}}async function dd(){id($,{recursive:!0}),await Nn();let t=Mn(),e=Fn(Wt,"a"),r=Fn(Wt,"a");od(process.execPath,[t],{detached:!0,stdio:["ignore",e,r],env:{...process.env,SIGIL_DAEMON_AUTOSPAWN:"1"}}).unref();try{Gn(e)}catch{}try{Gn(r)}catch{}}async function ld(){let t=Date.now()+Un,e=ud;for(;Date.now()<t;){if(await zn())return;await fd(e),e=Math.min(e*2,cd)}throw new Error(`daemon did not become ready within ${Un}ms \u2014 check ${Wt}`)}var Un,ud,cd,Zn=Fe(()=>{xt();jn();Dn();Ln();Un=5e3,ud=25,cd=400});var Wn={};dr(Wn,{closeDaemonConnection:()=>hd,daemonCall:()=>R});async function Vn(){return ut||(ft||(ft=Bn({quiet:!0}).then(t=>(ut=t,t)).catch(t=>{throw ft=null,t})),ft)}function md(t){return t?t.code&&pd.has(t.code)?!0:/^daemon connection closed/i.test(t.message||""):!1}async function R(t,e){let r=await Vn();try{let{data:a}=await r.call(t,e??{});return a}catch(a){if(md(a)){ut=null,ft=null;let n=await Vn(),{data:o}=await n.call(t,e??{});return o}throw a}}async function hd(){let t=ut;ut=null,ft=null,t&&await t.close()}var ft,ut,pd,H=Fe(()=>{Zn();ft=null,ut=null;pd=new Set(["ECONNREFUSED","ENOENT","EPIPE","ECONNRESET"])});import{config as vd}from"dotenv";import{resolve as cr,dirname as ao}from"node:path";import{fileURLToPath as bd}from"node:url";import{existsSync as wd}from"node:fs";import"dotenv/config";import{McpServer as yd}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as xd}from"@modelcontextprotocol/sdk/server/stdio.js";var y={};dr(y,{BRAND:()=>$o,DIRTY:()=>xe,EMPTY_PATH:()=>fo,INVALID:()=>x,NEVER:()=>hs,OK:()=>M,ParseStatus:()=>j,Schema:()=>w,ZodAny:()=>fe,ZodArray:()=>re,ZodBigInt:()=>ve,ZodBoolean:()=>be,ZodBranded:()=>lt,ZodCatch:()=>Re,ZodDate:()=>we,ZodDefault:()=>$e,ZodDiscriminatedUnion:()=>Tt,ZodEffects:()=>z,ZodEnum:()=>Ce,ZodError:()=>L,ZodFirstPartyTypeKind:()=>v,ZodFunction:()=>St,ZodIntersection:()=>Oe,ZodIssueCode:()=>c,ZodLazy:()=>Ae,ZodLiteral:()=>Ie,ZodMap:()=>Ve,ZodNaN:()=>He,ZodNativeEnum:()=>Ee,ZodNever:()=>Z,ZodNull:()=>ke,ZodNullable:()=>Y,ZodNumber:()=>_e,ZodObject:()=>F,ZodOptional:()=>U,ZodParsedType:()=>p,ZodPipeline:()=>pt,ZodPromise:()=>ue,ZodReadonly:()=>Pe,ZodRecord:()=>kt,ZodSchema:()=>w,ZodSet:()=>We,ZodString:()=>ie,ZodSymbol:()=>ze,ZodTransformer:()=>z,ZodTuple:()=>K,ZodType:()=>w,ZodUndefined:()=>Te,ZodUnion:()=>Se,ZodUnknown:()=>te,ZodVoid:()=>Ze,addIssueToContext:()=>l,any:()=>Go,array:()=>Zo,bigint:()=>jo,boolean:()=>wr,coerce:()=>ms,custom:()=>_r,date:()=>Mo,datetimeRegex:()=>yr,defaultErrorMap:()=>Q,discriminatedUnion:()=>qo,effect:()=>ss,enum:()=>as,function:()=>es,getErrorMap:()=>Ge,getParsedType:()=>q,instanceof:()=>Po,intersection:()=>Ko,isAborted:()=>bt,isAsync:()=>Ue,isDirty:()=>wt,isValid:()=>se,late:()=>Ro,lazy:()=>ts,literal:()=>rs,makeIssue:()=>dt,map:()=>Xo,nan:()=>No,nativeEnum:()=>ns,never:()=>Bo,null:()=>Fo,nullable:()=>fs,number:()=>br,object:()=>Vo,objectUtil:()=>qt,oboolean:()=>ps,onumber:()=>ls,optional:()=>is,ostring:()=>ds,pipeline:()=>cs,preprocess:()=>us,promise:()=>os,quotelessJson:()=>oo,record:()=>Jo,set:()=>Qo,setErrorMap:()=>io,strictObject:()=>Wo,string:()=>vr,symbol:()=>Do,transformer:()=>ss,tuple:()=>Yo,undefined:()=>Lo,union:()=>Ho,unknown:()=>Uo,util:()=>T,void:()=>zo});var T;(function(t){t.assertEqual=n=>{};function e(n){}t.assertIs=e;function r(n){throw new Error}t.assertNever=r,t.arrayToEnum=n=>{let o={};for(let s of n)o[s]=s;return o},t.getValidEnumValues=n=>{let o=t.objectKeys(n).filter(i=>typeof n[n[i]]!="number"),s={};for(let i of o)s[i]=n[i];return t.objectValues(s)},t.objectValues=n=>t.objectKeys(n).map(function(o){return n[o]}),t.objectKeys=typeof Object.keys=="function"?n=>Object.keys(n):n=>{let o=[];for(let s in n)Object.prototype.hasOwnProperty.call(n,s)&&o.push(s);return o},t.find=(n,o)=>{for(let s of n)if(o(s))return s},t.isInteger=typeof Number.isInteger=="function"?n=>Number.isInteger(n):n=>typeof n=="number"&&Number.isFinite(n)&&Math.floor(n)===n;function a(n,o=" | "){return n.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}t.joinValues=a,t.jsonStringifyReplacer=(n,o)=>typeof o=="bigint"?o.toString():o})(T||(T={}));var qt;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(qt||(qt={}));var p=T.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),q=t=>{switch(typeof t){case"undefined":return p.undefined;case"string":return p.string;case"number":return Number.isNaN(t)?p.nan:p.number;case"boolean":return p.boolean;case"function":return p.function;case"bigint":return p.bigint;case"symbol":return p.symbol;case"object":return Array.isArray(t)?p.array:t===null?p.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?p.promise:typeof Map<"u"&&t instanceof Map?p.map:typeof Set<"u"&&t instanceof Set?p.set:typeof Date<"u"&&t instanceof Date?p.date:p.object;default:return p.unknown}};var c=T.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),oo=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),L=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=a=>{this.issues=[...this.issues,a]},this.addIssues=(a=[])=>{this.issues=[...this.issues,...a]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(o){return o.message},a={_errors:[]},n=o=>{for(let s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(n);else if(s.code==="invalid_return_type")n(s.returnTypeError);else if(s.code==="invalid_arguments")n(s.argumentsError);else if(s.path.length===0)a._errors.push(r(s));else{let i=a,f=0;for(;f<s.path.length;){let u=s.path[f];f===s.path.length-1?(i[u]=i[u]||{_errors:[]},i[u]._errors.push(r(s))):i[u]=i[u]||{_errors:[]},i=i[u],f++}}};return n(this),a}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,T.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},a=[];for(let n of this.issues)if(n.path.length>0){let o=n.path[0];r[o]=r[o]||[],r[o].push(e(n))}else a.push(e(n));return{formErrors:a,fieldErrors:r}}get formErrors(){return this.flatten()}};L.create=t=>new L(t);var so=(t,e)=>{let r;switch(t.code){case c.invalid_type:t.received===p.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case c.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,T.jsonStringifyReplacer)}`;break;case c.unrecognized_keys:r=`Unrecognized key(s) in object: ${T.joinValues(t.keys,", ")}`;break;case c.invalid_union:r="Invalid input";break;case c.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${T.joinValues(t.options)}`;break;case c.invalid_enum_value:r=`Invalid enum value. Expected ${T.joinValues(t.options)}, received '${t.received}'`;break;case c.invalid_arguments:r="Invalid function arguments";break;case c.invalid_return_type:r="Invalid function return type";break;case c.invalid_date:r="Invalid date";break;case c.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:T.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case c.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case c.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case c.custom:r="Invalid input";break;case c.invalid_intersection_types:r="Intersection results could not be merged";break;case c.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case c.not_finite:r="Number must be finite";break;default:r=e.defaultError,T.assertNever(t)}return{message:r}},Q=so;var lr=Q;function io(t){lr=t}function Ge(){return lr}var dt=t=>{let{data:e,path:r,errorMaps:a,issueData:n}=t,o=[...r,...n.path||[]],s={...n,path:o};if(n.message!==void 0)return{...n,path:o,message:n.message};let i="",f=a.filter(u=>!!u).slice().reverse();for(let u of f)i=u(s,{data:e,defaultError:i}).message;return{...n,path:o,message:i}},fo=[];function l(t,e){let r=Ge(),a=dt({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Q?void 0:Q].filter(n=>!!n)});t.common.issues.push(a)}var j=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let a=[];for(let n of r){if(n.status==="aborted")return x;n.status==="dirty"&&e.dirty(),a.push(n.value)}return{status:e.value,value:a}}static async mergeObjectAsync(e,r){let a=[];for(let n of r){let o=await n.key,s=await n.value;a.push({key:o,value:s})}return t.mergeObjectSync(e,a)}static mergeObjectSync(e,r){let a={};for(let n of r){let{key:o,value:s}=n;if(o.status==="aborted"||s.status==="aborted")return x;o.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof s.value<"u"||n.alwaysSet)&&(a[o.value]=s.value)}return{status:e.value,value:a}}},x=Object.freeze({status:"aborted"}),xe=t=>({status:"dirty",value:t}),M=t=>({status:"valid",value:t}),bt=t=>t.status==="aborted",wt=t=>t.status==="dirty",se=t=>t.status==="valid",Ue=t=>typeof Promise<"u"&&t instanceof Promise;var h;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(h||(h={}));var B=class{constructor(e,r,a,n){this._cachedPath=[],this.parent=e,this.data=r,this._path=a,this._key=n}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},pr=(t,e)=>{if(se(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new L(t.common.issues);return this._error=r,this._error}}};function b(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:a,description:n}=t;if(e&&(r||a))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:n}:{errorMap:(s,i)=>{let{message:f}=t;return s.code==="invalid_enum_value"?{message:f??i.defaultError}:typeof i.data>"u"?{message:f??a??i.defaultError}:s.code!=="invalid_type"?{message:i.defaultError}:{message:f??r??i.defaultError}},description:n}}var w=class{get description(){return this._def.description}_getType(e){return q(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:q(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new j,ctx:{common:e.parent.common,data:e.data,parsedType:q(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Ue(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let a=this.safeParse(e,r);if(a.success)return a.data;throw a.error}safeParse(e,r){let a={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:q(e)},n=this._parseSync({data:e,path:a.path,parent:a});return pr(a,n)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:q(e)};if(!this["~standard"].async)try{let a=this._parseSync({data:e,path:[],parent:r});return se(a)?{value:a.value}:{issues:r.common.issues}}catch(a){a?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(a=>se(a)?{value:a.value}:{issues:r.common.issues})}async parseAsync(e,r){let a=await this.safeParseAsync(e,r);if(a.success)return a.data;throw a.error}async safeParseAsync(e,r){let a={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:q(e)},n=this._parse({data:e,path:a.path,parent:a}),o=await(Ue(n)?n:Promise.resolve(n));return pr(a,o)}refine(e,r){let a=n=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(n):r;return this._refinement((n,o)=>{let s=e(n),i=()=>o.addIssue({code:c.custom,...a(n)});return typeof Promise<"u"&&s instanceof Promise?s.then(f=>f?!0:(i(),!1)):s?!0:(i(),!1)})}refinement(e,r){return this._refinement((a,n)=>e(a)?!0:(n.addIssue(typeof r=="function"?r(a,n):r),!1))}_refinement(e){return new z({schema:this,typeName:v.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return U.create(this,this._def)}nullable(){return Y.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return re.create(this)}promise(){return ue.create(this,this._def)}or(e){return Se.create([this,e],this._def)}and(e){return Oe.create(this,e,this._def)}transform(e){return new z({...b(this._def),schema:this,typeName:v.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new $e({...b(this._def),innerType:this,defaultValue:r,typeName:v.ZodDefault})}brand(){return new lt({typeName:v.ZodBranded,type:this,...b(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Re({...b(this._def),innerType:this,catchValue:r,typeName:v.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return pt.create(this,e)}readonly(){return Pe.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},uo=/^c[^\s-]{8,}$/i,co=/^[0-9a-z]+$/,lo=/^[0-9A-HJKMNP-TV-Z]{26}$/i,po=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,mo=/^[a-z0-9_-]{21}$/i,ho=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,go=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,yo=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,xo="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Kt,_o=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,vo=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,bo=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,wo=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,To=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,ko=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,hr="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",So=new RegExp(`^${hr}$`);function gr(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function Oo(t){return new RegExp(`^${gr(t)}$`)}function yr(t){let e=`${hr}T${gr(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function Ao(t,e){return!!((e==="v4"||!e)&&_o.test(t)||(e==="v6"||!e)&&bo.test(t))}function Io(t,e){if(!ho.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let a=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),n=JSON.parse(atob(a));return!(typeof n!="object"||n===null||"typ"in n&&n?.typ!=="JWT"||!n.alg||e&&n.alg!==e)}catch{return!1}}function Co(t,e){return!!((e==="v4"||!e)&&vo.test(t)||(e==="v6"||!e)&&wo.test(t))}var ie=class t extends w{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==p.string){let o=this._getOrReturnCtx(e);return l(o,{code:c.invalid_type,expected:p.string,received:o.parsedType}),x}let a=new j,n;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(n=this._getOrReturnCtx(e,n),l(n,{code:c.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),a.dirty());else if(o.kind==="max")e.data.length>o.value&&(n=this._getOrReturnCtx(e,n),l(n,{code:c.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),a.dirty());else if(o.kind==="length"){let s=e.data.length>o.value,i=e.data.length<o.value;(s||i)&&(n=this._getOrReturnCtx(e,n),s?l(n,{code:c.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):i&&l(n,{code:c.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),a.dirty())}else if(o.kind==="email")yo.test(e.data)||(n=this._getOrReturnCtx(e,n),l(n,{validation:"email",code:c.invalid_string,message:o.message}),a.dirty());else if(o.kind==="emoji")Kt||(Kt=new RegExp(xo,"u")),Kt.test(e.data)||(n=this._getOrReturnCtx(e,n),l(n,{validation:"emoji",code:c.invalid_string,message:o.message}),a.dirty());else if(o.kind==="uuid")po.test(e.data)||(n=this._getOrReturnCtx(e,n),l(n,{validation:"uuid",code:c.invalid_string,message:o.message}),a.dirty());else if(o.kind==="nanoid")mo.test(e.data)||(n=this._getOrReturnCtx(e,n),l(n,{validation:"nanoid",code:c.invalid_string,message:o.message}),a.dirty());else if(o.kind==="cuid")uo.test(e.data)||(n=this._getOrReturnCtx(e,n),l(n,{validation:"cuid",code:c.invalid_string,message:o.message}),a.dirty());else if(o.kind==="cuid2")co.test(e.data)||(n=this._getOrReturnCtx(e,n),l(n,{validation:"cuid2",code:c.invalid_string,message:o.message}),a.dirty());else if(o.kind==="ulid")lo.test(e.data)||(n=this._getOrReturnCtx(e,n),l(n,{validation:"ulid",code:c.invalid_string,message:o.message}),a.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),l(n,{validation:"url",code:c.invalid_string,message:o.message}),a.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),l(n,{validation:"regex",code:c.invalid_string,message:o.message}),a.dirty())):o.kind==="trim"?e.data=e.data.trim():o.kind==="includes"?e.data.includes(o.value,o.position)||(n=this._getOrReturnCtx(e,n),l(n,{code:c.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),a.dirty()):o.kind==="toLowerCase"?e.data=e.data.toLowerCase():o.kind==="toUpperCase"?e.data=e.data.toUpperCase():o.kind==="startsWith"?e.data.startsWith(o.value)||(n=this._getOrReturnCtx(e,n),l(n,{code:c.invalid_string,validation:{startsWith:o.value},message:o.message}),a.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(n=this._getOrReturnCtx(e,n),l(n,{code:c.invalid_string,validation:{endsWith:o.value},message:o.message}),a.dirty()):o.kind==="datetime"?yr(o).test(e.data)||(n=this._getOrReturnCtx(e,n),l(n,{code:c.invalid_string,validation:"datetime",message:o.message}),a.dirty()):o.kind==="date"?So.test(e.data)||(n=this._getOrReturnCtx(e,n),l(n,{code:c.invalid_string,validation:"date",message:o.message}),a.dirty()):o.kind==="time"?Oo(o).test(e.data)||(n=this._getOrReturnCtx(e,n),l(n,{code:c.invalid_string,validation:"time",message:o.message}),a.dirty()):o.kind==="duration"?go.test(e.data)||(n=this._getOrReturnCtx(e,n),l(n,{validation:"duration",code:c.invalid_string,message:o.message}),a.dirty()):o.kind==="ip"?Ao(e.data,o.version)||(n=this._getOrReturnCtx(e,n),l(n,{validation:"ip",code:c.invalid_string,message:o.message}),a.dirty()):o.kind==="jwt"?Io(e.data,o.alg)||(n=this._getOrReturnCtx(e,n),l(n,{validation:"jwt",code:c.invalid_string,message:o.message}),a.dirty()):o.kind==="cidr"?Co(e.data,o.version)||(n=this._getOrReturnCtx(e,n),l(n,{validation:"cidr",code:c.invalid_string,message:o.message}),a.dirty()):o.kind==="base64"?To.test(e.data)||(n=this._getOrReturnCtx(e,n),l(n,{validation:"base64",code:c.invalid_string,message:o.message}),a.dirty()):o.kind==="base64url"?ko.test(e.data)||(n=this._getOrReturnCtx(e,n),l(n,{validation:"base64url",code:c.invalid_string,message:o.message}),a.dirty()):T.assertNever(o);return{status:a.value,value:e.data}}_regex(e,r,a){return this.refinement(n=>e.test(n),{validation:r,code:c.invalid_string,...h.errToObj(a)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...h.errToObj(e)})}url(e){return this._addCheck({kind:"url",...h.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...h.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...h.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...h.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...h.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...h.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...h.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...h.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...h.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...h.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...h.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...h.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...h.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...h.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...h.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...h.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...h.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...h.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...h.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...h.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...h.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...h.errToObj(r)})}nonempty(e){return this.min(1,h.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};ie.create=t=>new ie({checks:[],typeName:v.ZodString,coerce:t?.coerce??!1,...b(t)});function Eo(t,e){let r=(t.toString().split(".")[1]||"").length,a=(e.toString().split(".")[1]||"").length,n=r>a?r:a,o=Number.parseInt(t.toFixed(n).replace(".","")),s=Number.parseInt(e.toFixed(n).replace(".",""));return o%s/10**n}var _e=class t extends w{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==p.number){let o=this._getOrReturnCtx(e);return l(o,{code:c.invalid_type,expected:p.number,received:o.parsedType}),x}let a,n=new j;for(let o of this._def.checks)o.kind==="int"?T.isInteger(e.data)||(a=this._getOrReturnCtx(e,a),l(a,{code:c.invalid_type,expected:"integer",received:"float",message:o.message}),n.dirty()):o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(a=this._getOrReturnCtx(e,a),l(a,{code:c.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),n.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(a=this._getOrReturnCtx(e,a),l(a,{code:c.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),n.dirty()):o.kind==="multipleOf"?Eo(e.data,o.value)!==0&&(a=this._getOrReturnCtx(e,a),l(a,{code:c.not_multiple_of,multipleOf:o.value,message:o.message}),n.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(a=this._getOrReturnCtx(e,a),l(a,{code:c.not_finite,message:o.message}),n.dirty()):T.assertNever(o);return{status:n.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,h.toString(r))}gt(e,r){return this.setLimit("min",e,!1,h.toString(r))}lte(e,r){return this.setLimit("max",e,!0,h.toString(r))}lt(e,r){return this.setLimit("max",e,!1,h.toString(r))}setLimit(e,r,a,n){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:a,message:h.toString(n)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:h.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:h.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:h.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:h.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:h.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&T.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let a of this._def.checks){if(a.kind==="finite"||a.kind==="int"||a.kind==="multipleOf")return!0;a.kind==="min"?(r===null||a.value>r)&&(r=a.value):a.kind==="max"&&(e===null||a.value<e)&&(e=a.value)}return Number.isFinite(r)&&Number.isFinite(e)}};_e.create=t=>new _e({checks:[],typeName:v.ZodNumber,coerce:t?.coerce||!1,...b(t)});var ve=class t extends w{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==p.bigint)return this._getInvalidInput(e);let a,n=new j;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.data<o.value:e.data<=o.value)&&(a=this._getOrReturnCtx(e,a),l(a,{code:c.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),n.dirty()):o.kind==="max"?(o.inclusive?e.data>o.value:e.data>=o.value)&&(a=this._getOrReturnCtx(e,a),l(a,{code:c.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),n.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(a=this._getOrReturnCtx(e,a),l(a,{code:c.not_multiple_of,multipleOf:o.value,message:o.message}),n.dirty()):T.assertNever(o);return{status:n.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return l(r,{code:c.invalid_type,expected:p.bigint,received:r.parsedType}),x}gte(e,r){return this.setLimit("min",e,!0,h.toString(r))}gt(e,r){return this.setLimit("min",e,!1,h.toString(r))}lte(e,r){return this.setLimit("max",e,!0,h.toString(r))}lt(e,r){return this.setLimit("max",e,!1,h.toString(r))}setLimit(e,r,a,n){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:a,message:h.toString(n)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:h.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};ve.create=t=>new ve({checks:[],typeName:v.ZodBigInt,coerce:t?.coerce??!1,...b(t)});var be=class extends w{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==p.boolean){let a=this._getOrReturnCtx(e);return l(a,{code:c.invalid_type,expected:p.boolean,received:a.parsedType}),x}return M(e.data)}};be.create=t=>new be({typeName:v.ZodBoolean,coerce:t?.coerce||!1,...b(t)});var we=class t extends w{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==p.date){let o=this._getOrReturnCtx(e);return l(o,{code:c.invalid_type,expected:p.date,received:o.parsedType}),x}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return l(o,{code:c.invalid_date}),x}let a=new j,n;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(n=this._getOrReturnCtx(e,n),l(n,{code:c.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),a.dirty()):o.kind==="max"?e.data.getTime()>o.value&&(n=this._getOrReturnCtx(e,n),l(n,{code:c.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),a.dirty()):T.assertNever(o);return{status:a.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:h.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:h.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};we.create=t=>new we({checks:[],coerce:t?.coerce||!1,typeName:v.ZodDate,...b(t)});var ze=class extends w{_parse(e){if(this._getType(e)!==p.symbol){let a=this._getOrReturnCtx(e);return l(a,{code:c.invalid_type,expected:p.symbol,received:a.parsedType}),x}return M(e.data)}};ze.create=t=>new ze({typeName:v.ZodSymbol,...b(t)});var Te=class extends w{_parse(e){if(this._getType(e)!==p.undefined){let a=this._getOrReturnCtx(e);return l(a,{code:c.invalid_type,expected:p.undefined,received:a.parsedType}),x}return M(e.data)}};Te.create=t=>new Te({typeName:v.ZodUndefined,...b(t)});var ke=class extends w{_parse(e){if(this._getType(e)!==p.null){let a=this._getOrReturnCtx(e);return l(a,{code:c.invalid_type,expected:p.null,received:a.parsedType}),x}return M(e.data)}};ke.create=t=>new ke({typeName:v.ZodNull,...b(t)});var fe=class extends w{constructor(){super(...arguments),this._any=!0}_parse(e){return M(e.data)}};fe.create=t=>new fe({typeName:v.ZodAny,...b(t)});var te=class extends w{constructor(){super(...arguments),this._unknown=!0}_parse(e){return M(e.data)}};te.create=t=>new te({typeName:v.ZodUnknown,...b(t)});var Z=class extends w{_parse(e){let r=this._getOrReturnCtx(e);return l(r,{code:c.invalid_type,expected:p.never,received:r.parsedType}),x}};Z.create=t=>new Z({typeName:v.ZodNever,...b(t)});var Ze=class extends w{_parse(e){if(this._getType(e)!==p.undefined){let a=this._getOrReturnCtx(e);return l(a,{code:c.invalid_type,expected:p.void,received:a.parsedType}),x}return M(e.data)}};Ze.create=t=>new Ze({typeName:v.ZodVoid,...b(t)});var re=class t extends w{_parse(e){let{ctx:r,status:a}=this._processInputParams(e),n=this._def;if(r.parsedType!==p.array)return l(r,{code:c.invalid_type,expected:p.array,received:r.parsedType}),x;if(n.exactLength!==null){let s=r.data.length>n.exactLength.value,i=r.data.length<n.exactLength.value;(s||i)&&(l(r,{code:s?c.too_big:c.too_small,minimum:i?n.exactLength.value:void 0,maximum:s?n.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:n.exactLength.message}),a.dirty())}if(n.minLength!==null&&r.data.length<n.minLength.value&&(l(r,{code:c.too_small,minimum:n.minLength.value,type:"array",inclusive:!0,exact:!1,message:n.minLength.message}),a.dirty()),n.maxLength!==null&&r.data.length>n.maxLength.value&&(l(r,{code:c.too_big,maximum:n.maxLength.value,type:"array",inclusive:!0,exact:!1,message:n.maxLength.message}),a.dirty()),r.common.async)return Promise.all([...r.data].map((s,i)=>n.type._parseAsync(new B(r,s,r.path,i)))).then(s=>j.mergeArray(a,s));let o=[...r.data].map((s,i)=>n.type._parseSync(new B(r,s,r.path,i)));return j.mergeArray(a,o)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:h.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:h.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:h.toString(r)}})}nonempty(e){return this.min(1,e)}};re.create=(t,e)=>new re({type:t,minLength:null,maxLength:null,exactLength:null,typeName:v.ZodArray,...b(e)});function Be(t){if(t instanceof F){let e={};for(let r in t.shape){let a=t.shape[r];e[r]=U.create(Be(a))}return new F({...t._def,shape:()=>e})}else return t instanceof re?new re({...t._def,type:Be(t.element)}):t instanceof U?U.create(Be(t.unwrap())):t instanceof Y?Y.create(Be(t.unwrap())):t instanceof K?K.create(t.items.map(e=>Be(e))):t}var F=class t extends w{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=T.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==p.object){let u=this._getOrReturnCtx(e);return l(u,{code:c.invalid_type,expected:p.object,received:u.parsedType}),x}let{status:a,ctx:n}=this._processInputParams(e),{shape:o,keys:s}=this._getCached(),i=[];if(!(this._def.catchall instanceof Z&&this._def.unknownKeys==="strip"))for(let u in n.data)s.includes(u)||i.push(u);let f=[];for(let u of s){let d=o[u],m=n.data[u];f.push({key:{status:"valid",value:u},value:d._parse(new B(n,m,n.path,u)),alwaysSet:u in n.data})}if(this._def.catchall instanceof Z){let u=this._def.unknownKeys;if(u==="passthrough")for(let d of i)f.push({key:{status:"valid",value:d},value:{status:"valid",value:n.data[d]}});else if(u==="strict")i.length>0&&(l(n,{code:c.unrecognized_keys,keys:i}),a.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let d of i){let m=n.data[d];f.push({key:{status:"valid",value:d},value:u._parse(new B(n,m,n.path,d)),alwaysSet:d in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let u=[];for(let d of f){let m=await d.key,g=await d.value;u.push({key:m,value:g,alwaysSet:d.alwaysSet})}return u}).then(u=>j.mergeObjectSync(a,u)):j.mergeObjectSync(a,f)}get shape(){return this._def.shape()}strict(e){return h.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,a)=>{let n=this._def.errorMap?.(r,a).message??a.defaultError;return r.code==="unrecognized_keys"?{message:h.errToObj(e).message??n}:{message:n}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:v.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let a of T.objectKeys(e))e[a]&&this.shape[a]&&(r[a]=this.shape[a]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let a of T.objectKeys(this.shape))e[a]||(r[a]=this.shape[a]);return new t({...this._def,shape:()=>r})}deepPartial(){return Be(this)}partial(e){let r={};for(let a of T.objectKeys(this.shape)){let n=this.shape[a];e&&!e[a]?r[a]=n:r[a]=n.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let a of T.objectKeys(this.shape))if(e&&!e[a])r[a]=this.shape[a];else{let o=this.shape[a];for(;o instanceof U;)o=o._def.innerType;r[a]=o}return new t({...this._def,shape:()=>r})}keyof(){return xr(T.objectKeys(this.shape))}};F.create=(t,e)=>new F({shape:()=>t,unknownKeys:"strip",catchall:Z.create(),typeName:v.ZodObject,...b(e)});F.strictCreate=(t,e)=>new F({shape:()=>t,unknownKeys:"strict",catchall:Z.create(),typeName:v.ZodObject,...b(e)});F.lazycreate=(t,e)=>new F({shape:t,unknownKeys:"strip",catchall:Z.create(),typeName:v.ZodObject,...b(e)});var Se=class extends w{_parse(e){let{ctx:r}=this._processInputParams(e),a=this._def.options;function n(o){for(let i of o)if(i.result.status==="valid")return i.result;for(let i of o)if(i.result.status==="dirty")return r.common.issues.push(...i.ctx.common.issues),i.result;let s=o.map(i=>new L(i.ctx.common.issues));return l(r,{code:c.invalid_union,unionErrors:s}),x}if(r.common.async)return Promise.all(a.map(async o=>{let s={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:s}),ctx:s}})).then(n);{let o,s=[];for(let f of a){let u={...r,common:{...r.common,issues:[]},parent:null},d=f._parseSync({data:r.data,path:r.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!o&&(o={result:d,ctx:u}),u.common.issues.length&&s.push(u.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let i=s.map(f=>new L(f));return l(r,{code:c.invalid_union,unionErrors:i}),x}}get options(){return this._def.options}};Se.create=(t,e)=>new Se({options:t,typeName:v.ZodUnion,...b(e)});var ee=t=>t instanceof Ae?ee(t.schema):t instanceof z?ee(t.innerType()):t instanceof Ie?[t.value]:t instanceof Ce?t.options:t instanceof Ee?T.objectValues(t.enum):t instanceof $e?ee(t._def.innerType):t instanceof Te?[void 0]:t instanceof ke?[null]:t instanceof U?[void 0,...ee(t.unwrap())]:t instanceof Y?[null,...ee(t.unwrap())]:t instanceof lt||t instanceof Pe?ee(t.unwrap()):t instanceof Re?ee(t._def.innerType):[],Tt=class t extends w{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==p.object)return l(r,{code:c.invalid_type,expected:p.object,received:r.parsedType}),x;let a=this.discriminator,n=r.data[a],o=this.optionsMap.get(n);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(l(r,{code:c.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[a]}),x)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,a){let n=new Map;for(let o of r){let s=ee(o.shape[e]);if(!s.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let i of s){if(n.has(i))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);n.set(i,o)}}return new t({typeName:v.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:n,...b(a)})}};function Yt(t,e){let r=q(t),a=q(e);if(t===e)return{valid:!0,data:t};if(r===p.object&&a===p.object){let n=T.objectKeys(e),o=T.objectKeys(t).filter(i=>n.indexOf(i)!==-1),s={...t,...e};for(let i of o){let f=Yt(t[i],e[i]);if(!f.valid)return{valid:!1};s[i]=f.data}return{valid:!0,data:s}}else if(r===p.array&&a===p.array){if(t.length!==e.length)return{valid:!1};let n=[];for(let o=0;o<t.length;o++){let s=t[o],i=e[o],f=Yt(s,i);if(!f.valid)return{valid:!1};n.push(f.data)}return{valid:!0,data:n}}else return r===p.date&&a===p.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Oe=class extends w{_parse(e){let{status:r,ctx:a}=this._processInputParams(e),n=(o,s)=>{if(bt(o)||bt(s))return x;let i=Yt(o.value,s.value);return i.valid?((wt(o)||wt(s))&&r.dirty(),{status:r.value,value:i.data}):(l(a,{code:c.invalid_intersection_types}),x)};return a.common.async?Promise.all([this._def.left._parseAsync({data:a.data,path:a.path,parent:a}),this._def.right._parseAsync({data:a.data,path:a.path,parent:a})]).then(([o,s])=>n(o,s)):n(this._def.left._parseSync({data:a.data,path:a.path,parent:a}),this._def.right._parseSync({data:a.data,path:a.path,parent:a}))}};Oe.create=(t,e,r)=>new Oe({left:t,right:e,typeName:v.ZodIntersection,...b(r)});var K=class t extends w{_parse(e){let{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==p.array)return l(a,{code:c.invalid_type,expected:p.array,received:a.parsedType}),x;if(a.data.length<this._def.items.length)return l(a,{code:c.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),x;!this._def.rest&&a.data.length>this._def.items.length&&(l(a,{code:c.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...a.data].map((s,i)=>{let f=this._def.items[i]||this._def.rest;return f?f._parse(new B(a,s,a.path,i)):null}).filter(s=>!!s);return a.common.async?Promise.all(o).then(s=>j.mergeArray(r,s)):j.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};K.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new K({items:t,typeName:v.ZodTuple,rest:null,...b(e)})};var kt=class t extends w{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==p.object)return l(a,{code:c.invalid_type,expected:p.object,received:a.parsedType}),x;let n=[],o=this._def.keyType,s=this._def.valueType;for(let i in a.data)n.push({key:o._parse(new B(a,i,a.path,i)),value:s._parse(new B(a,a.data[i],a.path,i)),alwaysSet:i in a.data});return a.common.async?j.mergeObjectAsync(r,n):j.mergeObjectSync(r,n)}get element(){return this._def.valueType}static create(e,r,a){return r instanceof w?new t({keyType:e,valueType:r,typeName:v.ZodRecord,...b(a)}):new t({keyType:ie.create(),valueType:e,typeName:v.ZodRecord,...b(r)})}},Ve=class extends w{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==p.map)return l(a,{code:c.invalid_type,expected:p.map,received:a.parsedType}),x;let n=this._def.keyType,o=this._def.valueType,s=[...a.data.entries()].map(([i,f],u)=>({key:n._parse(new B(a,i,a.path,[u,"key"])),value:o._parse(new B(a,f,a.path,[u,"value"]))}));if(a.common.async){let i=new Map;return Promise.resolve().then(async()=>{for(let f of s){let u=await f.key,d=await f.value;if(u.status==="aborted"||d.status==="aborted")return x;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),i.set(u.value,d.value)}return{status:r.value,value:i}})}else{let i=new Map;for(let f of s){let u=f.key,d=f.value;if(u.status==="aborted"||d.status==="aborted")return x;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),i.set(u.value,d.value)}return{status:r.value,value:i}}}};Ve.create=(t,e,r)=>new Ve({valueType:e,keyType:t,typeName:v.ZodMap,...b(r)});var We=class t extends w{_parse(e){let{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==p.set)return l(a,{code:c.invalid_type,expected:p.set,received:a.parsedType}),x;let n=this._def;n.minSize!==null&&a.data.size<n.minSize.value&&(l(a,{code:c.too_small,minimum:n.minSize.value,type:"set",inclusive:!0,exact:!1,message:n.minSize.message}),r.dirty()),n.maxSize!==null&&a.data.size>n.maxSize.value&&(l(a,{code:c.too_big,maximum:n.maxSize.value,type:"set",inclusive:!0,exact:!1,message:n.maxSize.message}),r.dirty());let o=this._def.valueType;function s(f){let u=new Set;for(let d of f){if(d.status==="aborted")return x;d.status==="dirty"&&r.dirty(),u.add(d.value)}return{status:r.value,value:u}}let i=[...a.data.values()].map((f,u)=>o._parse(new B(a,f,a.path,u)));return a.common.async?Promise.all(i).then(f=>s(f)):s(i)}min(e,r){return new t({...this._def,minSize:{value:e,message:h.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:h.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};We.create=(t,e)=>new We({valueType:t,minSize:null,maxSize:null,typeName:v.ZodSet,...b(e)});var St=class t extends w{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==p.function)return l(r,{code:c.invalid_type,expected:p.function,received:r.parsedType}),x;function a(i,f){return dt({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Ge(),Q].filter(u=>!!u),issueData:{code:c.invalid_arguments,argumentsError:f}})}function n(i,f){return dt({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Ge(),Q].filter(u=>!!u),issueData:{code:c.invalid_return_type,returnTypeError:f}})}let o={errorMap:r.common.contextualErrorMap},s=r.data;if(this._def.returns instanceof ue){let i=this;return M(async function(...f){let u=new L([]),d=await i._def.args.parseAsync(f,o).catch(_=>{throw u.addIssue(a(f,_)),u}),m=await Reflect.apply(s,this,d);return await i._def.returns._def.type.parseAsync(m,o).catch(_=>{throw u.addIssue(n(m,_)),u})})}else{let i=this;return M(function(...f){let u=i._def.args.safeParse(f,o);if(!u.success)throw new L([a(f,u.error)]);let d=Reflect.apply(s,this,u.data),m=i._def.returns.safeParse(d,o);if(!m.success)throw new L([n(d,m.error)]);return m.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:K.create(e).rest(te.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,a){return new t({args:e||K.create([]).rest(te.create()),returns:r||te.create(),typeName:v.ZodFunction,...b(a)})}},Ae=class extends w{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Ae.create=(t,e)=>new Ae({getter:t,typeName:v.ZodLazy,...b(e)});var Ie=class extends w{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return l(r,{received:r.data,code:c.invalid_literal,expected:this._def.value}),x}return{status:"valid",value:e.data}}get value(){return this._def.value}};Ie.create=(t,e)=>new Ie({value:t,typeName:v.ZodLiteral,...b(e)});function xr(t,e){return new Ce({values:t,typeName:v.ZodEnum,...b(e)})}var Ce=class t extends w{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),a=this._def.values;return l(r,{expected:T.joinValues(a),received:r.parsedType,code:c.invalid_type}),x}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),a=this._def.values;return l(r,{received:r.data,code:c.invalid_enum_value,options:a}),x}return M(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(a=>!e.includes(a)),{...this._def,...r})}};Ce.create=xr;var Ee=class extends w{_parse(e){let r=T.getValidEnumValues(this._def.values),a=this._getOrReturnCtx(e);if(a.parsedType!==p.string&&a.parsedType!==p.number){let n=T.objectValues(r);return l(a,{expected:T.joinValues(n),received:a.parsedType,code:c.invalid_type}),x}if(this._cache||(this._cache=new Set(T.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let n=T.objectValues(r);return l(a,{received:a.data,code:c.invalid_enum_value,options:n}),x}return M(e.data)}get enum(){return this._def.values}};Ee.create=(t,e)=>new Ee({values:t,typeName:v.ZodNativeEnum,...b(e)});var ue=class extends w{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==p.promise&&r.common.async===!1)return l(r,{code:c.invalid_type,expected:p.promise,received:r.parsedType}),x;let a=r.parsedType===p.promise?r.data:Promise.resolve(r.data);return M(a.then(n=>this._def.type.parseAsync(n,{path:r.path,errorMap:r.common.contextualErrorMap})))}};ue.create=(t,e)=>new ue({type:t,typeName:v.ZodPromise,...b(e)});var z=class extends w{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===v.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:a}=this._processInputParams(e),n=this._def.effect||null,o={addIssue:s=>{l(a,s),s.fatal?r.abort():r.dirty()},get path(){return a.path}};if(o.addIssue=o.addIssue.bind(o),n.type==="preprocess"){let s=n.transform(a.data,o);if(a.common.async)return Promise.resolve(s).then(async i=>{if(r.value==="aborted")return x;let f=await this._def.schema._parseAsync({data:i,path:a.path,parent:a});return f.status==="aborted"?x:f.status==="dirty"?xe(f.value):r.value==="dirty"?xe(f.value):f});{if(r.value==="aborted")return x;let i=this._def.schema._parseSync({data:s,path:a.path,parent:a});return i.status==="aborted"?x:i.status==="dirty"?xe(i.value):r.value==="dirty"?xe(i.value):i}}if(n.type==="refinement"){let s=i=>{let f=n.refinement(i,o);if(a.common.async)return Promise.resolve(f);if(f instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(a.common.async===!1){let i=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});return i.status==="aborted"?x:(i.status==="dirty"&&r.dirty(),s(i.value),{status:r.value,value:i.value})}else return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then(i=>i.status==="aborted"?x:(i.status==="dirty"&&r.dirty(),s(i.value).then(()=>({status:r.value,value:i.value}))))}if(n.type==="transform")if(a.common.async===!1){let s=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});if(!se(s))return x;let i=n.transform(s.value,o);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:i}}else return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then(s=>se(s)?Promise.resolve(n.transform(s.value,o)).then(i=>({status:r.value,value:i})):x);T.assertNever(n)}};z.create=(t,e,r)=>new z({schema:t,typeName:v.ZodEffects,effect:e,...b(r)});z.createWithPreprocess=(t,e,r)=>new z({schema:e,effect:{type:"preprocess",transform:t},typeName:v.ZodEffects,...b(r)});var U=class extends w{_parse(e){return this._getType(e)===p.undefined?M(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};U.create=(t,e)=>new U({innerType:t,typeName:v.ZodOptional,...b(e)});var Y=class extends w{_parse(e){return this._getType(e)===p.null?M(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Y.create=(t,e)=>new Y({innerType:t,typeName:v.ZodNullable,...b(e)});var $e=class extends w{_parse(e){let{ctx:r}=this._processInputParams(e),a=r.data;return r.parsedType===p.undefined&&(a=this._def.defaultValue()),this._def.innerType._parse({data:a,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};$e.create=(t,e)=>new $e({innerType:t,typeName:v.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...b(e)});var Re=class extends w{_parse(e){let{ctx:r}=this._processInputParams(e),a={...r,common:{...r.common,issues:[]}},n=this._def.innerType._parse({data:a.data,path:a.path,parent:{...a}});return Ue(n)?n.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new L(a.common.issues)},input:a.data})})):{status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new L(a.common.issues)},input:a.data})}}removeCatch(){return this._def.innerType}};Re.create=(t,e)=>new Re({innerType:t,typeName:v.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...b(e)});var He=class extends w{_parse(e){if(this._getType(e)!==p.nan){let a=this._getOrReturnCtx(e);return l(a,{code:c.invalid_type,expected:p.nan,received:a.parsedType}),x}return{status:"valid",value:e.data}}};He.create=t=>new He({typeName:v.ZodNaN,...b(t)});var $o=Symbol("zod_brand"),lt=class extends w{_parse(e){let{ctx:r}=this._processInputParams(e),a=r.data;return this._def.type._parse({data:a,path:r.path,parent:r})}unwrap(){return this._def.type}},pt=class t extends w{_parse(e){let{status:r,ctx:a}=this._processInputParams(e);if(a.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:a.data,path:a.path,parent:a});return o.status==="aborted"?x:o.status==="dirty"?(r.dirty(),xe(o.value)):this._def.out._parseAsync({data:o.value,path:a.path,parent:a})})();{let n=this._def.in._parseSync({data:a.data,path:a.path,parent:a});return n.status==="aborted"?x:n.status==="dirty"?(r.dirty(),{status:"dirty",value:n.value}):this._def.out._parseSync({data:n.value,path:a.path,parent:a})}}static create(e,r){return new t({in:e,out:r,typeName:v.ZodPipeline})}},Pe=class extends w{_parse(e){let r=this._def.innerType._parse(e),a=n=>(se(n)&&(n.value=Object.freeze(n.value)),n);return Ue(r)?r.then(n=>a(n)):a(r)}unwrap(){return this._def.innerType}};Pe.create=(t,e)=>new Pe({innerType:t,typeName:v.ZodReadonly,...b(e)});function mr(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function _r(t,e={},r){return t?fe.create().superRefine((a,n)=>{let o=t(a);if(o instanceof Promise)return o.then(s=>{if(!s){let i=mr(e,a),f=i.fatal??r??!0;n.addIssue({code:"custom",...i,fatal:f})}});if(!o){let s=mr(e,a),i=s.fatal??r??!0;n.addIssue({code:"custom",...s,fatal:i})}}):fe.create()}var Ro={object:F.lazycreate},v;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(v||(v={}));var Po=(t,e={message:`Input not instance of ${t.name}`})=>_r(r=>r instanceof t,e),vr=ie.create,br=_e.create,No=He.create,jo=ve.create,wr=be.create,Mo=we.create,Do=ze.create,Lo=Te.create,Fo=ke.create,Go=fe.create,Uo=te.create,Bo=Z.create,zo=Ze.create,Zo=re.create,Vo=F.create,Wo=F.strictCreate,Ho=Se.create,qo=Tt.create,Ko=Oe.create,Yo=K.create,Jo=kt.create,Xo=Ve.create,Qo=We.create,es=St.create,ts=Ae.create,rs=Ie.create,as=Ce.create,ns=Ee.create,os=ue.create,ss=z.create,is=U.create,fs=Y.create,us=z.createWithPreprocess,cs=pt.create,ds=()=>vr().optional(),ls=()=>br().optional(),ps=()=>wr().optional(),ms={string:(t=>ie.create({...t,coerce:!0})),number:(t=>_e.create({...t,coerce:!0})),boolean:(t=>be.create({...t,coerce:!0})),bigint:(t=>ve.create({...t,coerce:!0})),date:(t=>we.create({...t,coerce:!0}))};var hs=x;var gs=typeof global=="object"&&global&&global.Object===Object&&global,Ot=gs;var ys=typeof self=="object"&&self&&self.Object===Object&&self,xs=Ot||ys||Function("return this")(),N=xs;var _s=N.Symbol,D=_s;var Tr=Object.prototype,vs=Tr.hasOwnProperty,bs=Tr.toString,mt=D?D.toStringTag:void 0;function ws(t){var e=vs.call(t,mt),r=t[mt];try{t[mt]=void 0;var a=!0}catch{}var n=bs.call(t);return a&&(e?t[mt]=r:delete t[mt]),n}var kr=ws;var Ts=Object.prototype,ks=Ts.toString;function Ss(t){return ks.call(t)}var Sr=Ss;var Os="[object Null]",As="[object Undefined]",Or=D?D.toStringTag:void 0;function Is(t){return t==null?t===void 0?As:Os:Or&&Or in Object(t)?kr(t):Sr(t)}var V=Is;function Cs(t){return t!=null&&typeof t=="object"}var W=Cs;var Es="[object Symbol]";function $s(t){return typeof t=="symbol"||W(t)&&V(t)==Es}var ae=$s;function Rs(t,e){for(var r=-1,a=t==null?0:t.length,n=Array(a);++r<a;)n[r]=e(t[r],r,t);return n}var qe=Rs;var Ps=Array.isArray,E=Ps;var Ns=1/0,Ar=D?D.prototype:void 0,Ir=Ar?Ar.toString:void 0;function Cr(t){if(typeof t=="string")return t;if(E(t))return qe(t,Cr)+"";if(ae(t))return Ir?Ir.call(t):"";var e=t+"";return e=="0"&&1/t==-Ns?"-0":e}var Er=Cr;function js(t){var e=typeof t;return t!=null&&(e=="object"||e=="function")}var ce=js;function Ms(t){return t}var de=Ms;var Ds="[object AsyncFunction]",Ls="[object Function]",Fs="[object GeneratorFunction]",Gs="[object Proxy]";function Us(t){if(!ce(t))return!1;var e=V(t);return e==Ls||e==Fs||e==Ds||e==Gs}var At=Us;var Bs=N["__core-js_shared__"],It=Bs;var $r=(function(){var t=/[^.]+$/.exec(It&&It.keys&&It.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""})();function zs(t){return!!$r&&$r in t}var Rr=zs;var Zs=Function.prototype,Vs=Zs.toString;function Ws(t){if(t!=null){try{return Vs.call(t)}catch{}try{return t+""}catch{}}return""}var ne=Ws;var Hs=/[\\^$.*+?()[\]{}|]/g,qs=/^\[object .+?Constructor\]$/,Ks=Function.prototype,Ys=Object.prototype,Js=Ks.toString,Xs=Ys.hasOwnProperty,Qs=RegExp("^"+Js.call(Xs).replace(Hs,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function ei(t){if(!ce(t)||Rr(t))return!1;var e=At(t)?Qs:qs;return e.test(ne(t))}var Pr=ei;function ti(t,e){return t?.[e]}var Nr=ti;function ri(t,e){var r=Nr(t,e);return Pr(r)?r:void 0}var G=ri;var ai=G(N,"WeakMap"),Ct=ai;function ni(t,e,r){switch(r.length){case 0:return t.call(e);case 1:return t.call(e,r[0]);case 2:return t.call(e,r[0],r[1]);case 3:return t.call(e,r[0],r[1],r[2])}return t.apply(e,r)}var jr=ni;var oi=800,si=16,ii=Date.now;function fi(t){var e=0,r=0;return function(){var a=ii(),n=si-(a-r);if(r=a,n>0){if(++e>=oi)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}var Mr=fi;function ui(t){return function(){return t}}var Dr=ui;var ci=(function(){try{var t=G(Object,"defineProperty");return t({},"",{}),t}catch{}})(),Ke=ci;var di=Ke?function(t,e){return Ke(t,"toString",{configurable:!0,enumerable:!1,value:Dr(e),writable:!0})}:de,Lr=di;var li=Mr(Lr),Fr=li;var pi=9007199254740991,mi=/^(?:0|[1-9]\d*)$/;function hi(t,e){var r=typeof t;return e=e??pi,!!e&&(r=="number"||r!="symbol"&&mi.test(t))&&t>-1&&t%1==0&&t<e}var Ye=hi;function gi(t,e,r){e=="__proto__"&&Ke?Ke(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}var Gr=gi;function yi(t,e){return t===e||t!==t&&e!==e}var Je=yi;var Ur=Math.max;function xi(t,e,r){return e=Ur(e===void 0?t.length-1:e,0),function(){for(var a=arguments,n=-1,o=Ur(a.length-e,0),s=Array(o);++n<o;)s[n]=a[e+n];n=-1;for(var i=Array(e+1);++n<e;)i[n]=a[n];return i[e]=r(s),jr(t,this,i)}}var Br=xi;function _i(t,e){return Fr(Br(t,e,de),t+"")}var zr=_i;var vi=9007199254740991;function bi(t){return typeof t=="number"&&t>-1&&t%1==0&&t<=vi}var Xe=bi;function wi(t){return t!=null&&Xe(t.length)&&!At(t)}var le=wi;function Ti(t,e,r){if(!ce(r))return!1;var a=typeof e;return(a=="number"?le(r)&&Ye(e,r.length):a=="string"&&e in r)?Je(r[e],t):!1}var Jt=Ti;var ki=Object.prototype;function Si(t){var e=t&&t.constructor,r=typeof e=="function"&&e.prototype||ki;return t===r}var Zr=Si;function Oi(t,e){for(var r=-1,a=Array(t);++r<t;)a[r]=e(r);return a}var Vr=Oi;var Ai="[object Arguments]";function Ii(t){return W(t)&&V(t)==Ai}var Xt=Ii;var Wr=Object.prototype,Ci=Wr.hasOwnProperty,Ei=Wr.propertyIsEnumerable,$i=Xt((function(){return arguments})())?Xt:function(t){return W(t)&&Ci.call(t,"callee")&&!Ei.call(t,"callee")},Qe=$i;function Ri(){return!1}var Hr=Ri;var Yr=typeof exports=="object"&&exports&&!exports.nodeType&&exports,qr=Yr&&typeof module=="object"&&module&&!module.nodeType&&module,Pi=qr&&qr.exports===Yr,Kr=Pi?N.Buffer:void 0,Ni=Kr?Kr.isBuffer:void 0,ji=Ni||Hr,ht=ji;var Mi="[object Arguments]",Di="[object Array]",Li="[object Boolean]",Fi="[object Date]",Gi="[object Error]",Ui="[object Function]",Bi="[object Map]",zi="[object Number]",Zi="[object Object]",Vi="[object RegExp]",Wi="[object Set]",Hi="[object String]",qi="[object WeakMap]",Ki="[object ArrayBuffer]",Yi="[object DataView]",Ji="[object Float32Array]",Xi="[object Float64Array]",Qi="[object Int8Array]",ef="[object Int16Array]",tf="[object Int32Array]",rf="[object Uint8Array]",af="[object Uint8ClampedArray]",nf="[object Uint16Array]",of="[object Uint32Array]",C={};C[Ji]=C[Xi]=C[Qi]=C[ef]=C[tf]=C[rf]=C[af]=C[nf]=C[of]=!0;C[Mi]=C[Di]=C[Ki]=C[Li]=C[Yi]=C[Fi]=C[Gi]=C[Ui]=C[Bi]=C[zi]=C[Zi]=C[Vi]=C[Wi]=C[Hi]=C[qi]=!1;function sf(t){return W(t)&&Xe(t.length)&&!!C[V(t)]}var Jr=sf;function ff(t){return function(e){return t(e)}}var Et=ff;var Xr=typeof exports=="object"&&exports&&!exports.nodeType&&exports,gt=Xr&&typeof module=="object"&&module&&!module.nodeType&&module,uf=gt&>.exports===Xr,Qt=uf&&Ot.process,cf=(function(){try{var t=gt&>.require&>.require("util").types;return t||Qt&&Qt.binding&&Qt.binding("util")}catch{}})(),er=cf;var Qr=er&&er.isTypedArray,df=Qr?Et(Qr):Jr,$t=df;var lf=Object.prototype,pf=lf.hasOwnProperty;function mf(t,e){var r=E(t),a=!r&&Qe(t),n=!r&&!a&&ht(t),o=!r&&!a&&!n&&$t(t),s=r||a||n||o,i=s?Vr(t.length,String):[],f=i.length;for(var u in t)(e||pf.call(t,u))&&!(s&&(u=="length"||n&&(u=="offset"||u=="parent")||o&&(u=="buffer"||u=="byteLength"||u=="byteOffset")||Ye(u,f)))&&i.push(u);return i}var ea=mf;function hf(t,e){return function(r){return t(e(r))}}var ta=hf;var gf=ta(Object.keys,Object),ra=gf;var yf=Object.prototype,xf=yf.hasOwnProperty;function _f(t){if(!Zr(t))return ra(t);var e=[];for(var r in Object(t))xf.call(t,r)&&r!="constructor"&&e.push(r);return e}var aa=_f;function vf(t){return le(t)?ea(t):aa(t)}var et=vf;var bf=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,wf=/^\w*$/;function Tf(t,e){if(E(t))return!1;var r=typeof t;return r=="number"||r=="symbol"||r=="boolean"||t==null||ae(t)?!0:wf.test(t)||!bf.test(t)||e!=null&&t in Object(e)}var tt=Tf;var kf=G(Object,"create"),oe=kf;function Sf(){this.__data__=oe?oe(null):{},this.size=0}var na=Sf;function Of(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}var oa=Of;var Af="__lodash_hash_undefined__",If=Object.prototype,Cf=If.hasOwnProperty;function Ef(t){var e=this.__data__;if(oe){var r=e[t];return r===Af?void 0:r}return Cf.call(e,t)?e[t]:void 0}var sa=Ef;var $f=Object.prototype,Rf=$f.hasOwnProperty;function Pf(t){var e=this.__data__;return oe?e[t]!==void 0:Rf.call(e,t)}var ia=Pf;var Nf="__lodash_hash_undefined__";function jf(t,e){var r=this.__data__;return this.size+=this.has(t)?0:1,r[t]=oe&&e===void 0?Nf:e,this}var fa=jf;function rt(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var a=t[e];this.set(a[0],a[1])}}rt.prototype.clear=na;rt.prototype.delete=oa;rt.prototype.get=sa;rt.prototype.has=ia;rt.prototype.set=fa;var tr=rt;function Mf(){this.__data__=[],this.size=0}var ua=Mf;function Df(t,e){for(var r=t.length;r--;)if(Je(t[r][0],e))return r;return-1}var pe=Df;var Lf=Array.prototype,Ff=Lf.splice;function Gf(t){var e=this.__data__,r=pe(e,t);if(r<0)return!1;var a=e.length-1;return r==a?e.pop():Ff.call(e,r,1),--this.size,!0}var ca=Gf;function Uf(t){var e=this.__data__,r=pe(e,t);return r<0?void 0:e[r][1]}var da=Uf;function Bf(t){return pe(this.__data__,t)>-1}var la=Bf;function zf(t,e){var r=this.__data__,a=pe(r,t);return a<0?(++this.size,r.push([t,e])):r[a][1]=e,this}var pa=zf;function at(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var a=t[e];this.set(a[0],a[1])}}at.prototype.clear=ua;at.prototype.delete=ca;at.prototype.get=da;at.prototype.has=la;at.prototype.set=pa;var me=at;var Zf=G(N,"Map"),he=Zf;function Vf(){this.size=0,this.__data__={hash:new tr,map:new(he||me),string:new tr}}var ma=Vf;function Wf(t){var e=typeof t;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?t!=="__proto__":t===null}var ha=Wf;function Hf(t,e){var r=t.__data__;return ha(e)?r[typeof e=="string"?"string":"hash"]:r.map}var ge=Hf;function qf(t){var e=ge(this,t).delete(t);return this.size-=e?1:0,e}var ga=qf;function Kf(t){return ge(this,t).get(t)}var ya=Kf;function Yf(t){return ge(this,t).has(t)}var xa=Yf;function Jf(t,e){var r=ge(this,t),a=r.size;return r.set(t,e),this.size+=r.size==a?0:1,this}var _a=Jf;function nt(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var a=t[e];this.set(a[0],a[1])}}nt.prototype.clear=ma;nt.prototype.delete=ga;nt.prototype.get=ya;nt.prototype.has=xa;nt.prototype.set=_a;var Ne=nt;var Xf="Expected a function";function rr(t,e){if(typeof t!="function"||e!=null&&typeof e!="function")throw new TypeError(Xf);var r=function(){var a=arguments,n=e?e.apply(this,a):a[0],o=r.cache;if(o.has(n))return o.get(n);var s=t.apply(this,a);return r.cache=o.set(n,s)||o,s};return r.cache=new(rr.Cache||Ne),r}rr.Cache=Ne;var va=rr;var Qf=500;function eu(t){var e=va(t,function(a){return r.size===Qf&&r.clear(),a}),r=e.cache;return e}var ba=eu;var tu=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,ru=/\\(\\)?/g,au=ba(function(t){var e=[];return t.charCodeAt(0)===46&&e.push(""),t.replace(tu,function(r,a,n,o){e.push(n?o.replace(ru,"$1"):a||r)}),e}),wa=au;function nu(t){return t==null?"":Er(t)}var Ta=nu;function ou(t,e){return E(t)?t:tt(t,e)?[t]:wa(Ta(t))}var Rt=ou;var su=1/0;function iu(t){if(typeof t=="string"||ae(t))return t;var e=t+"";return e=="0"&&1/t==-su?"-0":e}var ye=iu;function fu(t,e){e=Rt(e,t);for(var r=0,a=e.length;t!=null&&r<a;)t=t[ye(e[r++])];return r&&r==a?t:void 0}var ot=fu;function uu(t,e,r){var a=t==null?void 0:ot(t,e);return a===void 0?r:a}var ka=uu;function cu(t,e){for(var r=-1,a=e.length,n=t.length;++r<a;)t[n+r]=e[r];return t}var Pt=cu;var Sa=D?D.isConcatSpreadable:void 0;function du(t){return E(t)||Qe(t)||!!(Sa&&t&&t[Sa])}var Oa=du;function Aa(t,e,r,a,n){var o=-1,s=t.length;for(r||(r=Oa),n||(n=[]);++o<s;){var i=t[o];e>0&&r(i)?e>1?Aa(i,e-1,r,a,n):Pt(n,i):a||(n[n.length]=i)}return n}var Ia=Aa;function lu(){this.__data__=new me,this.size=0}var Ca=lu;function pu(t){var e=this.__data__,r=e.delete(t);return this.size=e.size,r}var Ea=pu;function mu(t){return this.__data__.get(t)}var $a=mu;function hu(t){return this.__data__.has(t)}var Ra=hu;var gu=200;function yu(t,e){var r=this.__data__;if(r instanceof me){var a=r.__data__;if(!he||a.length<gu-1)return a.push([t,e]),this.size=++r.size,this;r=this.__data__=new Ne(a)}return r.set(t,e),this.size=r.size,this}var Pa=yu;function st(t){var e=this.__data__=new me(t);this.size=e.size}st.prototype.clear=Ca;st.prototype.delete=Ea;st.prototype.get=$a;st.prototype.has=Ra;st.prototype.set=Pa;var it=st;function xu(t,e){for(var r=-1,a=t==null?0:t.length,n=0,o=[];++r<a;){var s=t[r];e(s,r,t)&&(o[n++]=s)}return o}var Na=xu;function _u(){return[]}var ja=_u;var vu=Object.prototype,bu=vu.propertyIsEnumerable,Ma=Object.getOwnPropertySymbols,wu=Ma?function(t){return t==null?[]:(t=Object(t),Na(Ma(t),function(e){return bu.call(t,e)}))}:ja,Da=wu;function Tu(t,e,r){var a=e(t);return E(t)?a:Pt(a,r(t))}var La=Tu;function ku(t){return La(t,et,Da)}var ar=ku;var Su=G(N,"DataView"),Nt=Su;var Ou=G(N,"Promise"),jt=Ou;var Au=G(N,"Set"),Mt=Au;var Fa="[object Map]",Iu="[object Object]",Ga="[object Promise]",Ua="[object Set]",Ba="[object WeakMap]",za="[object DataView]",Cu=ne(Nt),Eu=ne(he),$u=ne(jt),Ru=ne(Mt),Pu=ne(Ct),je=V;(Nt&&je(new Nt(new ArrayBuffer(1)))!=za||he&&je(new he)!=Fa||jt&&je(jt.resolve())!=Ga||Mt&&je(new Mt)!=Ua||Ct&&je(new Ct)!=Ba)&&(je=function(t){var e=V(t),r=e==Iu?t.constructor:void 0,a=r?ne(r):"";if(a)switch(a){case Cu:return za;case Eu:return Fa;case $u:return Ga;case Ru:return Ua;case Pu:return Ba}return e});var nr=je;var Nu=N.Uint8Array,or=Nu;var ju="__lodash_hash_undefined__";function Mu(t){return this.__data__.set(t,ju),this}var Za=Mu;function Du(t){return this.__data__.has(t)}var Va=Du;function Dt(t){var e=-1,r=t==null?0:t.length;for(this.__data__=new Ne;++e<r;)this.add(t[e])}Dt.prototype.add=Dt.prototype.push=Za;Dt.prototype.has=Va;var Wa=Dt;function Lu(t,e){for(var r=-1,a=t==null?0:t.length;++r<a;)if(e(t[r],r,t))return!0;return!1}var Ha=Lu;function Fu(t,e){return t.has(e)}var qa=Fu;var Gu=1,Uu=2;function Bu(t,e,r,a,n,o){var s=r&Gu,i=t.length,f=e.length;if(i!=f&&!(s&&f>i))return!1;var u=o.get(t),d=o.get(e);if(u&&d)return u==e&&d==t;var m=-1,g=!0,_=r&Uu?new Wa:void 0;for(o.set(t,e),o.set(e,t);++m<i;){var A=t[m],k=e[m];if(a)var S=s?a(k,A,m,e,t,o):a(A,k,m,t,e,o);if(S!==void 0){if(S)continue;g=!1;break}if(_){if(!Ha(e,function(P,X){if(!qa(_,X)&&(A===P||n(A,P,r,a,o)))return _.push(X)})){g=!1;break}}else if(!(A===k||n(A,k,r,a,o))){g=!1;break}}return o.delete(t),o.delete(e),g}var Lt=Bu;function zu(t){var e=-1,r=Array(t.size);return t.forEach(function(a,n){r[++e]=[n,a]}),r}var Ka=zu;function Zu(t){var e=-1,r=Array(t.size);return t.forEach(function(a){r[++e]=a}),r}var Ya=Zu;var Vu=1,Wu=2,Hu="[object Boolean]",qu="[object Date]",Ku="[object Error]",Yu="[object Map]",Ju="[object Number]",Xu="[object RegExp]",Qu="[object Set]",ec="[object String]",tc="[object Symbol]",rc="[object ArrayBuffer]",ac="[object DataView]",Ja=D?D.prototype:void 0,sr=Ja?Ja.valueOf:void 0;function nc(t,e,r,a,n,o,s){switch(r){case ac:if(t.byteLength!=e.byteLength||t.byteOffset!=e.byteOffset)return!1;t=t.buffer,e=e.buffer;case rc:return!(t.byteLength!=e.byteLength||!o(new or(t),new or(e)));case Hu:case qu:case Ju:return Je(+t,+e);case Ku:return t.name==e.name&&t.message==e.message;case Xu:case ec:return t==e+"";case Yu:var i=Ka;case Qu:var f=a&Vu;if(i||(i=Ya),t.size!=e.size&&!f)return!1;var u=s.get(t);if(u)return u==e;a|=Wu,s.set(t,e);var d=Lt(i(t),i(e),a,n,o,s);return s.delete(t),d;case tc:if(sr)return sr.call(t)==sr.call(e)}return!1}var Xa=nc;var oc=1,sc=Object.prototype,ic=sc.hasOwnProperty;function fc(t,e,r,a,n,o){var s=r&oc,i=ar(t),f=i.length,u=ar(e),d=u.length;if(f!=d&&!s)return!1;for(var m=f;m--;){var g=i[m];if(!(s?g in e:ic.call(e,g)))return!1}var _=o.get(t),A=o.get(e);if(_&&A)return _==e&&A==t;var k=!0;o.set(t,e),o.set(e,t);for(var S=s;++m<f;){g=i[m];var P=t[g],X=e[g];if(a)var _t=s?a(X,P,g,e,t,o):a(P,X,g,t,e,o);if(!(_t===void 0?P===X||n(P,X,r,a,o):_t)){k=!1;break}S||(S=g=="constructor")}if(k&&!S){var Le=t.constructor,vt=e.constructor;Le!=vt&&"constructor"in t&&"constructor"in e&&!(typeof Le=="function"&&Le instanceof Le&&typeof vt=="function"&&vt instanceof vt)&&(k=!1)}return o.delete(t),o.delete(e),k}var Qa=fc;var uc=1,en="[object Arguments]",tn="[object Array]",Ft="[object Object]",cc=Object.prototype,rn=cc.hasOwnProperty;function dc(t,e,r,a,n,o){var s=E(t),i=E(e),f=s?tn:nr(t),u=i?tn:nr(e);f=f==en?Ft:f,u=u==en?Ft:u;var d=f==Ft,m=u==Ft,g=f==u;if(g&&ht(t)){if(!ht(e))return!1;s=!0,d=!1}if(g&&!d)return o||(o=new it),s||$t(t)?Lt(t,e,r,a,n,o):Xa(t,e,f,r,a,n,o);if(!(r&uc)){var _=d&&rn.call(t,"__wrapped__"),A=m&&rn.call(e,"__wrapped__");if(_||A){var k=_?t.value():t,S=A?e.value():e;return o||(o=new it),n(k,S,r,a,o)}}return g?(o||(o=new it),Qa(t,e,r,a,n,o)):!1}var an=dc;function nn(t,e,r,a,n){return t===e?!0:t==null||e==null||!W(t)&&!W(e)?t!==t&&e!==e:an(t,e,r,a,nn,n)}var Gt=nn;var lc=1,pc=2;function mc(t,e,r,a){var n=r.length,o=n,s=!a;if(t==null)return!o;for(t=Object(t);n--;){var i=r[n];if(s&&i[2]?i[1]!==t[i[0]]:!(i[0]in t))return!1}for(;++n<o;){i=r[n];var f=i[0],u=t[f],d=i[1];if(s&&i[2]){if(u===void 0&&!(f in t))return!1}else{var m=new it;if(a)var g=a(u,d,f,t,e,m);if(!(g===void 0?Gt(d,u,lc|pc,a,m):g))return!1}}return!0}var on=mc;function hc(t){return t===t&&!ce(t)}var Ut=hc;function gc(t){for(var e=et(t),r=e.length;r--;){var a=e[r],n=t[a];e[r]=[a,n,Ut(n)]}return e}var sn=gc;function yc(t,e){return function(r){return r==null?!1:r[t]===e&&(e!==void 0||t in Object(r))}}var Bt=yc;function xc(t){var e=sn(t);return e.length==1&&e[0][2]?Bt(e[0][0],e[0][1]):function(r){return r===t||on(r,t,e)}}var fn=xc;function _c(t,e){return t!=null&&e in Object(t)}var un=_c;function vc(t,e,r){e=Rt(e,t);for(var a=-1,n=e.length,o=!1;++a<n;){var s=ye(e[a]);if(!(o=t!=null&&r(t,s)))break;t=t[s]}return o||++a!=n?o:(n=t==null?0:t.length,!!n&&Xe(n)&&Ye(s,n)&&(E(t)||Qe(t)))}var cn=vc;function bc(t,e){return t!=null&&cn(t,e,un)}var dn=bc;var wc=1,Tc=2;function kc(t,e){return tt(t)&&Ut(e)?Bt(ye(t),e):function(r){var a=ka(r,t);return a===void 0&&a===e?dn(r,t):Gt(e,a,wc|Tc)}}var ln=kc;function Sc(t){return function(e){return e?.[t]}}var pn=Sc;function Oc(t){return function(e){return ot(e,t)}}var mn=Oc;function Ac(t){return tt(t)?pn(ye(t)):mn(t)}var hn=Ac;function Ic(t){return typeof t=="function"?t:t==null?de:typeof t=="object"?E(t)?ln(t[0],t[1]):fn(t):hn(t)}var zt=Ic;function Cc(t,e,r,a){for(var n=-1,o=t==null?0:t.length;++n<o;){var s=t[n];e(a,s,r(s),t)}return a}var gn=Cc;function Ec(t){return function(e,r,a){for(var n=-1,o=Object(e),s=a(e),i=s.length;i--;){var f=s[t?i:++n];if(r(o[f],f,o)===!1)break}return e}}var yn=Ec;var $c=yn(),xn=$c;function Rc(t,e){return t&&xn(t,e,et)}var _n=Rc;function Pc(t,e){return function(r,a){if(r==null)return r;if(!le(r))return t(r,a);for(var n=r.length,o=e?n:-1,s=Object(r);(e?o--:++o<n)&&a(s[o],o,s)!==!1;);return r}}var vn=Pc;var Nc=vn(_n),Zt=Nc;function jc(t,e,r,a){return Zt(t,function(n,o,s){e(a,n,r(n),s)}),a}var bn=jc;function Mc(t,e){return function(r,a){var n=E(r)?gn:bn,o=e?e():{};return n(r,t,zt(a,2),o)}}var wn=Mc;function Dc(t,e){var r=-1,a=le(t)?Array(t.length):[];return Zt(t,function(n,o,s){a[++r]=e(n,o,s)}),a}var Tn=Dc;var Lc=Object.prototype,Fc=Lc.hasOwnProperty,Gc=wn(function(t,e,r){Fc.call(t,r)?t[r].push(e):Gr(t,r,[e])}),yt=Gc;function Uc(t,e){var r=t.length;for(t.sort(e);r--;)t[r]=t[r].value;return t}var kn=Uc;function Bc(t,e){if(t!==e){var r=t!==void 0,a=t===null,n=t===t,o=ae(t),s=e!==void 0,i=e===null,f=e===e,u=ae(e);if(!i&&!u&&!o&&t>e||o&&s&&f&&!i&&!u||a&&s&&f||!r&&f||!n)return 1;if(!a&&!o&&!u&&t<e||u&&r&&n&&!a&&!o||i&&r&&n||!s&&n||!f)return-1}return 0}var Sn=Bc;function zc(t,e,r){for(var a=-1,n=t.criteria,o=e.criteria,s=n.length,i=r.length;++a<s;){var f=Sn(n[a],o[a]);if(f){if(a>=i)return f;var u=r[a];return f*(u=="desc"?-1:1)}}return t.index-e.index}var On=zc;function Zc(t,e,r){e.length?e=qe(e,function(o){return E(o)?function(s){return ot(s,o.length===1?o[0]:o)}:o}):e=[de];var a=-1;e=qe(e,Et(zt));var n=Tn(t,function(o,s,i){var f=qe(e,function(u){return u(o)});return{criteria:f,index:++a,value:o}});return kn(n,function(o,s){return On(o,s,r)})}var An=Zc;var Vc=zr(function(t,e){if(t==null)return[];var r=e.length;return r>1&&Jt(t,e[0],e[1])?e=[]:r>2&&Jt(e[0],e[1],e[2])&&(e=[e[0]]),An(t,Ia(e,1),[])}),ir=Vc;H();function O(t){return{content:[{type:"text",text:t}]}}function J(t,e){return!t||t.length<=e?t:t.slice(0,e)+"..."}var ct=200;function Hn(t){t.tool("search",`Search Sigil knowledge base for facts across all ingested documents.
|
|
338
7
|
Automatically detects entity names and returns entity-centric results.
|
|
339
8
|
Use for: "how does X work", "what is Y?", "what are the rules for Z", domain knowledge, decisions.
|
|
340
9
|
Returns compact facts. Use get_fact_context(factId) for full detail on any fact.
|
|
341
10
|
Set includeChunks=true only when raw document context is needed.
|
|
342
|
-
Set format="compact" for token-efficient output (one line per category, no IDs/metadata).`,{query:
|
|
343
|
-
${
|
|
344
|
-
_Drill down: get_entity_context(entityId=${_.id}) for full details about ${_.name}_`),
|
|
345
|
-
`))})}function
|
|
346
|
-
`);let
|
|
347
|
-
`)}
|
|
11
|
+
Set format="compact" for token-efficient output (one line per category, no IDs/metadata).`,{query:y.string().describe("Natural language search query"),limit:y.number().optional().default(5).describe("Max facts to return (default 5)"),namespaces:y.array(y.string()).optional().describe("Filter by namespaces"),minConfidence:y.enum(["low","medium","high"]).optional().default("medium").describe("Minimum fact confidence"),includeChunks:y.boolean().optional().default(!1).describe("Include raw document chunks (verbose \u2014 only when needed)"),useGraph:y.boolean().optional().default(!1).describe("Traverse entity graph for additional related facts"),pointInTime:y.string().optional().describe("ISO timestamp \u2014 return only facts valid at this point in time"),format:y.enum(["full","compact"]).optional().default("full").describe('Output format: "full" (default) or "compact" (token-efficient, one line per category)'),podScope:y.union([y.literal("auto"),y.literal("global"),y.array(y.string())]).optional().describe('Pod scope: "auto" (active project/session pods \u2014 the default), "global" (whole brain, no scope), or list of pod uids/names.')},async({query:e,limit:r,namespaces:a,minConfidence:n,includeChunks:o,useGraph:s,pointInTime:i,format:f,podScope:u})=>{let d=await R("search",{query:e,namespaces:a,limit:r,minConfidence:n,includeChunks:o,useGraph:s,pointInTime:i,podScope:u??"auto",cwd:process.cwd(),route:!1,synthesize:!1}),{facts:m,chunks:g,matchedEntity:_,relatedEntities:A}=d;if(f==="compact")return O(gd(m,_));let k=[];if(_&&(k.push(`**Matched entity:** ${_.name} (${_.entityType||_.type}, id:${_.id}, ${_.mentions??_.mentionCount??0} mentions)`),_.description&&k.push(_.description),k.push("")),m.length){k.push(`**Facts (${m.length}):**`);for(let S of m){let P=J(S.content,ct),X=S.importance==="vital"?" **[VITAL]**":"",_t=S.agent?` \xB7 via ${S.agent}`:"",Le=Array.isArray(S.sourceDocumentIds)&&S.sourceDocumentIds.length?` \xB7 doc#${S.sourceDocumentIds[0]}`:"";k.push(`- [${S.category}] ${P}${X} _(${S.confidence}, id:${S.id}${_t}${Le})_`)}}if(A.length){k.push(""),k.push(`**Related entities (${A.length}):**`);for(let S of A.slice(0,10))k.push(`- ${S.name} (${S.entityType||S.type}) [${S.relation}] id:${S.id}`)}if(o&&g.length){k.push(""),k.push(`**Chunks (${g.length}):**`);for(let S of g.slice(0,3)){let P=S.sectionHeading?`[${S.sectionHeading}] `:"";k.push(`---
|
|
12
|
+
${P}${J(S.content,500)}`)}}return!m.length&&!g.length&&k.push("No results found. Try broader terms or use search_entity to find entity names."),_&&k.push(`
|
|
13
|
+
_Drill down: get_entity_context(entityId=${_.id}) for full details about ${_.name}_`),O(k.join(`
|
|
14
|
+
`))})}function gd(t,e){let r=[];if(e&&r.push(`> ${e.name} (${e.entityType||e.type})`),!t.length)return r.push("No results."),r.join(`
|
|
15
|
+
`);let a=yt(t,"category");for(let[n,o]of Object.entries(a)){let i=ir(o,f=>f.importance==="vital"?0:1).map(f=>f.content);r.push(`[${n}]: ${i.join(". ")}`)}return r.join(`
|
|
16
|
+
`)}H();function qn(t){t.tool("search_entity",`Find entities in the knowledge graph by name or type.
|
|
348
17
|
Use for: "find Alice", "list all topics", "show all people", "find documents about normalization".
|
|
349
18
|
Entity types: document, person, topic (extensible per domain).
|
|
350
|
-
Returns compact entity list. Use get_entity_context(entityId) for full details.`,{query:
|
|
351
|
-
${
|
|
19
|
+
Returns compact entity list. Use get_entity_context(entityId) for full details.`,{query:y.string().optional().describe('Entity name to search (e.g. "Alice", "Cohort 6")'),entityType:y.string().optional().describe("Filter by type: session, course, person, topic"),limit:y.number().optional().default(10).describe("Max results"),namespace:y.string().optional().describe("Namespace. Omit for default.")},async({query:e,entityType:r,limit:a,namespace:n})=>{if(!e&&!r)return O("Error: Provide either a query (entity name) or entityType.");let{entities:o}=await R("searchEntity",{query:e,entityType:r,limit:a,namespace:n});if(!o.length){let f=e?`matching "${e}"`:`of type "${r}"`;return O(`No entities found ${f}.`)}let s=o.map(f=>{let u=f.description?` \u2014 ${f.description}`:"";return`- **${f.name}** (${f.entityType}, id:${f.id}, ${f.mentionCount} mentions)${u}`}),i=e?`Entities matching "${e}"`:`${r} entities`;return O(`${i} (${o.length}):
|
|
20
|
+
${s.join(`
|
|
352
21
|
`)}
|
|
353
22
|
|
|
354
|
-
_Use get_entity_context(entityId=<id>) for details or traverse_graph(startEntityId=<id>) for connections._`)})}
|
|
355
|
-
WITH RECURSIVE graph AS (
|
|
356
|
-
SELECT r.target_id AS entity_id, r.relation_type, r.mention_count,
|
|
357
|
-
1 AS depth, ARRAY[?::integer] AS path
|
|
358
|
-
FROM relation r
|
|
359
|
-
WHERE r.source_id = ?
|
|
360
|
-
AND r.invalid_at IS NULL
|
|
361
|
-
${i}
|
|
362
|
-
|
|
363
|
-
UNION ALL
|
|
364
|
-
|
|
365
|
-
SELECT r.target_id, r.relation_type, r.mention_count,
|
|
366
|
-
g.depth + 1, g.path || r.target_id
|
|
367
|
-
FROM relation r
|
|
368
|
-
JOIN graph g ON r.source_id = g.entity_id
|
|
369
|
-
WHERE g.depth < ?
|
|
370
|
-
AND r.invalid_at IS NULL
|
|
371
|
-
AND NOT (r.target_id = ANY(g.path))
|
|
372
|
-
${s}
|
|
373
|
-
)
|
|
374
|
-
SELECT DISTINCT ON (g.entity_id)
|
|
375
|
-
g.entity_id AS "entityId", g.relation_type AS "relationType",
|
|
376
|
-
g.depth, g.mention_count AS "mentionCount",
|
|
377
|
-
e.name, e.entity_type AS "entityType", e.description, e.uid
|
|
378
|
-
FROM graph g
|
|
379
|
-
JOIN entity e ON e.id = g.entity_id
|
|
380
|
-
WHERE e.merged_with IS NULL
|
|
381
|
-
ORDER BY g.entity_id, g.depth ASC
|
|
382
|
-
LIMIT ?
|
|
383
|
-
`,a);return c}async function bd(e,{depth:t=1,limit:r=50}={}){let n=await q(e);if(!n)return null;if(t>1){let a=await Zo(e,{maxDepth:t,limit:r});return{entity:n,related:a}}let o=await or(e,{limit:r});return{entity:n,relations:o}}async function Td(e,t,{maxDepth:r=4}={}){let n=Math.min(Math.max(r,1),6),{rows:o}=await m.raw(`
|
|
384
|
-
WITH RECURSIVE search AS (
|
|
385
|
-
SELECT r.target_id AS current_id,
|
|
386
|
-
ARRAY[r.source_id, r.target_id] AS path,
|
|
387
|
-
ARRAY[r.relation_type] AS relation_types,
|
|
388
|
-
1 AS depth
|
|
389
|
-
FROM relation r
|
|
390
|
-
WHERE r.source_id = ?
|
|
391
|
-
AND r.invalid_at IS NULL
|
|
392
|
-
|
|
393
|
-
UNION ALL
|
|
394
|
-
|
|
395
|
-
SELECT r.target_id,
|
|
396
|
-
s.path || r.target_id,
|
|
397
|
-
s.relation_types || r.relation_type,
|
|
398
|
-
s.depth + 1
|
|
399
|
-
FROM relation r
|
|
400
|
-
JOIN search s ON r.source_id = s.current_id
|
|
401
|
-
WHERE s.depth < ?
|
|
402
|
-
AND r.invalid_at IS NULL
|
|
403
|
-
AND NOT (r.target_id = ANY(s.path))
|
|
404
|
-
)
|
|
405
|
-
SELECT path, relation_types AS "relationTypes", depth
|
|
406
|
-
FROM search
|
|
407
|
-
WHERE current_id = ?
|
|
408
|
-
ORDER BY depth ASC
|
|
409
|
-
LIMIT 1
|
|
410
|
-
`,[e,n,t]);if(!o.length)return null;let{path:a,relationTypes:i,depth:s}=o[0],c=await m("entity").whereIn("id",a).select("id","uid","name","entityType","description"),u=Object.fromEntries(c.map(p=>[p.id,p]));return{path:a.map(p=>u[p]),relationTypes:i,depth:s}}function Sd(e){e.tool("traverse_graph",`Navigate entity relationships in the knowledge graph.
|
|
23
|
+
_Use get_entity_context(entityId=<id>) for details or traverse_graph(startEntityId=<id>) for connections._`)})}H();function Kn(t){t.tool("traverse_graph",`Navigate entity relationships in the knowledge graph.
|
|
411
24
|
Use for: "who did Alice mentor?", "what topics does course X cover?", "how is A related to B?",
|
|
412
25
|
"what documents cover this topic?", "show mentorship chain".
|
|
413
|
-
Relation types: PART_OF, LED_BY, MENTORED, COVERS, FOLLOWS.`,{startEntityId:
|
|
414
|
-
|
|
415
|
-
${
|
|
416
|
-
`)
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
${
|
|
422
|
-
${
|
|
423
|
-
`))}
|
|
26
|
+
Relation types: PART_OF, LED_BY, MENTORED, COVERS, FOLLOWS.`,{startEntityId:y.number().describe("Starting entity ID (from search_entity results)"),action:y.enum(["neighbors","path","related"]).optional().default("neighbors").describe("neighbors = direct connections, path = shortest path to target, related = all reachable"),targetEntityId:y.number().optional().describe('Target entity ID (required for "path" action)'),relationType:y.string().optional().describe("Filter: PART_OF, LED_BY, MENTORED, COVERS, FOLLOWS"),maxDepth:y.number().optional().default(2).describe("Traversal depth 1-3"),limit:y.number().optional().default(20).describe("Max results")},async({startEntityId:e,action:r,targetEntityId:a,relationType:n,maxDepth:o,limit:s})=>{let i=await R("traverseGraph",{startEntityId:e,action:r,targetEntityId:a,relationType:n,maxDepth:o,limit:s});if(i.notFound)return O(`Error: Entity ID ${e} not found.`);let f=`${i.start.name} (${i.start.entityType}, id:${i.start.id})`;if(i.action==="path"){if(!i.path)return O(`No path found from ${i.start.name} to entity ${a}.`);let g=i.path.path.map((_,A)=>{let k=A<i.path.relationTypes.length?` --[${i.path.relationTypes[A]}]--> `:"";return`${_.name} (${_.entityType})${k}`});return O(`Path (${i.path.depth} hops):
|
|
27
|
+
${g.join("")}`)}if(i.action==="related"){let g=i.related||[];if(!g.length)return O(`${i.start.name} has no related entities within ${o} hops.`);let _=yt(g,"depth"),A=[`Entities related to ${f} (${g.length}):`];for(let k of Object.keys(_).sort()){let S=k==="1"?"Direct":`${k} hops`;A.push(`
|
|
28
|
+
${S}:`);for(let P of _[k])A.push(`- [${P.relationType}] ${P.name} (${P.entityType}, id:${P.entityId})`)}return O(A.join(`
|
|
29
|
+
`))}if(i.related){let g=i.related.map(_=>`- [${_.relationType}] ${_.name} (${_.entityType}, id:${_.entityId||_.id}) depth:${_.depth}`);return O(`${f}
|
|
30
|
+
Connections (${i.related.length}):
|
|
31
|
+
${g.join(`
|
|
32
|
+
`)}`)}if(!i.relations?.length)return O(`${f}
|
|
33
|
+
No connections found.`);let u=i.relations.filter(g=>g.direction==="outgoing"),d=i.relations.filter(g=>g.direction==="incoming"),m=[f];if(u.length){m.push(`
|
|
34
|
+
Outgoing (${u.length}):`);for(let g of u)m.push(`- [${g.relationType}] ${g.name} (${g.entityType}, id:${g.entityId})`)}if(d.length){m.push(`
|
|
35
|
+
Incoming (${d.length}):`);for(let g of d)m.push(`- ${g.name} (${g.entityType}, id:${g.entityId}) [${g.relationType}]`)}return O(m.join(`
|
|
36
|
+
`))})}H();function Yn(t){t.tool("get_fact_context",`Get full context for a specific fact: complete content, entities mentioned, relations created, sources.
|
|
424
37
|
Use for: drilling down on a fact from search results, checking provenance, understanding connections.
|
|
425
|
-
This is the detail view \u2014 search returns truncated facts, this returns everything.`,{factId:
|
|
426
|
-
Entities mentioned: ${o.map(
|
|
427
|
-
Relations from this fact:`);for(let
|
|
428
|
-
Sources: ${i.map(
|
|
429
|
-
`))})}
|
|
38
|
+
This is the detail view \u2014 search returns truncated facts, this returns everything.`,{factId:y.number().optional().describe("Fact ID (from search results)"),uid:y.string().optional().describe('Fact UID (e.g. "fact-a1b2c3d4")')},async({uid:e,factId:r})=>{if(!e&&!r)return O("Error: Provide either factId or uid.");let a=await R("getFactContext",{uid:e,factId:r});if(a.notFound)return O("Error: Fact not found.");let{fact:n,entities:o,relations:s,documents:i}=a,f=[`**Fact ${n.uid}** (${n.category}, ${n.confidence}, ${n.status})`,n.content];if(n.sourceSection&&f.push(`Source section: ${n.sourceSection}`),o.length&&f.push(`
|
|
39
|
+
Entities mentioned: ${o.map(u=>`${u.name} (${u.entityType}, id:${u.id})`).join(", ")}`),s.length){f.push(`
|
|
40
|
+
Relations from this fact:`);for(let u of s)f.push(`- ${u.sourceName} --[${u.relationType}]--> ${u.targetName}`)}return i.length&&f.push(`
|
|
41
|
+
Sources: ${i.map(u=>`${u.title} (${u.sourceType})`).join(", ")}`),O(f.join(`
|
|
42
|
+
`))})}H();function Jn(t){t.tool("get_entity_context",`Get full context for an entity: relations, connected facts, graph position.
|
|
430
43
|
Use for: "tell me about Alice", "what documents cover this topic?", "show expertise areas".
|
|
431
|
-
Returns entity details + relations + key facts (truncated \u2014 use get_fact_context for full text).`,{entityId:
|
|
432
|
-
Outgoing relations (${
|
|
433
|
-
Incoming relations (${
|
|
434
|
-
Key facts (${i.length}):`);for(let
|
|
435
|
-
No connections or facts found for this entity.`),
|
|
436
|
-
_Use traverse_graph(startEntityId=${o.id}) for deeper graph exploration._`),
|
|
437
|
-
`))})}
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
ON CONFLICT (source_path, namespace) DO UPDATE SET
|
|
441
|
-
title = EXCLUDED.title,
|
|
442
|
-
content_hash = EXCLUDED.content_hash,
|
|
443
|
-
last_ingested_at = NOW(),
|
|
444
|
-
updated_at = NOW()
|
|
445
|
-
RETURNING *, (xmax = 0) AS "isNew", content_hash != ? AS "contentChanged"
|
|
446
|
-
`,[a,e,t,r,n,o,n]),c=i.isNew||i.contentChanged;return{doc:i,changed:c}}async function Jo(e,{chunkCount:t,factCount:r}){await m("document").where({id:e}).update({chunkCount:t,factCount:r})}async function Cd(e){let t=m("document");e&&t.where({namespace:e});let r=await t;return{documentCount:r.length,totalChunks:r.reduce((n,o)=>n+(o.chunkCount||0),0),totalFacts:r.reduce((n,o)=>n+(o.factCount||0),0)}}async function Nd(e){await m("document").where({id:e}).update({contentHash:null})}async function Rd(e,t,r=null){if(!t&&!r)return;let n={};t&&Object.keys(t).length&&(n.sourceMetadata=JSON.stringify(t)),r&&(n.connectionId=r),Object.keys(n).length&&await m("document").where({id:e}).update(n)}we();function kd(e){e.tool("status",`Show Sigil knowledge base statistics \u2014 documents, chunks, facts, entities, relations.
|
|
447
|
-
Use when: checking system health, verifying ingestion, reviewing knowledge graph size.`,{namespace:T.string().optional().describe("Filter by namespace. Omit for global stats.")},async({namespace:t})=>{let[r,n,o,a,i,s,c]=await Promise.all([Cd(t),Bl(t),Rr("document"),Rr("person"),Rr("topic"),Gl(),jl(t,{limit:5})]),l=[`Sigil KB${t?` (${t})`:""}: ${r.documentCount} docs, ${r.totalChunks} chunks, ${n} facts`,`Entities: ${o} documents, ${a} people, ${i} topics`,`Relations: ${s}`,`Hot facts (top ${c.length}): ${c.map(p=>`${ve(p.content,60)} (${p.accessCount}x)`).join(", ")||"none yet"}`].join(`
|
|
448
|
-
`);return L(l)})}import{createHash as zE}from"node:crypto";import{join as KE}from"node:path";function Ld(e){let t=e.split(`
|
|
449
|
-
`),r=[],n=null,o=[];for(let s of t){let c=s.match(/^(#{1,6})\s+(.+)/);c?(o.length&&r.push({heading:n||"Introduction",text:o.join(`
|
|
450
|
-
`).trim()}),n=c[2].trim(),o=[]):o.push(s)}o.length&&r.push({heading:n||"Content",text:o.join(`
|
|
451
|
-
`).trim()});let a=r.map(s=>s.text).join(`
|
|
452
|
-
|
|
453
|
-
`),i=rE(t)||null;return{text:a,sections:r,metadata:{title:i}}}function rE(e){for(let t of e){let r=t.match(/^#\s+(.+)/);if(r)return r[1].trim()}return null}function Xo(e){let t=e.split(/\n{2,}/).map(n=>n.trim()).filter(Boolean),r=t.length>1?t.map((n,o)=>({heading:`Section ${o+1}`,text:n})):[{heading:"Content",text:e.trim()}];return{text:e.trim(),sections:r,metadata:{}}}function Dd(e){let t=nE(e),r=e.replace(/<script[\s\S]*?<\/script>/gi,"");return r=r.replace(/<style[\s\S]*?<\/style>/gi,""),r=r.replace(/<\/(p|div|h[1-6]|li|tr|br|hr)>/gi,`
|
|
454
|
-
`),r=r.replace(/<br\s*\/?>/gi,`
|
|
455
|
-
`),r=r.replace(/<[^>]+>/g,""),r=r.replace(/&/g,"&"),r=r.replace(/</g,"<"),r=r.replace(/>/g,">"),r=r.replace(/"/g,'"'),r=r.replace(/'/g,"'"),r=r.replace(/ /g," "),r=r.replace(/[ \t]+/g," "),r=r.replace(/\n{3,}/g,`
|
|
456
|
-
|
|
457
|
-
`),r=r.trim(),{text:r,sections:[{heading:"Content",text:r}],metadata:{title:t}}}function nE(e){let t=e.match(/<title[^>]*>([\s\S]*?)<\/title>/i);return t?t[1].trim():null}function Pd(e,{language:t}={}){let r=t||sE(e),n=oE(e,r);return{text:e.trim(),sections:n,metadata:{language:r}}}function oE(e,t){let r=e.split(`
|
|
458
|
-
`),n=[],o="Header",a=[],i=!1,s=0;for(let c of r){let u=aE(c,t);u&&s===0?(a.length&&n.push({heading:o,text:a.join(`
|
|
459
|
-
`).trim()}),o=u,a=[c],i=!0):a.push(c);for(let l of c)l==="{"&&s++,l==="}"&&(s=Math.max(0,s-1))}return a.length&&n.push({heading:o,text:a.join(`
|
|
460
|
-
`).trim()}),n.length<=1?iE(e):n.filter(c=>c.text)}function aE(e,t){let r=e.trim(),n=[/^(?:export\s+)?(?:async\s+)?function\s+(\w+)/,/^(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*(?:async\s*)?\(/,/^(?:export\s+)?class\s+(\w+)/,/^(?:export\s+)?(?:const|let|var)\s+(\w+)\s*=\s*\{/,/^(?:export\s+default\s+)/],o=[/^(?:async\s+)?def\s+(\w+)/,/^class\s+(\w+)/],a=[/^func\s+(?:\(\w+\s+\*?\w+\)\s+)?(\w+)/,/^type\s+(\w+)/],i=[...n,...o,...a];for(let s of i){let c=r.match(s);if(c)return c[1]||c[0].slice(0,40)}return null}function iE(e){return e.split(/\n{2,}/).map((r,n)=>({heading:`Block ${n+1}`,text:r.trim()})).filter(r=>r.text)}function sE(e){return e.includes("import ")&&(e.includes("from ")||e.includes("require("))?"javascript":e.match(/^def\s/m)||e.match(/^class\s.*:/m)?"python":e.match(/^func\s/m)||e.includes("package ")?"go":e.match(/^fn\s/m)||e.includes("use ")?"rust":"unknown"}function $d(e){let t;try{t=typeof e=="string"?JSON.parse(e):e}catch{return{text:e,sections:[{heading:"Content",text:e}],metadata:{}}}let r=Qo(t);return{text:r,sections:[{heading:"Content",text:r}],metadata:{}}}function Qo(e,t=0){if(e==null)return"";if(Array.isArray(e))return e.map((r,n)=>typeof r=="object"&&r!==null?`Item ${n+1}:
|
|
461
|
-
${Qo(r,t+1)}`:`- ${r}`).join(`
|
|
462
|
-
`);if(typeof e=="object"){let r=" ".repeat(t);return Object.entries(e).filter(([,n])=>n!=null).map(([n,o])=>typeof o=="object"?`${r}${n}:
|
|
463
|
-
${Qo(o,t+1)}`:`${r}${n}: ${o}`).join(`
|
|
464
|
-
`)}return String(e)}var cE={".md":"markdown",".mdx":"markdown",".txt":"text",".html":"html",".htm":"html",".json":"json",".js":"code",".ts":"code",".jsx":"code",".tsx":"code",".py":"code",".go":"code",".rs":"code",".java":"code",".rb":"code",".php":"code",".c":"code",".cpp":"code",".h":"code",".cs":"code",".swift":"code",".kt":"code",".yaml":"text",".yml":"text",".toml":"text",".ini":"text",".cfg":"text",".env":"text",".csv":"text",".sql":"code",".sh":"code",".bash":"code",".zsh":"code"},uE={"text/markdown":"markdown","text/html":"html","text/plain":"text","application/json":"json","text/javascript":"code","application/javascript":"code","text/x-python":"code"},lE={markdown:Ld,text:Xo,html:Dd,code:Pd,json:$d};function Md(e,{format:t,filePath:r,contentType:n}={}){let o=t||dE(n)||fE(r)||pE(e);return(lE[o]||Xo)(e)}function dE(e){if(!e)return null;let t=e.split(";")[0].trim();return uE[t]||null}function fE(e){if(!e)return null;let t=e.match(/\.[^.]+$/)?.[0]?.toLowerCase();return t&&cE[t]||null}function pE(e){if(!e)return"text";let t=e.trim();return t.startsWith("{")||t.startsWith("[")?"json":t.startsWith("<!DOCTYPE")||t.startsWith("<html")?"html":t.match(/^#{1,6}\s/m)?"markdown":t.match(/^(import|export|function|class|const|let|var|def|func|package)\s/m)?"code":"text"}function mE(e,{maxTokens:t=512,overlapTokens:r=50}={}){if(!e?.trim())return[];let n=t*4,o=r*4;if(e.length<=n)return[{content:e.trim(),index:0}];let a=hE(e),i=[],s="",c="";for(let u of a){if(u.length>n){s.trim()&&(i.push({content:s.trim(),index:i.length}),c=ea(s,o),s="");let l=yE(u,n,o);for(let p of l)i.push({content:p.trim(),index:i.length});c=ea(i[i.length-1].content,o);continue}(s+u).length>n?(i.push({content:s.trim(),index:i.length}),c=ea(s,o),s=c+u):s+=u}return s.trim()&&i.push({content:s.trim(),index:i.length}),i}function Fd(e,t={}){let r=[];for(let{heading:n,text:o}of e){if(!o?.trim())continue;let a=mE(o,t);for(let i of a)r.push({content:i.content,index:r.length,sectionHeading:n})}return r}function hE(e){return e.split(/(?<=[.!?])\s+|(?<=\n)\s*/).filter(r=>r.trim())}function yE(e,t,r){let n=[],o=0;for(;o<e.length;){let a=Math.min(o+t,e.length);if(n.push(e.slice(o,a)),o=a-r,o>=e.length)break}return n}function ea(e,t){if(e.length<=t)return e;let r=e.slice(-t),n=r.search(/[.!?]\s+/);return n!==-1?r.slice(n+1).trimStart():r}import{readFile as gE}from"node:fs/promises";import{join as _E}from"node:path";D();Re();var xE=_E(ie,"chunk-context.md");async function jd(e,t,{title:r}){if(!e.length)return e;let n=await gE(xE,"utf8"),o=e.map((i,s)=>`Chunk ${s+1}: ${i.content.slice(0,200)}`),a=`${n}
|
|
465
|
-
|
|
466
|
-
---
|
|
467
|
-
|
|
468
|
-
**Document title:** ${r}
|
|
469
|
-
|
|
470
|
-
**Full document:**
|
|
471
|
-
${t.slice(0,8e3)}
|
|
472
|
-
|
|
473
|
-
**Chunks (${e.length}):**
|
|
474
|
-
${o.join(`
|
|
475
|
-
`)}
|
|
476
|
-
|
|
477
|
-
---
|
|
478
|
-
|
|
479
|
-
Respond with a JSON array of ${e.length} context prefix strings.`;try{let i=await Ee(a,{model:y.llm.extractionModel,caller:"contextualizer"}),s=Array.isArray(i)?i:i&&typeof i=="object"?Object.values(i).find(u=>Array.isArray(u))??null:null;if(!s)return console.warn("[contextualizer] LLM did not return an array \u2014 skipping"),e;let c=s;return c.length!==e.length&&console.warn(`[contextualizer] Got ${c.length} prefixes for ${e.length} chunks \u2014 using partial`),e.map((u,l)=>({...u,contextualPrefix:typeof c[l]=="string"?c[l]:null}))}catch(i){return console.error("[contextualizer] Failed:",i.message),e}}P();Ve();async function Bd(e,t,r){if(await m("chunk").where({documentId:e}).del(),!t.length)return[];let n=t.map((a,i)=>({documentId:e,chunkIndex:i,content:a.content,contextualPrefix:a.contextualPrefix||null,sectionHeading:a.sectionHeading||null,namespace:r,embedding:V(a.embedding)})),o=await m("chunk").insert(n).returning("*");return await m.raw(`
|
|
480
|
-
UPDATE chunk
|
|
481
|
-
SET search_vector = to_tsvector('english', COALESCE(contextual_prefix, '') || ' ' || content)
|
|
482
|
-
WHERE document_id = ?
|
|
483
|
-
`,[e]),o}er();import{readFile as EE}from"node:fs/promises";D();var vE=5;function bE(e){let t=[];return e.sectionHeading&&t.push(`[Section: ${e.sectionHeading}]`),e.contextualPrefix&&t.push(e.contextualPrefix),t.push(e.content),t.join(`
|
|
484
|
-
`)}function TE(e,t,r){return`${e}
|
|
485
|
-
|
|
486
|
-
---
|
|
487
|
-
|
|
488
|
-
${t}
|
|
489
|
-
|
|
490
|
-
---
|
|
491
|
-
|
|
492
|
-
Respond with ONLY a JSON array of facts. Each fact object must have exactly these fields:
|
|
493
|
-
- "content" (string): the atomic fact statement
|
|
494
|
-
- "category" (string): one of ${r.join(", ")}
|
|
495
|
-
- "confidence" (string): one of high, medium, low
|
|
496
|
-
- "importance" (string): "vital" if essential to understanding the topic, "supplementary" if supporting detail
|
|
497
|
-
|
|
498
|
-
Output the JSON array directly, no explanation or wrapping.`}function SE(e,t){let r=Array.isArray(e)?e:Array.isArray(e?.facts)?e.facts:null;return r?r.filter(n=>n.content&&t.includes(n.category)&&["high","medium","low"].includes(n.confidence)).map(n=>({...n,importance:["vital","supplementary"].includes(n.importance)?n.importance:"supplementary"})):[]}async function AE(e,t,r){let n=bE(e),o=TE(t,n,r),a=await Ee(o,{model:y.llm.extractionModel,caller:"extractor"});return SE(a,r).map(s=>({...s,sourceSection:e.sectionHeading||null}))}async function Ud(e,{promptPath:t,categories:r}){if(!e.length)return[];let n=await EE(t,"utf8"),o=io(e,vE),a=[];for(let i of o){let s=await Promise.all(i.map(c=>AE(c,n,r).catch(u=>(console.error(`[extractor] chunk failed: ${u.message}`),[]))));a.push(...s.flat())}return a}var jn={preference:"Personal likes, dislikes, favorites, preferred tools/foods/methods",opinion:"Personal views, assessments, evaluations of tools/concepts/approaches",personal:"Personal facts \u2014 birthday, workplace, location, biographical details",experience:"Personal experiences \u2014 projects built, tools used, skills acquired",business_rule:"Organizational rules, policies, constraints",workflow:"Process flows, state transitions, procedures",architecture:"System design, service interactions, infrastructure",convention:"Coding patterns, naming rules, team standards",decision:"Why choices were made, tradeoffs considered",domain_knowledge:"Domain-specific terminology and concepts",key_insight:"Important takeaways, notable explanations",metric:"Quantitative data, measurements, statistics",issue:"Known problems, bugs, limitations, risks",action_item:"Tasks, follow-ups, assignments, deadlines"},OE=["preference","opinion","personal","experience"],zL=Object.keys(jn).filter(e=>!OE.includes(e)),Hd=jn;import{readFile as IE}from"node:fs/promises";import{join as CE}from"node:path";D();Re();var NE=CE(ie,"input-classifier.md"),RE=3,kE=2e3,LE=["thought","knowledge","noise"];async function Gd(e,{title:t}={}){if(!e?.trim()||e.trim().length<RE)return{route:"noise",facts:[],entities:[],reasoning:"Empty or too short"};if(e.length>kE)return{route:"knowledge",facts:[],entities:[],reasoning:"Long content \u2014 auto-routed to full pipeline"};let n=`${await IE(NE,"utf8")}
|
|
499
|
-
|
|
500
|
-
---
|
|
501
|
-
|
|
502
|
-
Title: ${t||"(none)"}
|
|
503
|
-
Input: ${e}
|
|
504
|
-
|
|
505
|
-
---
|
|
506
|
-
|
|
507
|
-
Respond with ONLY a JSON object: { "route": "thought|knowledge|noise", "facts": [{"content":"...","category":"...","confidence":"high|medium|low","importance":"vital|supplementary"}], "entities": ["..."], "reasoning": "..." }`;try{let o=await Ee(n,{model:y.llm.extractionModel,caller:"classifier"});if(!o||!LE.includes(o.route))return Wd("Invalid classification result");let a=Object.keys(Hd),i=o.route==="thought"&&Array.isArray(o.facts)?o.facts.filter(s=>s.content&&a.includes(s.category)).map(s=>({...s,confidence:["high","medium","low"].includes(s.confidence)?s.confidence:"high",importance:["vital","supplementary"].includes(s.importance)?s.importance:"vital"})):[];return{route:o.route,facts:i,entities:Array.isArray(o.entities)?o.entities:[],reasoning:o.reasoning||""}}catch(o){return console.error("[input-classifier] Failed:",o.message),Wd(o.message)}}function Wd(e){return{route:"knowledge",facts:[],entities:[],reasoning:`Fallback \u2014 ${e}`}}import WE from"node:path";import{readFile as BE}from"node:fs/promises";D();we();P();Ve();D();var DE=.85;async function Yd(e,t,{namespace:r,threshold:n=DE,limit:o=5}){if(!t)return[];let a=V(t),i=`${_e("embedding")} <=> ${xe()}`,{rows:s}=await m.raw(`
|
|
508
|
-
SELECT id, name, entity_type AS "entityType", entity_types AS "entityTypes",
|
|
509
|
-
1 - (${i}) AS similarity
|
|
510
|
-
FROM entity
|
|
511
|
-
WHERE namespace = ?
|
|
512
|
-
AND embedding IS NOT NULL
|
|
513
|
-
AND LOWER(name) != LOWER(?)
|
|
514
|
-
AND merged_with IS NULL
|
|
515
|
-
AND 1 - (${i}) >= ?
|
|
516
|
-
ORDER BY ${i}
|
|
517
|
-
LIMIT ?
|
|
518
|
-
`,[a,r,e,a,n,a,o]);return s.map(c=>{let u;try{u=c.entityTypes?JSON.parse(c.entityTypes):[c.entityType]}catch{u=[c.entityType]}return{...c,types:u}})}async function ta(e,t,r,n){let o=(r.aliases||[]).filter(Boolean),a=o.length?`Existing aliases: ${o.join(", ")}`:"",i=r.similarity>0?`Name-embedding similarity: ${(r.similarity*100).toFixed(0)}%`:"Name-embedding similarity: not directly measured (LLM judging on episode text alone)",s=n?`
|
|
519
|
-
Source passage where the new mention appeared:
|
|
520
|
-
---
|
|
521
|
-
${n.slice(0,1500)}
|
|
522
|
-
---
|
|
523
|
-
`:"",c=`You're deciding whether two entity mentions refer to the same real-world thing, and whether the source passage indicates a RENAME.
|
|
524
|
-
|
|
525
|
-
Mention A (new): "${e}" (type: ${t})
|
|
526
|
-
Mention B (existing): "${r.name}" (types: ${(r.types||[r.entityType]).join(", ")})
|
|
527
|
-
${a}
|
|
528
|
-
${i}
|
|
529
|
-
${s}
|
|
530
|
-
Decision rules:
|
|
531
|
-
- "same" = true when both mentions refer to the same person/product/concept/thing \u2014 including renames, abbreviations ("NYC" / "New York City"), and common-knowledge equivalents.
|
|
532
|
-
- "rename" = true ONLY when "same" is true AND the source passage says one name has replaced the other ("X is now named Y", "X was renamed to Y", "we renamed X to Y", "X used to be called Y", etc.). A normal synonym match is NOT a rename.
|
|
533
|
-
- "current_name" = which of A or B is the new/canonical name per the source passage (the one we want as \`entity.name\` going forward). Only meaningful when "rename" is true. Use the literal string of mention A or B.
|
|
534
|
-
- If you cannot tell, "same" is false. Don't guess.
|
|
535
|
-
|
|
536
|
-
Respond as STRICT JSON, no markdown, no prose:
|
|
537
|
-
{"same": boolean, "rename": boolean, "current_name": "<one of A or B verbatim, or null>", "reason": "one short sentence"}`,u;try{u=await Ze(c,{model:y.llm.entityModel,caller:"entity-matcher"})}catch{return{same:!1,rename:!1,reason:"llm-error"}}let l=PE(u);return l&&typeof l.same=="boolean"?{same:l.same===!0,rename:l.rename===!0&&l.same===!0,currentName:typeof l.current_name=="string"?l.current_name:null,reason:typeof l.reason=="string"?l.reason:""}:{same:/^\s*(yes|true)\b/i.test(u),rename:!1,currentName:null,reason:"fallback-text-match"}}function PE(e){if(typeof e!="string")return null;try{return JSON.parse(e.trim())}catch{}let t=e.match(/\{[\s\S]*\}/);if(t)try{return JSON.parse(t[0])}catch{}return null}async function Br({name:e,entityType:t,description:r,namespace:n,externalId:o,embedding:a,episodeText:i,episodeEntityIds:s=[]}){let c=n||y.defaults.namespace,u=await xt(e,c);if(u)return u=await vt(u.id),await Nr(u.id),u.entityType!==t&&await Et(u.id,t),u;let l=a||await rr(`${t}: ${e}`),p=await Yd(e,l,{namespace:c,limit:3});for(let _ of p){let E=await ta(e,t,_,i);if(E.same)return Kd(_,{newName:e,entityType:t,isRename:E.rename,currentName:E.currentName})}let f=new Set(p.map(_=>_.id)),h=s.filter(_=>_!=null&&!f.has(_));for(let _ of h){let E=await vt(_);if(!E||E.namespace!==c||E.name?.toLowerCase()===e.toLowerCase())continue;let x=await ta(e,t,{...E,types:UE(E),similarity:0},i);if(x.same)return Kd(E,{newName:e,entityType:t,isRename:x.rename,currentName:x.currentName})}try{return await ko({name:e,entityType:t,description:r,namespace:c,externalId:o,embedding:l})}catch(_){if(qd(_)){let E=await xt(e,c);if(E){let x=await vt(E.id);return await Nr(x.id),await Et(x.id,t),x}}throw _}}function qd(e){return e?!!(e.code==="23505"||typeof e.message=="string"&&e.message.includes("duplicate key value violates unique constraint")):!1}async function Kd(e,{newName:t,entityType:r,isRename:n,currentName:o}){let a=await vt(e.id);if(await Nr(a.id),await Et(a.id,r),n&&a.name&&a.name.toLowerCase()!==t.toLowerCase()){let i=t.toLowerCase(),s=a.name.toLowerCase(),c=(o||"").toLowerCase(),u,l;if(c===i?(u=t,l=a.name):c===s?(u=a.name,l=t):(u=t,l=a.name),l&&l.toLowerCase()!==u.toLowerCase()&&(await Sn(a.id,l),a.aliases=[...a.aliases||[],l.toLowerCase()]),u!==a.name)try{await Lo(a.id,u),a.name=u}catch(p){if(qd(p)){let f=await xt(u,a.namespace);if(f&&f.id!==a.id){let{mergeEntities:h}=await Promise.resolve().then(()=>(zd(),Vd));return await h(f.id,a.id),await Sn(f.id,a.name),await vt(f.id)}}throw p}}return a}function UE(e){if(e.entityTypes)try{return JSON.parse(e.entityTypes)}catch{}return[e.entityType]}async function ra(e,{promptPath:t,namespace:r}){if(!e.length)return[];let n=e.map(f=>`- [${f.category}] ${f.content}`).join(`
|
|
538
|
-
`),a=`${await BE(t,"utf8")}
|
|
539
|
-
|
|
540
|
-
---
|
|
541
|
-
|
|
542
|
-
${n}`,i=await Ze(a,{model:y.llm.entityModel,caller:"entity-resolver"}),s=$o(i);if(!Array.isArray(s))return[];let c=s.filter(f=>f.name);if(!c.length)return[];let u=new Array(c.length),l=[],p=[];for(let f=0;f<c.length;f++){let h=await HE(c[f].name,r);h?(u[f]=h,l.push(h.id)):p.push(f)}for(let f of p){let h=c[f],_=await Br({name:h.name,entityType:"topic",description:h.description||null,namespace:r,episodeText:n,episodeEntityIds:l});u[f]=_,_?.id&&l.push(_.id)}return u.filter(Boolean)}async function HE(e,t){let{findByName:r,getCanonicalEntity:n,incrementMentionCount:o}=await Promise.resolve().then(()=>(we(),bl)),a=await r(e,t);if(!a)return null;let i=await n(a.id);return await o(i.id),i}Re();P();var Zd=WE.join(ie,"entity-extraction.md");async function ia(e,t,r,n){let{title:o,sourceType:a,metadata:i={}}=e,s=t.filter(f=>f.action==="ADD"||f.action==="UPDATE"),c=s.map(f=>f.fact||f.existing).filter(Boolean),l=s.find(f=>f.fact)?.fact?.id||null,p=new Date().toISOString().split("T")[0];return n?.items?.length?GE({entityDefs:n,factObjects:c,firstFactId:l,namespace:r,today:p}):YE({title:o,sourceType:a,metadata:i,factObjects:c,firstFactId:l,namespace:r,today:p})}async function GE({entityDefs:e,factObjects:t,firstFactId:r,namespace:n,today:o}){let a={},i=0,s=t.map(f=>f.content).filter(Boolean).join(`
|
|
543
|
-
`),c=[];for(let f of e.items){let h=await Br({name:f.name,entityType:f.type,description:f.description,namespace:n,episodeText:s,episodeEntityIds:c});a[f.name]=h,h?.id&&c.push(h.id)}for(let f of e.relations||[]){let h=a[f.source],_=a[f.target];if(!h||!_)continue;let E=na(t,f.source)||na(t,f.target);await Dn({sourceId:h.id,targetId:_.id,relationType:f.type,sourceFactId:E?.id||r,validAt:o}),i++}let u=await aa(t,n),l=oa(Object.values(a),u),p=0;for(let f of t){let h=l.filter(_=>Bn(f.content,_));h.length&&(await Nn(f.id,h),p+=h.length)}return{entityCount:l.length,relationCount:i,factEntityLinks:p,topics:l.filter(f=>f.entityType==="topic").map(f=>f.name)}}async function YE({title:e,sourceType:t,metadata:r,factObjects:n,firstFactId:o,namespace:a,today:i}){if(!e){let x=n.length?await ra(n,{promptPath:Zd,namespace:a}):[],O=await aa(n,a),N=oa(x,O),F=0;for(let j of n){let k=N.filter(Je=>Bn(j.content,Je));k.length&&(await Nn(j.id,k),F+=k.length)}return{entityCount:N.length,relationCount:0,factEntityLinks:F,topics:x.map(j=>j.name)}}let s=n.map(x=>x.content).filter(Boolean).join(`
|
|
544
|
-
`).slice(0,2e3),c=await Br({name:e,entityType:"document",description:`${t} document: ${e}`,namespace:a,episodeText:s}),u=null;r.author&&(u=await Br({name:r.author,entityType:"person",namespace:a,episodeText:s,episodeEntityIds:c?.id?[c.id]:[]}));let l=n.length?await ra(n,{promptPath:Zd,namespace:a}):[],p=0;u&&(await Dn({sourceId:c.id,targetId:u.id,relationType:"AUTHORED_BY",sourceFactId:o,validAt:i}),p++);for(let x of l){let O=na(n,x.name);await Dn({sourceId:c.id,targetId:x.id,relationType:"COVERS",sourceFactId:O?.id||o,validAt:i}),p++}let f=[c,u,...l].filter(Boolean),h=await aa(n,a),_=oa(f,h),E=0;for(let x of n){let O=_.filter(N=>Bn(x.content,N));O.length&&(await Nn(x.id,O),E+=O.length)}return{entityCount:_.length,relationCount:p,factEntityLinks:E,topics:l.map(x=>x.name)}}function na(e,t){if(!t)return null;let r=t.toLowerCase();return e.find(n=>n.content?.toLowerCase().includes(r))||null}function Bn(e,t){if(!e||!t?.name)return!1;let r=e.toLowerCase();return[t.name.toLowerCase(),...t.aliases||[]].some(o=>o?new RegExp(`\\b${VE(o)}\\b`).test(r):!1)}function VE(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function oa(...e){let t=new Set,r=[];for(let n of e)for(let o of n)!o||t.has(o.id)||(t.add(o.id),r.push(o));return r}async function aa(e,t){if(!e?.length)return[];let r=await m("entity as e").join("pod as p","p.entity_id","e.id").where("p.status","active").where("e.namespace",t).whereNull("e.mergedWith").select("e.id","e.uid","e.name","e.entityType","e.aliases");return r.length?r.filter(n=>e.some(o=>Bn(o.content,n))):[]}qe();Mr();qe();D();async function Jd(e,t){if(!e||typeof e!="object")return[];let r=[],n=t||y.defaults.namespace;if(e.slack?.team_id&&e.connection_id){let o=await Lr({podType:"connector_workspace",externalId:`slack:${e.slack.team_id}`,namespace:n});o&&r.push({podId:o.id,role:"primary"})}if(e.github?.org&&e.connection_id){let o=await Lr({podType:"connector_workspace",externalId:`github:${e.github.org}`,namespace:n});o&&r.push({podId:o.id,role:"primary"})}return r}D();Re();var qE=KE(ie,"default-extraction.md");async function Qd({content:e,title:t,sourcePath:r,sourceType:n="raw",contentType:o,namespace:a,metadata:i={},promptPath:s,categories:c,entities:u,skipFacts:l=!1,skipEntities:p=!1,skipContextualization:f=!1,classify:h=!0,podUids:_=[],resolvePodsFrom:E=null}){let x=a||y.defaults.namespace,O=c||Object.keys(jn),N=s||qE,F=t||r,j=null;if(h&&(process.stderr.write(`[0/6] Classifying input...
|
|
545
|
-
`),j=await Gd(e,{title:F}),process.stderr.write(` Route: ${j.route} \u2014 ${j.reasoning}
|
|
546
|
-
`),j.route==="noise"))return process.stderr.write(` Skipped \u2014 classified as noise.
|
|
547
|
-
`),{documentId:null,title:F,skipped:!0,route:"noise"};process.stderr.write(`[1/6] Checking for changes...
|
|
548
|
-
`);let k=zE("sha256").update(e).digest("hex"),Je=r||`thought:${k}`,{doc:z,changed:Tt}=await Id({sourcePath:Je,sourceType:n,title:F,contentHash:k,namespace:x});if(!Tt)return process.stderr.write(` Skipped \u2014 content unchanged.
|
|
549
|
-
`),{documentId:z.id,title:F,skipped:!0};i&&(Object.keys(i).length||i.connection_id)&&await Rd(z.id,i,i.connection_id??null);let cr=await XE({podUids:_,resolvePodsFrom:E,metadata:i,namespace:x});for(let{podId:Z,role:St}of cr)await Po(Z,z.id,St);process.stderr.write(`[2/6] Parsing content...
|
|
550
|
-
`);let Xe=Md(e,{format:i.format,filePath:r,contentType:o});if(F=t||Xe.metadata?.title||r,j?.route==="thought"&&j.facts.length){process.stderr.write(`[thought] Storing ${j.facts.length} facts directly...
|
|
551
|
-
`);let Z=await ZE(j.facts,{documentId:z.id,namespace:x}),St={entityCount:0,relationCount:0,factEntityLinks:0,topics:[]};return!p&&Z.results.length&&(St=await ia({title:F,sourceType:n,metadata:i},Z.results,x,u)),await Jo(z.id,{chunkCount:0,factCount:Z.counts.added}),await Xd(Z.results,cr),process.stderr.write(`Done. Route: thought, ${Z.counts.total} facts (${Z.counts.added} new)
|
|
552
|
-
`),{documentId:z.id,documentUid:z.uid,title:F,skipped:!1,route:"thought",chunkCount:0,facts:Z.counts,entities:St}}let se=[],be={counts:{total:0,added:0,skipped:0,updated:0,contradicted:0},results:[]},ur={entityCount:0,relationCount:0,factEntityLinks:0,topics:[]};try{process.stderr.write(`[3/6] Chunking and embedding...
|
|
553
|
-
`),se=Fd(Xe.sections),process.stderr.write(` ${se.length} chunks created
|
|
554
|
-
`),!f&&se.length&&(se=await jd(se,Xe.text,{title:F}));let Z=se.map(lr=>{let Ur=lr.contextualPrefix;return Ur?`${Ur}
|
|
555
|
-
${lr.content}`:lr.content}),St=await ze(Z),lf=se.map((lr,Ur)=>({...lr,embedding:St[Ur]}));await Bd(z.id,lf,x),!l&&y.ingest.eagerExtract?(process.stderr.write(`[4/6] Extracting facts...
|
|
556
|
-
`),be=await JE(se,{documentId:z.id,namespace:x,promptPath:N,categories:O})):y.ingest.eagerExtract||process.stderr.write(`[4/6] Skipping fact extraction (SIGIL_EAGER_EXTRACT=false)
|
|
557
|
-
`),await Jo(z.id,{chunkCount:se.length,factCount:be.counts.added+be.counts.updated+be.counts.contradicted}),await Xd(be.results,cr),!p&&be.results.length&&(process.stderr.write(`[5/6] Linking entities...
|
|
558
|
-
`),ur=await ia({title:F,sourceType:n,metadata:i},be.results,x,u),process.stderr.write(` ${ur.entityCount} entities, ${ur.relationCount} relations
|
|
559
|
-
`))}catch(Z){throw console.error(`[pipeline] Failed after document upsert: ${Z.message}`),await Nd(z.id).catch(()=>{}),Z}return process.stderr.write(`Done. ${se.length} chunks, ${be.counts.total} facts, ${ur.entityCount} entities
|
|
560
|
-
`),{documentId:z.id,documentUid:z.uid,title:F,skipped:!1,chunkCount:se.length,facts:be.counts,entities:ur}}async function ef(e,{documentId:t,namespace:r,embeddings:n,defaultConfidence:o="medium",defaultImportance:a="supplementary"}){let i={total:e.length,added:0,skipped:0,updated:0,contradicted:0},s=[];for(let c=0;c<e.length;c++){let u=e[c],l=await $l({content:u.content,category:u.category,confidence:u.confidence||o,importance:u.importance||a,namespace:r,sourceDocumentIds:t?[t]:[],sourceSection:u.sourceSection||u.category,embedding:n[c]});s.push(l);let p=l.action.toLowerCase();p==="add"?i.added++:p==="skip"?i.skipped++:p==="update"?i.updated++:p==="contradict"&&i.contradicted++}return{counts:i,results:s}}async function ZE(e,{documentId:t,namespace:r}){let n=await ze(e.map(o=>o.content));return ef(e,{documentId:t,namespace:r,embeddings:n,defaultConfidence:"high",defaultImportance:"vital"})}async function JE(e,{documentId:t,namespace:r,promptPath:n,categories:o}){let a=await Ud(e,{promptPath:n,categories:o});if(process.stderr.write(` ${a.length} facts extracted from ${e.length} chunks
|
|
561
|
-
`),!a.length)return{counts:{total:0,added:0,skipped:0,updated:0,contradicted:0},results:[]};let i=await ze(a.map(s=>s.content));return ef(a,{documentId:t,namespace:r,embeddings:i})}async function XE({podUids:e,resolvePodsFrom:t,metadata:r,namespace:n}){let o=[];for(let i of e){let s=await bt(i);s&&o.push({podId:s.id,role:"primary"})}if(t==="metadata"){let i=await Jd(r,n);for(let s of i)o.push(s)}let a=new Map;for(let i of o){let s=a.get(i.podId);(!s||i.role==="primary"&&s.role!=="primary")&&a.set(i.podId,i)}return[...a.values()]}async function Xd(e,t){if(!(!t.length||!e.length))for(let r of e){let n=r?.fact?.id??r?.existing?.id;if(!n)continue;let o=r?.action==="SKIP"?"mention":"primary";for(let{podId:a}of t)await Pr(a,n,o)}}import{resolve as av}from"node:path";import{readFile as QE,stat as KD}from"node:fs/promises";import{basename as ev,extname as tv,resolve as rv}from"node:path";async function tf(e){let t=rv(e),r=await QE(t,"utf8"),n=ev(t),o=tv(t).toLowerCase();return{content:r,title:n,sourcePath:t,sourceType:"file",contentType:nv(o),metadata:{filePath:t,fileName:n,extension:o}}}function nv(e){return{".md":"text/markdown",".mdx":"text/markdown",".txt":"text/plain",".html":"text/html",".htm":"text/html",".json":"application/json",".js":"text/javascript",".ts":"text/javascript",".py":"text/x-python"}[e]||"text/plain"}async function rf(e){let t=await fetch(e);if(!t.ok)throw new Error(`Failed to fetch ${e}: ${t.status} ${t.statusText}`);let r=await t.text(),n=t.headers.get("content-type")||"text/plain",o=ov(e);return{content:r,title:o,sourcePath:e,sourceType:"url",contentType:n,metadata:{url:e,fetchedAt:new Date().toISOString()}}}function ov(e){try{let t=new URL(e),n=t.pathname.replace(/\/$/,"").split("/").pop()||t.hostname;return decodeURIComponent(n)}catch{return e}}async function nf({content:e,url:t,filePath:r,title:n,sourceType:o,sourcePath:a,metadata:i}){if(t)return rf(t);if(r){let s=av(r),c=process.cwd();if(!s.startsWith(c))throw new Error(`Path traversal denied: ${r} resolves outside working directory`);return tf(s)}return e?{content:e,title:n||"Untitled",sourcePath:a||`raw/${Date.now()}`,sourceType:o||"raw",contentType:"text/plain",metadata:i||{}}:null}function of(e){e.tool("ingest",`Ingest a document into the Sigil knowledge base. Accepts raw content, a file path, or a URL.
|
|
44
|
+
Returns entity details + relations + key facts (truncated \u2014 use get_fact_context for full text).`,{entityId:y.number().optional().describe("Entity ID (from search_entity or search results)"),name:y.string().optional().describe("Entity name (alternative to ID)"),namespace:y.string().optional().describe("Namespace. Omit for default.")},async({entityId:e,name:r,namespace:a})=>{if(!e&&!r)return O("Error: Provide either entityId or name.");let n=await R("getEntityContext",{entityId:e,name:r,namespace:a});if(n.notFound)return O("Error: Entity not found.");let{entity:o,relations:s,facts:i}=n,f=[`**${o.name}** (${o.entityType}, id:${o.id}, ${o.mentionCount} mentions)`];o.description&&f.push(o.description);let u=s.filter(m=>m.direction==="outgoing"),d=s.filter(m=>m.direction==="incoming");if(u.length){f.push(`
|
|
45
|
+
Outgoing relations (${u.length}):`);for(let m of u.slice(0,15))f.push(`- [${m.relationType}] ${m.name} (${m.entityType}, id:${m.entityId})`);u.length>15&&f.push(` ...and ${u.length-15} more`)}if(d.length){f.push(`
|
|
46
|
+
Incoming relations (${d.length}):`);for(let m of d.slice(0,15))f.push(`- ${m.name} (${m.entityType}, id:${m.entityId}) [${m.relationType}]`);d.length>15&&f.push(` ...and ${d.length-15} more`)}if(i.length){f.push(`
|
|
47
|
+
Key facts (${i.length}):`);for(let m of i){let g=J(m.content,ct);f.push(`- [${m.category}] ${g} _(${m.confidence}, id:${m.id})_`)}}return!u.length&&!d.length&&!i.length&&f.push(`
|
|
48
|
+
No connections or facts found for this entity.`),f.push(`
|
|
49
|
+
_Use traverse_graph(startEntityId=${o.id}) for deeper graph exploration._`),O(f.join(`
|
|
50
|
+
`))})}H();function Xn(t){t.tool("status",`Show Sigil knowledge base statistics \u2014 documents, chunks, facts, entities, relations.
|
|
51
|
+
Use when: checking system health, verifying ingestion, reviewing knowledge graph size.`,{namespace:y.string().optional().describe("Filter by namespace. Omit for global stats.")},async({namespace:e})=>{let r=await R("status",{namespace:e,hotFactsLimit:5}),n=[`Sigil KB${r.namespace?` (${r.namespace})`:""}: ${r.documents} docs, ${r.chunks} chunks, ${r.facts} facts`,`Entities: ${r.entities.documents} documents, ${r.entities.people} people, ${r.entities.topics} topics`,`Relations: ${r.relations}`,`Hot facts (top ${r.hotFacts.length}): ${r.hotFacts.map(o=>`${J(o.content,60)} (${o.accessCount}x)`).join(", ")||"none yet"}`].join(`
|
|
52
|
+
`);return O(n)})}H();function Qn(t){t.tool("ingest",`Ingest a document into the Sigil knowledge base. Accepts raw content, a file path, or a URL.
|
|
562
53
|
Parses the content, chunks it, embeds it, extracts facts, links entities, and stores everything for search.
|
|
563
|
-
Use when: adding documents to the knowledge base, ingesting files, URLs, or raw text.`,{content:
|
|
564
|
-
`);return
|
|
54
|
+
Use when: adding documents to the knowledge base, ingesting files, URLs, or raw text.`,{content:y.string().optional().describe("Raw text content to ingest. Provide this OR filePath OR url."),filePath:y.string().optional().describe("Local file path to ingest. Provide this OR content OR url."),url:y.string().optional().describe("URL to fetch and ingest. Provide this OR content OR filePath."),title:y.string().optional().describe("Document title. Auto-detected if not provided."),namespace:y.string().optional().describe("Namespace for the document. Defaults to config default."),sourceType:y.string().optional().describe("Source type label (e.g., docs, code, notes). Auto-detected from format."),skipFacts:y.boolean().optional().default(!1).describe("Skip fact extraction (faster, chunks only)"),skipEntities:y.boolean().optional().default(!1).describe("Skip entity linking")},async({content:e,filePath:r,url:a,title:n,namespace:o,sourceType:s,skipFacts:i,skipEntities:f})=>{let u=await R("ingestDoc",{content:e,filePath:r,url:a,title:n,namespace:o,sourceType:s,skipFacts:i,skipEntities:f}),d=u.skipped?`Document "${u.title}" already up to date \u2014 skipped.`:[`Document "${u.title}" ingested.`,`- Document ID: ${u.documentId}`,`- Chunks: ${u.chunkCount}`,u.facts?`- Facts: ${u.facts.total} extracted (${u.facts.added} new, ${u.facts.skipped} skipped)`:"- Facts: skipped",u.entities?`- Entities: ${u.entities.entityCount}, Relations: ${u.entities.relationCount}`:"- Entities: skipped",u.output?`- Output: ${u.output}`:""].filter(Boolean).join(`
|
|
55
|
+
`);return O(d)})}H();function eo(t){t.tool("list_pods",`List memory pods (typed containers segregating facts by source or subject).
|
|
565
56
|
Use for: "what sessions do I have?", "list everyone I have a pod for", "which workspaces?".
|
|
566
57
|
Pod types: session (Claude Code), person (people you have a relationship with),
|
|
567
|
-
project, connector_workspace, custom.`,{type:
|
|
568
|
-
`))})}
|
|
58
|
+
project, connector_workspace, custom.`,{type:y.enum(["session","person","project","connector_workspace","custom"]).optional().describe("Filter by pod type. Omit for all types."),namespace:y.string().optional().describe("Namespace. Omit for default."),status:y.enum(["active","archived"]).optional().default("active"),limit:y.number().int().positive().max(100).optional().default(20)},async({type:e,namespace:r,status:a,limit:n})=>{let{pods:o}=await R("listPods",{type:e,namespace:r,status:a,limit:n});if(!o.length){let i=e?` of type "${e}"`:"";return O(`No${i} pods found.`)}let s=[`Found ${o.length} pod${o.length===1?"":"s"}:`,""];for(let i of o){let f=i.memberFactCount??0,u=i.memberDocCount??0,d=i.updatedAt?new Date(i.updatedAt).toISOString().slice(0,16).replace("T"," "):"\u2014";s.push(`- **${i.name}** (${i.podType}, uid:${i.uid})`),s.push(` facts=${f} docs=${u} updated=${d}`)}return s.push(""),s.push("_Use get_pod(uid=...) for member facts and full metadata._"),O(s.join(`
|
|
59
|
+
`))})}H();function to(t){t.tool("get_pod",`Get a memory pod with its member facts, documents, and (for person pods)
|
|
569
60
|
the canonical entity link.
|
|
570
61
|
Use for: "what happened in this session?", "show me everything sigil knows
|
|
571
62
|
about Dhaval", "what's in the Slack workspace pod?".
|
|
572
|
-
Returns pod metadata + up to 20 latest facts + up to 10 latest documents.`,{uid:
|
|
573
|
-
`))})}
|
|
63
|
+
Returns pod metadata + up to 20 latest facts + up to 10 latest documents.`,{uid:y.string().describe("Pod uid (from list_pods or sigil session current)")},async({uid:e})=>{let r=await R("getPod",{uid:e});if(r.notFound)return O(`Error: pod ${e} not found.`);let{pod:a,facts:n,documents:o}=r,s=[`**${a.name}** (${a.podType}, uid:${a.uid})`,"",`- namespace: ${a.namespace}`,`- status: ${a.status}`];a.startedAt&&s.push(`- started_at: ${a.startedAt}`),a.endedAt&&s.push(`- ended_at: ${a.endedAt}`),a.entityId&&s.push(`- entity_id: ${a.entityId}`),a.connectionId&&s.push(`- connection_id: ${a.connectionId}`),a.externalId&&s.push(`- external_id: ${a.externalId}`);let i=Object.entries(a.attrs||{}).filter(([,f])=>f!=null&&f!=="");if(i.length){s.push("","Attrs:");for(let[f,u]of i){let d=typeof u=="object"?JSON.stringify(u):u;s.push(`- ${f}: ${d}`)}}if(n.length){s.push("",`Member facts (${n.length}, up to 20):`);for(let f of n){let u=J(f.content,ct),d=f.podRole==="mention"?" _[mention]_":"";s.push(`- ${u} (id:${f.id})${d}`)}}if(o.length){s.push("",`Member documents (${o.length}, up to 10):`);for(let f of o){let u=f.title||f.sourcePath||`doc-${f.id}`;s.push(`- ${J(u,80)} (id:${f.id})`)}}return!n.length&&!o.length&&s.push("","_Pod has no member facts or documents yet._"),O(s.join(`
|
|
64
|
+
`))})}process.env.SIGIL_AGENT||(process.env.SIGIL_AGENT="mcp");function _d(){let t=new yd({name:"sigil",version:"0.2.0"});return Hn(t),qn(t),Kn(t),Yn(t),Jn(t),to(t),eo(t),Xn(t),Qn(t),t}async function ro(){let t=_d(),e=new xd;await t.connect(e);let{closeDaemonConnection:r}=await Promise.resolve().then(()=>(H(),Wn)),a=()=>{r().catch(()=>{})};return process.on("SIGTERM",a),process.on("SIGINT",a),process.on("beforeExit",a),t}var Td=ao(ao(bd(import.meta.url))),kd=process.env.DOTENV_CONFIG_PATH||(wd(cr(process.cwd(),".env"))?cr(process.cwd(),".env"):null)||cr(Td,".env");vd({path:kd,quiet:!0});await ro();
|