@anmol-srv/sigil 0.10.3
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 +15 -0
- package/README.md +417 -0
- package/dist/cli.js +1019 -0
- package/dist/hooks/post-tool-use.js +70 -0
- package/dist/hooks/session-end.js +222 -0
- package/dist/hooks/stop.js +259 -0
- package/dist/hooks/user-prompt-submit.js +279 -0
- package/dist/server.js +573 -0
- package/integrations/hermes/README.md +41 -0
- package/integrations/hermes/plugin/README.md +72 -0
- package/integrations/hermes/plugin/__init__.py +353 -0
- package/integrations/hermes/plugin/plugin.yaml +10 -0
- package/knexfile.js +15 -0
- package/package.json +100 -0
- package/prompts/audm-decision.md +31 -0
- package/prompts/chunk-context.md +23 -0
- package/prompts/default-extraction.md +35 -0
- package/prompts/entity-extraction.md +37 -0
- package/prompts/input-classifier.md +23 -0
- package/prompts/query-router.md +18 -0
- package/src/db/migrations/20260310120000_create-cortex-document-table.cjs +21 -0
- package/src/db/migrations/20260310120001_create-cortex-chunk-table.cjs +37 -0
- package/src/db/migrations/20260310120002_create-cortex-fact-table.cjs +37 -0
- package/src/db/migrations/20260310120003_create-cortex-entity-table.cjs +26 -0
- package/src/db/migrations/20260310120004_create-cortex-relation-table.cjs +27 -0
- package/src/db/migrations/20260310120005_create-cortex-history-table.cjs +16 -0
- package/src/db/migrations/20260311120000_add-entity-namespace-and-relation-indexes.cjs +32 -0
- package/src/db/migrations/20260312120000_add-fact-entity-linking.cjs +22 -0
- package/src/db/migrations/20260313093130_create-api-key-table.cjs +15 -0
- package/src/db/migrations/20260313120000_add-entity-dedup-support.cjs +13 -0
- package/src/db/migrations/20260313150000_create-connector-tables.cjs +46 -0
- package/src/db/migrations/20260318120000_add-contextual-chunk-prefix.cjs +11 -0
- package/src/db/migrations/20260318120001_add-fact-temporal-validity.cjs +15 -0
- package/src/db/migrations/20260318120002_add-fact-importance.cjs +11 -0
- package/src/db/migrations/20260318120003_add-fact-access-tracking.cjs +13 -0
- package/src/db/migrations/20260405120000_add-unique-constraints.cjs +58 -0
- package/src/db/migrations/20260405140000_create-llm-log-table.cjs +21 -0
- package/src/db/migrations/20260424120000_split-fact-lifecycle.cjs +86 -0
- package/src/db/migrations/20260424120002_create-embedding-cache.cjs +26 -0
- package/src/db/migrations/20260429120000_halfvec-index-compression.cjs +34 -0
- package/src/db/migrations/20260429120100_create-hebbian-edge-table.cjs +37 -0
- package/src/db/migrations/20260429120200_upgrade-embedding-dim-1024.cjs +68 -0
- package/src/db/migrations/20260504120000_scope-document-source-path-uniqueness.cjs +45 -0
- package/src/db/migrations/20260508001733_add-entity-aliases.cjs +42 -0
- package/src/db/migrations/20260512120000_create-entity-hebbian-edge.cjs +42 -0
- package/src/db/migrations/20260512120000_create-pod-tables.cjs +71 -0
- package/src/db/migrations/20260512120100_create-pod-membership.cjs +50 -0
- package/src/db/migrations/20260512120200_add-document-source-metadata.cjs +32 -0
- package/src/db/migrations/20260514023428_rewrite-session-pods-and-add-fact-attribution-columns.cjs +86 -0
package/dist/server.js
ADDED
|
@@ -0,0 +1,573 @@
|
|
|
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
|
+
PGlite was deprecated; existing PGlite data at ~/.sigil/db is preserved but unreachable from this version.
|
|
4
|
+
Set SIGIL_DB_TYPE=postgres in ~/.sigil/.env and configure SIGIL_DB_HOST / PORT / NAME / USER / PASSWORD.
|
|
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.
|
|
338
|
+
Automatically detects entity names and returns entity-centric results.
|
|
339
|
+
Use for: "how does X work", "what is Y?", "what are the rules for Z", domain knowledge, decisions.
|
|
340
|
+
Returns compact facts. Use get_fact_context(factId) for full detail on any fact.
|
|
341
|
+
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:T.string().describe("Natural language search query"),limit:T.number().optional().default(5).describe("Max facts to return (default 5)"),namespaces:T.array(T.string()).optional().describe("Filter by namespaces"),minConfidence:T.enum(["low","medium","high"]).optional().default("medium").describe("Minimum fact confidence"),includeChunks:T.boolean().optional().default(!1).describe("Include raw document chunks (verbose \u2014 only when needed)"),useGraph:T.boolean().optional().default(!1).describe("Traverse entity graph for additional related facts"),pointInTime:T.string().optional().describe("ISO timestamp \u2014 return only facts valid at this point in time"),format:T.enum(["full","compact"]).optional().default("full").describe('Output format: "full" (default) or "compact" (token-efficient, one line per category)'),podScope:T.union([T.literal("auto"),T.literal("global"),T.array(T.string())]).optional().describe('Pod scope: "auto" (uses active session/project/person pods), "global" (no filter), or list of pod uids/names. Default: "global".')},async({query:t,limit:r,namespaces:n,minConfidence:o,includeChunks:a,useGraph:i,pointInTime:s,format:c,podScope:u})=>{let l=n?.length?n:[y.defaults.namespace],p=s?new Date(s):void 0,{facts:f,chunks:h,matchedEntity:_,relatedEntities:E}=await _d(t,{namespaces:l,limit:r,minConfidence:o,includeChunks:a,useGraph:i,pointInTime:p,podScope:u??null,route:!1,synthesize:!1});if(c==="compact")return L(Jw(f,_));let x=[];if(_&&(x.push(`**Matched entity:** ${_.name} (${_.type}, id:${_.id}, ${_.mentions} mentions)`),_.description&&x.push(_.description),x.push("")),f.length){x.push(`**Facts (${f.length}):**`);for(let O of f){let N=ve(O.content,sr),F=O.importance==="vital"?" **[VITAL]**":"";x.push(`- [${O.category}] ${N}${F} _(${O.confidence}, id:${O.id})_`)}}if(E.length){x.push(""),x.push(`**Related entities (${E.length}):**`);for(let O of E.slice(0,10))x.push(`- ${O.name} (${O.type}) [${O.relation}] id:${O.id}`)}if(a&&h.length){x.push(""),x.push(`**Chunks (${h.length}):**`);for(let O of h.slice(0,3)){let N=O.sectionHeading?`[${O.sectionHeading}] `:"";x.push(`---
|
|
343
|
+
${N}${ve(O.content,500)}`)}}return!f.length&&!h.length&&x.push("No results found. Try broader terms or use search_entity to find entity names."),_&&x.push(`
|
|
344
|
+
_Drill down: get_entity_context(entityId=${_.id}) for full details about ${_.name}_`),L(x.join(`
|
|
345
|
+
`))})}function Jw(e,t){let r=[];if(t&&r.push(`> ${t.name} (${t.type})`),!e.length)return r.push("No results."),r.join(`
|
|
346
|
+
`);let n=gt(e,"category");for(let[o,a]of Object.entries(n)){let s=Ar(a,c=>c.importance==="vital"?0:1).map(c=>c.content);r.push(`[${o}]: ${s.join(". ")}`)}return r.join(`
|
|
347
|
+
`)}we();function vd(e){e.tool("search_entity",`Find entities in the knowledge graph by name or type.
|
|
348
|
+
Use for: "find Alice", "list all topics", "show all people", "find documents about normalization".
|
|
349
|
+
Entity types: document, person, topic (extensible per domain).
|
|
350
|
+
Returns compact entity list. Use get_entity_context(entityId) for full details.`,{query:T.string().optional().describe('Entity name to search (e.g. "Alice", "Cohort 6")'),entityType:T.string().optional().describe("Filter by type: session, course, person, topic"),limit:T.number().optional().default(10).describe("Max results"),namespace:T.string().optional().describe("Namespace. Omit for default.")},async({query:t,entityType:r,limit:n,namespace:o})=>{if(!t&&!r)return L("Error: Provide either a query (entity name) or entityType.");let a=t?await wt(t,{entityType:r,namespace:o,limit:n}):await Do(r,{namespace:o,limit:n});if(!a.length){let c=t?`matching "${t}"`:`of type "${r}"`;return L(`No entities found ${c}.`)}let i=a.map(c=>{let u=c.description?` \u2014 ${c.description}`:"";return`- **${c.name}** (${c.entityType}, id:${c.id}, ${c.mentionCount} mentions)${u}`}),s=t?`Entities matching "${t}"`:`${r} entities`;return L(`${s} (${a.length}):
|
|
351
|
+
${i.join(`
|
|
352
|
+
`)}
|
|
353
|
+
|
|
354
|
+
_Use get_entity_context(entityId=<id>) for details or traverse_graph(startEntityId=<id>) for connections._`)})}er();we();P();we();async function Zo(e,{maxDepth:t=2,relationType:r,limit:n=30}={}){let o=Math.min(Math.max(t,1),6),a=[e,e],i=r?"AND r.relation_type = ?":"";r&&a.push(r);let s=r?"AND r.relation_type = ?":"";r&&a.push(r),a.push(o,n);let{rows:c}=await m.raw(`
|
|
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.
|
|
411
|
+
Use for: "who did Alice mentor?", "what topics does course X cover?", "how is A related to B?",
|
|
412
|
+
"what documents cover this topic?", "show mentorship chain".
|
|
413
|
+
Relation types: PART_OF, LED_BY, MENTORED, COVERS, FOLLOWS.`,{startEntityId:T.number().describe("Starting entity ID (from search_entity results)"),action:T.enum(["neighbors","path","related"]).optional().default("neighbors").describe("neighbors = direct connections, path = shortest path to target, related = all reachable"),targetEntityId:T.number().optional().describe('Target entity ID (required for "path" action)'),relationType:T.string().optional().describe("Filter: PART_OF, LED_BY, MENTORED, COVERS, FOLLOWS"),maxDepth:T.number().optional().default(2).describe("Traversal depth 1-3"),limit:T.number().optional().default(20).describe("Max results")},async({startEntityId:t,action:r,targetEntityId:n,relationType:o,maxDepth:a,limit:i})=>{let s=await q(t);if(!s)return L(`Error: Entity ID ${t} not found.`);let c=`${s.name} (${s.entityType}, id:${s.id})`;return r==="path"?n?Qw(c,s,n,{maxDepth:Math.min(a,4)}):L('Error: targetEntityId is required for "path" action.'):r==="related"?eE(c,s,{maxDepth:Math.min(a,3),relationType:o,limit:i}):Xw(c,s,{depth:Math.min(a,3),limit:i})})}async function Xw(e,t,r){let n=await bd(t.id,r);if(n.related){let s=n.related.map(c=>`- [${c.relationType}] ${c.name} (${c.entityType}, id:${c.entityId||c.id}) depth:${c.depth}`);return L(`${e}
|
|
414
|
+
Connections (${n.related.length}):
|
|
415
|
+
${s.join(`
|
|
416
|
+
`)}`)}if(!n.relations?.length)return L(`${e}
|
|
417
|
+
No connections found.`);let o=n.relations.filter(s=>s.direction==="outgoing"),a=n.relations.filter(s=>s.direction==="incoming"),i=[e];if(o.length){i.push(`
|
|
418
|
+
Outgoing (${o.length}):`);for(let s of o)i.push(`- [${s.relationType}] ${s.name} (${s.entityType}, id:${s.entityId})`)}if(a.length){i.push(`
|
|
419
|
+
Incoming (${a.length}):`);for(let s of a)i.push(`- ${s.name} (${s.entityType}, id:${s.entityId}) [${s.relationType}]`)}return L(i.join(`
|
|
420
|
+
`))}async function Qw(e,t,r,n){let o=await Td(t.id,r,n);if(!o)return L(`No path found from ${t.name} to entity ${r}.`);let a=o.path.map((i,s)=>{let c=s<o.relationTypes.length?` --[${o.relationTypes[s]}]--> `:"";return`${i.name} (${i.entityType})${c}`});return L(`Path (${o.depth} hops):
|
|
421
|
+
${a.join("")}`)}async function eE(e,t,r){let n=await Zo(t.id,r);if(!n.length)return L(`${t.name} has no related entities within ${r.maxDepth} hops.`);let o=gt(n,"depth"),a=[`Entities related to ${e} (${n.length}):`];for(let i of Object.keys(o).sort()){let s=i==="1"?"Direct":`${i} hops`;a.push(`
|
|
422
|
+
${s}:`);for(let c of o[i])a.push(`- [${c.relationType}] ${c.name} (${c.entityType}, id:${c.entityId})`)}return L(a.join(`
|
|
423
|
+
`))}P();function Ad(e){e.tool("get_fact_context",`Get full context for a specific fact: complete content, entities mentioned, relations created, sources.
|
|
424
|
+
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:T.number().optional().describe("Fact ID (from search results)"),uid:T.string().optional().describe('Fact UID (e.g. "fact-a1b2c3d4")')},async({uid:t,factId:r})=>{if(!t&&!r)return L("Error: Provide either factId or uid.");let n;if(t?n=await Ml(t):n=await m("fact").where({id:r}).first(),!n)return L("Error: Fact not found.");let[o,a,i]=await Promise.all([Al(n.id),Wl(n.id),n.sourceDocumentIds?.length?m("document").whereIn("id",n.sourceDocumentIds).select("id","title","sourceType"):[]]),s=[`**Fact ${n.uid}** (${n.category}, ${n.confidence}, ${n.status})`,n.content];if(n.sourceSection&&s.push(`Source section: ${n.sourceSection}`),o.length&&s.push(`
|
|
426
|
+
Entities mentioned: ${o.map(c=>`${c.name} (${c.entityType}, id:${c.id})`).join(", ")}`),a.length){s.push(`
|
|
427
|
+
Relations from this fact:`);for(let c of a)s.push(`- ${c.sourceName} --[${c.relationType}]--> ${c.targetName}`)}return i.length&&s.push(`
|
|
428
|
+
Sources: ${i.map(c=>`${c.title} (${c.sourceType})`).join(", ")}`),L(s.join(`
|
|
429
|
+
`))})}we();function Od(e){e.tool("get_entity_context",`Get full context for an entity: relations, connected facts, graph position.
|
|
430
|
+
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:T.number().optional().describe("Entity ID (from search_entity or search results)"),name:T.string().optional().describe("Entity name (alternative to ID)"),namespace:T.string().optional().describe("Namespace. Omit for default.")},async({entityId:t,name:r,namespace:n})=>{if(!t&&!r)return L("Error: Provide either entityId or name.");let o;if(t?o=await q(t):o=(await wt(r,{namespace:n,limit:1}))[0],!o)return L("Error: Entity not found.");let[a,i]=await Promise.all([or(o.id,{limit:30}),Rn(o.id,{limit:10})]),s=[`**${o.name}** (${o.entityType}, id:${o.id}, ${o.mentionCount} mentions)`];o.description&&s.push(o.description);let c=a.filter(l=>l.direction==="outgoing"),u=a.filter(l=>l.direction==="incoming");if(c.length){s.push(`
|
|
432
|
+
Outgoing relations (${c.length}):`);for(let l of c.slice(0,15))s.push(`- [${l.relationType}] ${l.name} (${l.entityType}, id:${l.entityId})`);c.length>15&&s.push(` ...and ${c.length-15} more`)}if(u.length){s.push(`
|
|
433
|
+
Incoming relations (${u.length}):`);for(let l of u.slice(0,15))s.push(`- ${l.name} (${l.entityType}, id:${l.entityId}) [${l.relationType}]`);u.length>15&&s.push(` ...and ${u.length-15} more`)}if(i.length){s.push(`
|
|
434
|
+
Key facts (${i.length}):`);for(let l of i){let p=ve(l.content,sr);s.push(`- [${l.category}] ${p} _(${l.confidence}, id:${l.id})_`)}}return!c.length&&!u.length&&!i.length&&s.push(`
|
|
435
|
+
No connections or facts found for this entity.`),s.push(`
|
|
436
|
+
_Use traverse_graph(startEntityId=${o.id}) for deeper graph exploration._`),L(s.join(`
|
|
437
|
+
`))})}Cr();P();async function Id({sourcePath:e,sourceType:t,title:r=null,contentHash:n,namespace:o}){let a=`doc-${Ke(16)}`,{rows:[i]}=await m.raw(`
|
|
438
|
+
INSERT INTO document (uid, source_path, source_type, title, content_hash, namespace, last_ingested_at, created_at, updated_at)
|
|
439
|
+
VALUES (?, ?, ?, ?, ?, ?, NOW(), NOW(), NOW())
|
|
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.
|
|
562
|
+
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:T.string().optional().describe("Raw text content to ingest. Provide this OR filePath OR url."),filePath:T.string().optional().describe("Local file path to ingest. Provide this OR content OR url."),url:T.string().optional().describe("URL to fetch and ingest. Provide this OR content OR filePath."),title:T.string().optional().describe("Document title. Auto-detected if not provided."),namespace:T.string().optional().describe("Namespace for the document. Defaults to config default."),sourceType:T.string().optional().describe("Source type label (e.g., docs, code, notes). Auto-detected from format."),skipFacts:T.boolean().optional().default(!1).describe("Skip fact extraction (faster, chunks only)"),skipEntities:T.boolean().optional().default(!1).describe("Skip entity linking")},async({content:t,filePath:r,url:n,title:o,namespace:a,sourceType:i,skipFacts:s,skipEntities:c})=>{let u=await nf({content:t,filePath:r,url:n,title:o,sourceType:i});if(!u)return L("Error: provide content, filePath, or url.");let l=await Qd({content:u.content,title:o||u.title,sourcePath:u.sourcePath,sourceType:i||u.sourceType,contentType:u.contentType,namespace:a,metadata:u.metadata,skipFacts:s,skipEntities:c}),p=l.skipped?`Document "${l.title}" already up to date \u2014 skipped.`:[`Document "${l.title}" ingested.`,`- Document ID: ${l.documentId}`,`- Chunks: ${l.chunkCount}`,l.facts?`- Facts: ${l.facts.total} extracted (${l.facts.added} new, ${l.facts.skipped} skipped)`:"- Facts: skipped",l.entities?`- Entities: ${l.entities.entityCount}, Relations: ${l.entities.relationCount}`:"- Entities: skipped",l.md?`- Output: ${l.md.url}`:""].filter(Boolean).join(`
|
|
564
|
+
`);return L(p)})}qe();function af(e){e.tool("list_pods",`List memory pods (typed containers segregating facts by source or subject).
|
|
565
|
+
Use for: "what sessions do I have?", "list everyone I have a pod for", "which workspaces?".
|
|
566
|
+
Pod types: session (Claude Code), person (people you have a relationship with),
|
|
567
|
+
project, connector_workspace, custom.`,{type:T.enum(["session","person","project","connector_workspace","custom"]).optional().describe("Filter by pod type. Omit for all types."),namespace:T.string().optional().describe("Namespace. Omit for default."),status:T.enum(["active","archived"]).optional().default("active"),limit:T.number().int().positive().max(100).optional().default(20)},async({type:t,namespace:r,status:n,limit:o})=>{let a=await Tl({podType:t,namespace:r,status:n,limit:o});if(!a.length){let s=t?` of type "${t}"`:"";return L(`No${s} pods found.`)}let i=[`Found ${a.length} pod${a.length===1?"":"s"}:`,""];for(let s of a){let c=s.memberFactCount??0,u=s.memberDocCount??0,l=s.updatedAt?new Date(s.updatedAt).toISOString().slice(0,16).replace("T"," "):"\u2014";i.push(`- **${s.name}** (${s.podType}, uid:${s.uid})`),i.push(` facts=${c} docs=${u} updated=${l}`)}return i.push(""),i.push("_Use get_pod(uid=...) for member facts and full metadata._"),L(i.join(`
|
|
568
|
+
`))})}qe();Mr();function sf(e){e.tool("get_pod",`Get a memory pod with its member facts, documents, and (for person pods)
|
|
569
|
+
the canonical entity link.
|
|
570
|
+
Use for: "what happened in this session?", "show me everything sigil knows
|
|
571
|
+
about Dhaval", "what's in the Slack workspace pod?".
|
|
572
|
+
Returns pod metadata + up to 20 latest facts + up to 10 latest documents.`,{uid:T.string().describe("Pod uid (from list_pods or sigil session current)")},async({uid:t})=>{let r=await bt(t);if(!r)return L(`Error: pod ${t} not found.`);let n=typeof r.attrs=="object"?r.attrs:iv(r.attrs),[o,a]=await Promise.all([Cn(r.id,{memberType:"fact",limit:20}),Cn(r.id,{memberType:"document",limit:10})]),i=[`**${r.name}** (${r.podType}, uid:${r.uid})`,"",`- namespace: ${r.namespace}`,`- status: ${r.status}`];r.startedAt&&i.push(`- started_at: ${r.startedAt}`),r.endedAt&&i.push(`- ended_at: ${r.endedAt}`),r.entityId&&i.push(`- entity_id: ${r.entityId}`),r.connectionId&&i.push(`- connection_id: ${r.connectionId}`),r.externalId&&i.push(`- external_id: ${r.externalId}`);let s=Object.entries(n).filter(([,c])=>c!=null&&c!=="");if(s.length){i.push("","Attrs:");for(let[c,u]of s){let l=typeof u=="object"?JSON.stringify(u):u;i.push(`- ${c}: ${l}`)}}if(o.length){i.push("",`Member facts (${o.length}, up to 20):`);for(let c of o){let u=ve(c.content,sr),l=c.podRole==="mention"?" _[mention]_":"";i.push(`- ${u} (id:${c.id})${l}`)}}if(a.length){i.push("",`Member documents (${a.length}, up to 10):`);for(let c of a){let u=c.title||c.sourcePath||`doc-${c.id}`;i.push(`- ${ve(u,80)} (id:${c.id})`)}}return!o.length&&!a.length&&i.push("","_Pod has no member facts or documents yet._"),L(i.join(`
|
|
573
|
+
`))})}function iv(e){if(!e)return{};try{return JSON.parse(e)}catch{return{}}}function uv(){let e=new sv({name:"sigil",version:"0.2.0"});return Ed(e),vd(e),Sd(e),Ad(e),Od(e),sf(e),af(e),kd(e),of(e),e}async function cf(){let e=uv(),t=new cv;return await e.connect(t),e}var pv=uf(uf(dv(import.meta.url))),mv=process.env.DOTENV_CONFIG_PATH||(fv(sa(process.cwd(),".env"))?sa(process.cwd(),".env"):null)||sa(pv,".env");lv({path:mv,quiet:!0});await cf();
|