@rizom/brain 0.2.0-alpha.495 → 0.2.0-alpha.496
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/dist/brain.js +222 -222
- package/dist/chunks/{app-1p9yf7n6.js → app-ygmc0bkd.js} +2 -2
- package/dist/chunks/{blog-post-adapter-ymh1dn8t.js → blog-post-adapter-aqek4r23.js} +2 -2
- package/dist/chunks/{index-390n8ge8.js → index-1af7q36h.js} +3 -3
- package/dist/chunks/{index-jp81rj6x.js → index-4jdfvr30.js} +2 -2
- package/dist/chunks/{index-y0wh3bnp.js → index-5bq8yawt.js} +3 -3
- package/dist/chunks/{index-y0wh3bnp.js.map → index-5bq8yawt.js.map} +3 -3
- package/dist/chunks/{index-sq9ptpvr.js → index-6crtt8mr.js} +2 -2
- package/dist/chunks/{index-a5na8p4p.js → index-r6a0hpn8.js} +3 -3
- package/dist/chunks/{index-a5na8p4p.js.map → index-r6a0hpn8.js.map} +1 -1
- package/dist/chunks/{index-c36br3r2.js → index-wqq0pdyw.js} +2 -2
- package/dist/chunks/linkedin-template-6m1rc1a6.js +5 -0
- package/dist/chunks/{rss-datasource-j65pv9gj.js → rss-datasource-75h1bpzq.js} +2 -2
- package/dist/entities.js +1 -1
- package/dist/index.js +1 -1
- package/dist/interfaces.js +1 -1
- package/dist/model.js +42 -42
- package/dist/model.js.map +1 -1
- package/dist/plugins.js +1 -1
- package/dist/services.js +1 -1
- package/package.json +1 -1
- package/dist/chunks/linkedin-template-2dcckpkt.js +0 -5
- /package/dist/chunks/{app-1p9yf7n6.js.map → app-ygmc0bkd.js.map} +0 -0
- /package/dist/chunks/{blog-post-adapter-ymh1dn8t.js.map → blog-post-adapter-aqek4r23.js.map} +0 -0
- /package/dist/chunks/{index-390n8ge8.js.map → index-1af7q36h.js.map} +0 -0
- /package/dist/chunks/{index-jp81rj6x.js.map → index-4jdfvr30.js.map} +0 -0
- /package/dist/chunks/{index-sq9ptpvr.js.map → index-6crtt8mr.js.map} +0 -0
- /package/dist/chunks/{index-c36br3r2.js.map → index-wqq0pdyw.js.map} +0 -0
- /package/dist/chunks/{linkedin-template-2dcckpkt.js.map → linkedin-template-6m1rc1a6.js.map} +0 -0
- /package/dist/chunks/{rss-datasource-j65pv9gj.js.map → rss-datasource-75h1bpzq.js.map} +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{na as a,oa as b,pa as c,qa as d}from"./index-
|
|
2
|
+
import{na as a,oa as b,pa as c,qa as d}from"./index-1af7q36h.js";import"./index-wj8m4xjr.js";import"./index-d86pb7vs.js";import"./index-5bq8yawt.js";import"./index-pzx4w8bw.js";import"./index-9zvbczej.js";import"./index-q9w9db40.js";import"./index-btvt6ajr.js";export{d as App,a as STARTUP_CHECK_API_KEY,c as buildShellConfig,b as toAppConfig};
|
|
3
3
|
|
|
4
4
|
//# debugId=DB9A66FEC845134064756E2164756E21
|
|
5
|
-
//# sourceMappingURL=app-
|
|
5
|
+
//# sourceMappingURL=app-ygmc0bkd.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{B as a,C as b}from"./index-
|
|
2
|
+
import{B as a,C as b}from"./index-6crtt8mr.js";import"./index-wqq0pdyw.js";import"./index-5bq8yawt.js";import"./index-pzx4w8bw.js";import"./index-9zvbczej.js";import"./index-q9w9db40.js";import"./index-btvt6ajr.js";export{a as BlogPostAdapter,b as blogPostAdapter};
|
|
3
3
|
|
|
4
4
|
//# debugId=55FD0F31AC84592664756E2164756E21
|
|
5
|
-
//# sourceMappingURL=blog-post-adapter-
|
|
5
|
+
//# sourceMappingURL=blog-post-adapter-aqek4r23.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ra as VR,sa as oE,ta as iE}from"./index-wj8m4xjr.js";import{ua as wp}from"./index-d86pb7vs.js";import{$a as sT,$j as se,$l as wT,$n as JT,$p as YT,Aa as nr,Ak as NT,An as QC,Ca as Bn,Cn as LT,Dn as $T,Ea as oT,Kd as Zw,Lm as h0,Ma as iT,Mm as y0,Mo as CI,Nm as v0,No as kI,Np as rI,Ob as bI,Oo as ua,Op as yT,Pl as mC,Qa as Fd,Qg as Xe,Ql as gC,Qn as FT,Ra as ks,Rb as ZC,Rp as nI,Sa as Qx,Sb as gI,Sm as Bs,Sn as BT,Sp as vT,Ta as Yx,Tb as Zx,Tm as JI,Tn as Do,Tp as QT,Ul as fa,Um as Gx,Un as SI,Up as bT,Va as Xx,Wa as r0,Xa as gr,Xd as et,Xl as m0,Xn as ol,Yl as g0,Ym as e0,Yn as GT,Yo as ZT,Zk as el,Zl as Us,_a as eT,_l as ST,_n as YC,_o as KT,am as xT,ao as HT,bb as _n,bh as Yr,bl as bC,bm as TT,bo as WT,bp as Ax,cb as Sn,db as n0,dl as eI,dm as GC,eb as o0,em as JC,fb as i0,fl as tI,fm as HC,gb as a0,gk as Rx,gl as YI,gn as jp,hb as s0,hl as wI,hm as ct,hn as pa,ib as l0,ig as Pr,in as _I,jb as c0,jl as wC,jn as KC,kb as u0,ke as mI,kg as OT,kl as DT,kn as Fx,lb as d0,ln as qT,mb as ca,ml as Qr,nb as OI,nk as bs,nm as kx,nn as dI,ob as SC,ok as Ad,on as Kd,pk as fn,qb as Wt,qk as Kw,rb as Vs,rk as Hx,sb as Qd,sn as fI,tb as oC,to as AI,ub as cC,wg as ot,xa as Bd,za as nT,zb as Zs,zl as Or}from"./index-
|
|
2
|
+
import{ra as VR,sa as oE,ta as iE}from"./index-wj8m4xjr.js";import{ua as wp}from"./index-d86pb7vs.js";import{$a as sT,$j as se,$l as wT,$n as JT,$p as YT,Aa as nr,Ak as NT,An as QC,Ca as Bn,Cn as LT,Dn as $T,Ea as oT,Kd as Zw,Lm as h0,Ma as iT,Mm as y0,Mo as CI,Nm as v0,No as kI,Np as rI,Ob as bI,Oo as ua,Op as yT,Pl as mC,Qa as Fd,Qg as Xe,Ql as gC,Qn as FT,Ra as ks,Rb as ZC,Rp as nI,Sa as Qx,Sb as gI,Sm as Bs,Sn as BT,Sp as vT,Ta as Yx,Tb as Zx,Tm as JI,Tn as Do,Tp as QT,Ul as fa,Um as Gx,Un as SI,Up as bT,Va as Xx,Wa as r0,Xa as gr,Xd as et,Xl as m0,Xn as ol,Yl as g0,Ym as e0,Yn as GT,Yo as ZT,Zk as el,Zl as Us,_a as eT,_l as ST,_n as YC,_o as KT,am as xT,ao as HT,bb as _n,bh as Yr,bl as bC,bm as TT,bo as WT,bp as Ax,cb as Sn,db as n0,dl as eI,dm as GC,eb as o0,em as JC,fb as i0,fl as tI,fm as HC,gb as a0,gk as Rx,gl as YI,gn as jp,hb as s0,hl as wI,hm as ct,hn as pa,ib as l0,ig as Pr,in as _I,jb as c0,jl as wC,jn as KC,kb as u0,ke as mI,kg as OT,kl as DT,kn as Fx,lb as d0,ln as qT,mb as ca,ml as Qr,nb as OI,nk as bs,nm as kx,nn as dI,ob as SC,ok as Ad,on as Kd,pk as fn,qb as Wt,qk as Kw,rb as Vs,rk as Hx,sb as Qd,sn as fI,tb as oC,to as AI,ub as cC,wg as ot,xa as Bd,za as nT,zb as Zs,zl as Or}from"./index-5bq8yawt.js";import{bq as xs,dq as FC,eq as Ss,fq as lx,gq as ws,hq as cx,iq as VT,mq as bn,qq as Xr}from"./index-pzx4w8bw.js";import{rq as qt,sq as fr}from"./index-9zvbczej.js";import{Aq as fp,Cq as na,Cr as mT,Er as gT,Fr as fT,Gs as EI,Hr as hT,Ir as Nx,Js as VC,Ks as Zd,Lr as vs,Nr as Lx,Pr as $x,Ps as RT,Xr as hn,_r as Qn,as as Ce,bs as Xi,ds as qx,et as zT,jt as GI,ks as js,kt as _s,lt as UT,mr as gt,or as as,qs as tp,rr as Ox,rs as uI,sr as Px,ss as $C,uq as Xm,vq as eg,wq as r,xr as sx}from"./index-q9w9db40.js";import{qt as Mn,rt as ye,tt as zl}from"./index-btvt6ajr.js";var Dl=ye(function(AW,xg){var{defineProperty:Nl,getOwnPropertyDescriptor:$R,getOwnPropertyNames:FR}=Object,BR=Object.prototype.hasOwnProperty,GR=(e,t)=>{for(var n in t)Nl(e,n,{get:t[n],enumerable:!0})},JR=(e,t,n,o)=>{if(t&&typeof t==="object"||typeof t==="function"){for(let i of FR(t))if(!BR.call(e,i)&&i!==n)Nl(e,i,{get:()=>t[i],enumerable:!(o=$R(t,i))||o.enumerable})}return e},HR=(e)=>JR(Nl({},"__esModule",{value:!0}),e),Sg={};GR(Sg,{SYMBOL_FOR_REQ_CONTEXT:()=>wg,getContext:()=>WR});xg.exports=HR(Sg);var wg=Symbol.for("@vercel/request-context");function WR(){return globalThis[wg]?.get?.()??{}}});var Cg=ye(function(PW,Ig){var{defineProperty:ql,getOwnPropertyDescriptor:ZR,getOwnPropertyNames:KR}=Object,QR=Object.prototype.hasOwnProperty,YR=(e,t)=>{for(var n in t)ql(e,n,{get:t[n],enumerable:!0})},XR=(e,t,n,o)=>{if(t&&typeof t==="object"||typeof t==="function"){for(let i of KR(t))if(!QR.call(e,i)&&i!==n)ql(e,i,{get:()=>t[i],enumerable:!(o=ZR(t,i))||o.enumerable})}return e},eE=(e)=>XR(ql({},"__esModule",{value:!0}),e),Tg={};YR(Tg,{getVercelOidcToken:()=>nE,getVercelOidcTokenSync:()=>Ul});Ig.exports=eE(Tg);var tE=Dl(),rE=VR();async function nE(e){let t="",n;try{t=Ul()}catch(o){n=o}try{let[{getTokenPayload:o,isExpired:i},{refreshToken:a}]=await Promise.all([await import("./token-util-kr4bxg42.js").then((m)=>Mn(m.default)),await import("./token-q107bcca.js").then((m)=>Mn(m.default))]);if(!t||i(o(t),e?.expirationBufferMs))await a(e),t=Ul()}catch(o){let i=n instanceof Error?n.message:"";if(o instanceof Error)i=`${i}
|
|
3
3
|
${o.message}`;if(i)throw new rE.VercelOidcTokenError(i);throw o}return t}function Ul(){let e=(0,tE.getContext)().headers?.["x-vercel-oidc-token"]??process.env.VERCEL_OIDC_TOKEN;if(!e)throw Error("The 'x-vercel-oidc-token' header is missing from the request. Do you have the OIDC option enabled in the Vercel project settings?");return e}});var $l=ye(function(MW,Ag){var{defineProperty:Ll,getOwnPropertyDescriptor:aE,getOwnPropertyNames:sE}=Object,lE=Object.prototype.hasOwnProperty,cE=(e,t)=>{for(var n in t)Ll(e,n,{get:t[n],enumerable:!0})},uE=(e,t,n,o)=>{if(t&&typeof t==="object"||typeof t==="function"){for(let i of sE(t))if(!lE.call(e,i)&&i!==n)Ll(e,i,{get:()=>t[i],enumerable:!(o=aE(t,i))||o.enumerable})}return e},dE=(e)=>uE(Ll({},"__esModule",{value:!0}),e),Eg={};cE(Eg,{AccessTokenMissingError:()=>Rg.AccessTokenMissingError,RefreshAccessTokenFailedError:()=>Rg.RefreshAccessTokenFailedError,getContext:()=>pE.getContext,getVercelOidcToken:()=>kg.getVercelOidcToken,getVercelOidcTokenSync:()=>kg.getVercelOidcTokenSync,getVercelToken:()=>mE.getVercelToken});Ag.exports=dE(Eg);var kg=Cg(),pE=Dl(),Rg=oE(),mE=iE()});var Gl=ye(function(Cf){Object.defineProperty(Cf,"__esModule",{value:!0});Cf.VERSION=void 0;Cf.VERSION="1.9.1"});var Mf=ye(function(Af){Object.defineProperty(Af,"__esModule",{value:!0});Af.isCompatible=Af._makeCompatibilityCheck=void 0;var AA=Gl(),Rf=/^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;function Ef(e){let t=new Set([e]),n=new Set,o=e.match(Rf);if(!o)return()=>!1;let i={major:+o[1],minor:+o[2],patch:+o[3],prerelease:o[4]};if(i.prerelease!=null)return function(c){return c===e};function a(l){return n.add(l),!1}function s(l){return t.add(l),!0}return function(c){if(t.has(c))return!0;if(n.has(c))return!1;let u=c.match(Rf);if(!u)return a(c);let d={major:+u[1],minor:+u[2],patch:+u[3],prerelease:u[4]};if(d.prerelease!=null)return a(c);if(i.major!==d.major)return a(c);if(i.major===0){if(i.minor===d.minor&&i.patch<=d.patch)return s(c);return a(c)}if(i.minor<=d.minor)return s(c);return a(c)}}Af._makeCompatibilityCheck=Ef;Af.isCompatible=Ef(AA.VERSION)});var jn=ye(function(jf){Object.defineProperty(jf,"__esModule",{value:!0});jf.unregisterGlobal=jf.getGlobal=jf.registerGlobal=void 0;var uo=Gl(),MA=Mf(),jA=uo.VERSION.split(".")[0],hi=Symbol.for(`opentelemetry.js.api.${jA}`),yi=typeof globalThis==="object"?globalThis:typeof self==="object"?self:typeof window==="object"?window:typeof global==="object"?global:{};function OA(e,t,n,o=!1){var i;let a=yi[hi]=(i=yi[hi])!==null&&i!==void 0?i:{version:uo.VERSION};if(!o&&a[e]){let s=Error(`@opentelemetry/api: Attempted duplicate registration of API: ${e}`);return n.error(s.stack||s.message),!1}if(a.version!==uo.VERSION){let s=Error(`@opentelemetry/api: Registration of version v${a.version} for ${e} does not match previously registered API v${uo.VERSION}`);return n.error(s.stack||s.message),!1}return a[e]=t,n.debug(`@opentelemetry/api: Registered a global for ${e} v${uo.VERSION}.`),!0}jf.registerGlobal=OA;function NA(e){var t,n;let o=(t=yi[hi])===null||t===void 0?void 0:t.version;if(!o||!(0,MA.isCompatible)(o))return;return(n=yi[hi])===null||n===void 0?void 0:n[e]}jf.getGlobal=NA;function DA(e,t){t.debug(`@opentelemetry/api: Unregistering a global for ${e} v${uo.VERSION}.`);let n=yi[hi];if(n)delete n[e]}jf.unregisterGlobal=DA});var Uf=ye(function(Df){Object.defineProperty(Df,"__esModule",{value:!0});Df.DiagComponentLogger=void 0;var qA=jn();class Nf{constructor(e){this._namespace=e.namespace||"DiagComponentLogger"}debug(...e){return vi("debug",this._namespace,e)}error(...e){return vi("error",this._namespace,e)}info(...e){return vi("info",this._namespace,e)}warn(...e){return vi("warn",this._namespace,e)}verbose(...e){return vi("verbose",this._namespace,e)}}Df.DiagComponentLogger=Nf;function vi(e,t,n){let o=(0,qA.getGlobal)("diag");if(!o)return;return o[e](t,...n)}});var Da=ye(function(qf){Object.defineProperty(qf,"__esModule",{value:!0});qf.DiagLogLevel=void 0;var LA;(function(e){e[e.NONE=0]="NONE",e[e.ERROR=30]="ERROR",e[e.WARN=50]="WARN",e[e.INFO=60]="INFO",e[e.DEBUG=70]="DEBUG",e[e.VERBOSE=80]="VERBOSE",e[e.ALL=9999]="ALL"})(LA=qf.DiagLogLevel||(qf.DiagLogLevel={}))});var Ff=ye(function(Lf){Object.defineProperty(Lf,"__esModule",{value:!0});Lf.createLogLevelDiagLogger=void 0;var Jr=Da();function $A(e,t){if(e<Jr.DiagLogLevel.NONE)e=Jr.DiagLogLevel.NONE;else if(e>Jr.DiagLogLevel.ALL)e=Jr.DiagLogLevel.ALL;t=t||{};function n(o,i){let a=t[o];if(typeof a==="function"&&e>=i)return a.bind(t);return function(){}}return{error:n("error",Jr.DiagLogLevel.ERROR),warn:n("warn",Jr.DiagLogLevel.WARN),info:n("info",Jr.DiagLogLevel.INFO),debug:n("debug",Jr.DiagLogLevel.DEBUG),verbose:n("verbose",Jr.DiagLogLevel.VERBOSE)}}Lf.createLogLevelDiagLogger=$A});var On=ye(function(Gf){Object.defineProperty(Gf,"__esModule",{value:!0});Gf.DiagAPI=void 0;var FA=Uf(),BA=Ff(),Bf=Da(),za=jn(),GA="diag";class Hl{static instance(){if(!this._instance)this._instance=new Hl;return this._instance}constructor(){function e(o){return function(...i){let a=(0,za.getGlobal)("diag");if(!a)return;return a[o](...i)}}let t=this,n=(o,i={logLevel:Bf.DiagLogLevel.INFO})=>{var a,s,l;if(o===t){let d=Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");return t.error((a=d.stack)!==null&&a!==void 0?a:d.message),!1}if(typeof i==="number")i={logLevel:i};let c=(0,za.getGlobal)("diag"),u=(0,BA.createLogLevelDiagLogger)((s=i.logLevel)!==null&&s!==void 0?s:Bf.DiagLogLevel.INFO,o);if(c&&!i.suppressOverrideMessage){let d=(l=Error().stack)!==null&&l!==void 0?l:"<failed to generate stacktrace>";c.warn(`Current logger will be overwritten from ${d}`),u.warn(`Current logger will overwrite one already registered from ${d}`)}return(0,za.registerGlobal)("diag",u,t,!0)};t.setLogger=n,t.disable=()=>{(0,za.unregisterGlobal)(GA,t)},t.createComponentLogger=(o)=>new FA.DiagComponentLogger(o),t.verbose=e("verbose"),t.debug=e("debug"),t.info=e("info"),t.warn=e("warn"),t.error=e("error")}}Gf.DiagAPI=Hl});var Vf=ye(function(Hf){Object.defineProperty(Hf,"__esModule",{value:!0});Hf.BaggageImpl=void 0;class po{constructor(e){this._entries=e?new Map(e):new Map}getEntry(e){let t=this._entries.get(e);if(!t)return;return Object.assign({},t)}getAllEntries(){return Array.from(this._entries.entries())}setEntry(e,t){let n=new po(this._entries);return n._entries.set(e,t),n}removeEntry(e){let t=new po(this._entries);return t._entries.delete(e),t}removeEntries(...e){let t=new po(this._entries);for(let n of e)t._entries.delete(n);return t}clear(){return new po}}Hf.BaggageImpl=po});var Qf=ye(function(Zf){Object.defineProperty(Zf,"__esModule",{value:!0});Zf.baggageEntryMetadataSymbol=void 0;Zf.baggageEntryMetadataSymbol=Symbol("BaggageEntryMetadata")});var Wl=ye(function(Yf){Object.defineProperty(Yf,"__esModule",{value:!0});Yf.baggageEntryMetadataFromString=Yf.createBaggage=void 0;var JA=On(),HA=Vf(),WA=Qf(),VA=JA.DiagAPI.instance();function ZA(e={}){return new HA.BaggageImpl(new Map(Object.entries(e)))}Yf.createBaggage=ZA;function KA(e){if(typeof e!=="string")VA.error(`Cannot create baggage metadata from unknown type: ${typeof e}`),e="";return{__TYPE__:WA.baggageEntryMetadataSymbol,toString(){return e}}}Yf.baggageEntryMetadataFromString=KA});var bi=ye(function(eh){Object.defineProperty(eh,"__esModule",{value:!0});eh.ROOT_CONTEXT=eh.createContextKey=void 0;function YA(e){return Symbol.for(e)}eh.createContextKey=YA;class Ua{constructor(e){let t=this;t._currentContext=e?new Map(e):new Map,t.getValue=(n)=>t._currentContext.get(n),t.setValue=(n,o)=>{let i=new Ua(t._currentContext);return i._currentContext.set(n,o),i},t.deleteValue=(n)=>{let o=new Ua(t._currentContext);return o._currentContext.delete(n),o}}}eh.ROOT_CONTEXT=new Ua});var ih=ye(function(nh){Object.defineProperty(nh,"__esModule",{value:!0});nh.DiagConsoleLogger=nh._originalConsoleMethods=void 0;var Vl=[{n:"error",c:"error"},{n:"warn",c:"warn"},{n:"info",c:"info"},{n:"debug",c:"debug"},{n:"verbose",c:"trace"}];nh._originalConsoleMethods={};if(typeof console<"u"){let e=["error","warn","info","debug","trace","log"];for(let t of e)if(typeof console[t]==="function")nh._originalConsoleMethods[t]=console[t]}class rh{constructor(){function e(t){return function(...n){let o=nh._originalConsoleMethods[t];if(typeof o!=="function")o=nh._originalConsoleMethods.log;if(typeof o!=="function"&&console){if(o=console[t],typeof o!=="function")o=console.log}if(typeof o==="function")return o.apply(console,n)}}for(let t=0;t<Vl.length;t++)this[Vl[t].n]=e(Vl[t].c)}}nh.DiagConsoleLogger=rh});var nc=ye(function(ah){Object.defineProperty(ah,"__esModule",{value:!0});ah.createNoopMeter=ah.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=ah.NOOP_OBSERVABLE_GAUGE_METRIC=ah.NOOP_OBSERVABLE_COUNTER_METRIC=ah.NOOP_UP_DOWN_COUNTER_METRIC=ah.NOOP_HISTOGRAM_METRIC=ah.NOOP_GAUGE_METRIC=ah.NOOP_COUNTER_METRIC=ah.NOOP_METER=ah.NoopObservableUpDownCounterMetric=ah.NoopObservableGaugeMetric=ah.NoopObservableCounterMetric=ah.NoopObservableMetric=ah.NoopHistogramMetric=ah.NoopGaugeMetric=ah.NoopUpDownCounterMetric=ah.NoopCounterMetric=ah.NoopMetric=ah.NoopMeter=void 0;class Zl{constructor(){}createGauge(e,t){return ah.NOOP_GAUGE_METRIC}createHistogram(e,t){return ah.NOOP_HISTOGRAM_METRIC}createCounter(e,t){return ah.NOOP_COUNTER_METRIC}createUpDownCounter(e,t){return ah.NOOP_UP_DOWN_COUNTER_METRIC}createObservableGauge(e,t){return ah.NOOP_OBSERVABLE_GAUGE_METRIC}createObservableCounter(e,t){return ah.NOOP_OBSERVABLE_COUNTER_METRIC}createObservableUpDownCounter(e,t){return ah.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC}addBatchObservableCallback(e,t){}removeBatchObservableCallback(e){}}ah.NoopMeter=Zl;class mo{}ah.NoopMetric=mo;class Kl extends mo{add(e,t){}}ah.NoopCounterMetric=Kl;class Ql extends mo{add(e,t){}}ah.NoopUpDownCounterMetric=Ql;class Yl extends mo{record(e,t){}}ah.NoopGaugeMetric=Yl;class Xl extends mo{record(e,t){}}ah.NoopHistogramMetric=Xl;class _i{addCallback(e){}removeCallback(e){}}ah.NoopObservableMetric=_i;class ec extends _i{}ah.NoopObservableCounterMetric=ec;class tc extends _i{}ah.NoopObservableGaugeMetric=tc;class rc extends _i{}ah.NoopObservableUpDownCounterMetric=rc;ah.NOOP_METER=new Zl;ah.NOOP_COUNTER_METRIC=new Kl;ah.NOOP_GAUGE_METRIC=new Yl;ah.NOOP_HISTOGRAM_METRIC=new Xl;ah.NOOP_UP_DOWN_COUNTER_METRIC=new Ql;ah.NOOP_OBSERVABLE_COUNTER_METRIC=new ec;ah.NOOP_OBSERVABLE_GAUGE_METRIC=new tc;ah.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC=new rc;function eP(){return ah.NOOP_METER}ah.createNoopMeter=eP});var yh=ye(function(hh){Object.defineProperty(hh,"__esModule",{value:!0});hh.ValueType=void 0;var dP;(function(e){e[e.INT=0]="INT",e[e.DOUBLE=1]="DOUBLE"})(dP=hh.ValueType||(hh.ValueType={}))});var ic=ye(function(vh){Object.defineProperty(vh,"__esModule",{value:!0});vh.defaultTextMapSetter=vh.defaultTextMapGetter=void 0;vh.defaultTextMapGetter={get(e,t){if(e==null)return;return e[t]},keys(e){if(e==null)return[];return Object.keys(e)}};vh.defaultTextMapSetter={set(e,t,n){if(e==null)return;e[t]=n}}});var xh=ye(function(Sh){Object.defineProperty(Sh,"__esModule",{value:!0});Sh.NoopContextManager=void 0;var mP=bi();class _h{active(){return mP.ROOT_CONTEXT}with(e,t,n,...o){return t.call(n,...o)}bind(e,t){return t}enable(){return this}disable(){return this}}Sh.NoopContextManager=_h});var Si=ye(function(Ih){Object.defineProperty(Ih,"__esModule",{value:!0});Ih.ContextAPI=void 0;var gP=xh(),ac=jn(),Th=On(),sc="context",fP=new gP.NoopContextManager;class lc{constructor(){}static getInstance(){if(!this._instance)this._instance=new lc;return this._instance}setGlobalContextManager(e){return(0,ac.registerGlobal)(sc,e,Th.DiagAPI.instance())}active(){return this._getContextManager().active()}with(e,t,n,...o){return this._getContextManager().with(e,t,n,...o)}bind(e,t){return this._getContextManager().bind(e,t)}_getContextManager(){return(0,ac.getGlobal)(sc)||fP}disable(){this._getContextManager().disable(),(0,ac.unregisterGlobal)(sc,Th.DiagAPI.instance())}}Ih.ContextAPI=lc});var uc=ye(function(kh){Object.defineProperty(kh,"__esModule",{value:!0});kh.TraceFlags=void 0;var hP;(function(e){e[e.NONE=0]="NONE",e[e.SAMPLED=1]="SAMPLED"})(hP=kh.TraceFlags||(kh.TraceFlags={}))});var La=ye(function(Rh){Object.defineProperty(Rh,"__esModule",{value:!0});Rh.INVALID_SPAN_CONTEXT=Rh.INVALID_TRACEID=Rh.INVALID_SPANID=void 0;var yP=uc();Rh.INVALID_SPANID="0000000000000000";Rh.INVALID_TRACEID="00000000000000000000000000000000";Rh.INVALID_SPAN_CONTEXT={traceId:Rh.INVALID_TRACEID,spanId:Rh.INVALID_SPANID,traceFlags:yP.TraceFlags.NONE}});var $a=ye(function(jh){Object.defineProperty(jh,"__esModule",{value:!0});jh.NonRecordingSpan=void 0;var vP=La();class Mh{constructor(e=vP.INVALID_SPAN_CONTEXT){this._spanContext=e}spanContext(){return this._spanContext}setAttribute(e,t){return this}setAttributes(e){return this}addEvent(e,t){return this}addLink(e){return this}addLinks(e){return this}setStatus(e){return this}updateName(e){return this}end(e){}isRecording(){return!1}recordException(e,t){}}jh.NonRecordingSpan=Mh});var mc=ye(function(Dh){Object.defineProperty(Dh,"__esModule",{value:!0});Dh.getSpanContext=Dh.setSpanContext=Dh.deleteSpan=Dh.setSpan=Dh.getActiveSpan=Dh.getSpan=void 0;var bP=bi(),_P=$a(),SP=Si(),dc=(0,bP.createContextKey)("OpenTelemetry Context Key SPAN");function pc(e){return e.getValue(dc)||void 0}Dh.getSpan=pc;function wP(){return pc(SP.ContextAPI.getInstance().active())}Dh.getActiveSpan=wP;function Nh(e,t){return e.setValue(dc,t)}Dh.setSpan=Nh;function xP(e){return e.deleteValue(dc)}Dh.deleteSpan=xP;function TP(e,t){return Nh(e,new _P.NonRecordingSpan(t))}Dh.setSpanContext=TP;function IP(e){var t;return(t=pc(e))===null||t===void 0?void 0:t.spanContext()}Dh.getSpanContext=IP});var Ba=ye(function(Fh){Object.defineProperty(Fh,"__esModule",{value:!0});Fh.wrapSpanContext=Fh.isSpanContextValid=Fh.isValidSpanId=Fh.isValidTraceId=void 0;var Uh=La(),PP=$a(),Fa=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1]);function qh(e,t){if(typeof e!=="string"||e.length!==t)return!1;let n=0;for(let o=0;o<e.length;o+=4)n+=(Fa[e.charCodeAt(o)]|0)+(Fa[e.charCodeAt(o+1)]|0)+(Fa[e.charCodeAt(o+2)]|0)+(Fa[e.charCodeAt(o+3)]|0);return n===t}function Lh(e){return qh(e,32)&&e!==Uh.INVALID_TRACEID}Fh.isValidTraceId=Lh;function $h(e){return qh(e,16)&&e!==Uh.INVALID_SPANID}Fh.isValidSpanId=$h;function MP(e){return Lh(e.traceId)&&$h(e.spanId)}Fh.isSpanContextValid=MP;function jP(e){return new PP.NonRecordingSpan(e)}Fh.wrapSpanContext=jP});var hc=ye(function(Hh){Object.defineProperty(Hh,"__esModule",{value:!0});Hh.NoopTracer=void 0;var zP=Si(),Gh=mc(),gc=$a(),UP=Ba(),fc=zP.ContextAPI.getInstance();class Jh{startSpan(e,t,n=fc.active()){if(Boolean(t===null||t===void 0?void 0:t.root))return new gc.NonRecordingSpan;let i=n&&(0,Gh.getSpanContext)(n);if(qP(i)&&(0,UP.isSpanContextValid)(i))return new gc.NonRecordingSpan(i);else return new gc.NonRecordingSpan}startActiveSpan(e,t,n,o){let i,a,s;if(arguments.length<2)return;else if(arguments.length===2)s=t;else if(arguments.length===3)i=t,s=n;else i=t,a=n,s=o;let l=a!==null&&a!==void 0?a:fc.active(),c=this.startSpan(e,i,l),u=(0,Gh.setSpan)(l,c);return fc.with(u,s,void 0,c)}}Hh.NoopTracer=Jh;function qP(e){return e!==null&&typeof e==="object"&&"spanId"in e&&typeof e.spanId==="string"&&"traceId"in e&&typeof e.traceId==="string"&&"traceFlags"in e&&typeof e.traceFlags==="number"}});var yc=ye(function(Zh){Object.defineProperty(Zh,"__esModule",{value:!0});Zh.ProxyTracer=void 0;var LP=hc(),$P=new LP.NoopTracer;class Vh{constructor(e,t,n,o){this._provider=e,this.name=t,this.version=n,this.options=o}startSpan(e,t,n){return this._getTracer().startSpan(e,t,n)}startActiveSpan(e,t,n,o){let i=this._getTracer();return Reflect.apply(i.startActiveSpan,i,arguments)}_getTracer(){if(this._delegate)return this._delegate;let e=this._provider.getDelegateTracer(this.name,this.version,this.options);if(!e)return $P;return this._delegate=e,this._delegate}}Zh.ProxyTracer=Vh});var ey=ye(function(Yh){Object.defineProperty(Yh,"__esModule",{value:!0});Yh.NoopTracerProvider=void 0;var FP=hc();class Qh{getTracer(e,t,n){return new FP.NoopTracer}}Yh.NoopTracerProvider=Qh});var vc=ye(function(ry){Object.defineProperty(ry,"__esModule",{value:!0});ry.ProxyTracerProvider=void 0;var BP=yc(),GP=ey(),JP=new GP.NoopTracerProvider;class ty{getTracer(e,t,n){var o;return(o=this.getDelegateTracer(e,t,n))!==null&&o!==void 0?o:new BP.ProxyTracer(this,e,t,n)}getDelegate(){var e;return(e=this._delegate)!==null&&e!==void 0?e:JP}setDelegate(e){this._delegate=e}getDelegateTracer(e,t,n){var o;return(o=this._delegate)===null||o===void 0?void 0:o.getTracer(e,t,n)}}ry.ProxyTracerProvider=ty});var iy=ye(function(oy){Object.defineProperty(oy,"__esModule",{value:!0});oy.SamplingDecision=void 0;var HP;(function(e){e[e.NOT_RECORD=0]="NOT_RECORD",e[e.RECORD=1]="RECORD",e[e.RECORD_AND_SAMPLED=2]="RECORD_AND_SAMPLED"})(HP=oy.SamplingDecision||(oy.SamplingDecision={}))});var sy=ye(function(ay){Object.defineProperty(ay,"__esModule",{value:!0});ay.SpanKind=void 0;var WP;(function(e){e[e.INTERNAL=0]="INTERNAL",e[e.SERVER=1]="SERVER",e[e.CLIENT=2]="CLIENT",e[e.PRODUCER=3]="PRODUCER",e[e.CONSUMER=4]="CONSUMER"})(WP=ay.SpanKind||(ay.SpanKind={}))});var cy=ye(function(ly){Object.defineProperty(ly,"__esModule",{value:!0});ly.SpanStatusCode=void 0;var VP;(function(e){e[e.UNSET=0]="UNSET",e[e.OK=1]="OK",e[e.ERROR=2]="ERROR"})(VP=ly.SpanStatusCode||(ly.SpanStatusCode={}))});var py=ye(function(uy){Object.defineProperty(uy,"__esModule",{value:!0});uy.validateValue=uy.validateKey=void 0;var wc="[_0-9a-z-*/]",ZP=`[a-z]${wc}{0,255}`,KP=`[a-z0-9]${wc}{0,240}@[a-z]${wc}{0,13}`,QP=new RegExp(`^(?:${ZP}|${KP})$`),YP=/^[ -~]{0,255}[!-~]$/,XP=/,|=/;function eM(e){return QP.test(e)}uy.validateKey=eM;function tM(e){return YP.test(e)&&!XP.test(e)}uy.validateValue=tM});var by=ye(function(yy){Object.defineProperty(yy,"__esModule",{value:!0});yy.TraceStateImpl=void 0;var my=py(),gy=32,nM=512,fy=",",hy="=";class xc{constructor(e){if(this._internalState=new Map,e)this._parse(e)}set(e,t){let n=this._clone();if(n._internalState.has(e))n._internalState.delete(e);return n._internalState.set(e,t),n}unset(e){let t=this._clone();return t._internalState.delete(e),t}get(e){return this._internalState.get(e)}serialize(){return Array.from(this._internalState.keys()).reduceRight((e,t)=>(e.push(t+hy+this.get(t)),e),[]).join(fy)}_parse(e){if(e.length>nM)return;if(this._internalState=e.split(fy).reduceRight((t,n)=>{let o=n.trim(),i=o.indexOf(hy);if(i!==-1){let a=o.slice(0,i),s=o.slice(i+1,n.length);if((0,my.validateKey)(a)&&(0,my.validateValue)(s))t.set(a,s)}return t},new Map),this._internalState.size>gy)this._internalState=new Map(Array.from(this._internalState.entries()).reverse().slice(0,gy))}_keys(){return Array.from(this._internalState.keys()).reverse()}_clone(){let e=new xc;return e._internalState=new Map(this._internalState),e}}yy.TraceStateImpl=xc});var wy=ye(function(_y){Object.defineProperty(_y,"__esModule",{value:!0});_y.createTraceState=void 0;var oM=by();function iM(e){return new oM.TraceStateImpl(e)}_y.createTraceState=iM});var Iy=ye(function(xy){Object.defineProperty(xy,"__esModule",{value:!0});xy.context=void 0;var aM=Si();xy.context=aM.ContextAPI.getInstance()});var Ry=ye(function(Cy){Object.defineProperty(Cy,"__esModule",{value:!0});Cy.diag=void 0;var sM=On();Cy.diag=sM.DiagAPI.instance()});var Py=ye(function(Ey){Object.defineProperty(Ey,"__esModule",{value:!0});Ey.NOOP_METER_PROVIDER=Ey.NoopMeterProvider=void 0;var lM=nc();class Tc{getMeter(e,t,n){return lM.NOOP_METER}}Ey.NoopMeterProvider=Tc;Ey.NOOP_METER_PROVIDER=new Tc});var Ny=ye(function(jy){Object.defineProperty(jy,"__esModule",{value:!0});jy.MetricsAPI=void 0;var uM=Py(),Ic=jn(),My=On(),Cc="metrics";class kc{constructor(){}static getInstance(){if(!this._instance)this._instance=new kc;return this._instance}setGlobalMeterProvider(e){return(0,Ic.registerGlobal)(Cc,e,My.DiagAPI.instance())}getMeterProvider(){return(0,Ic.getGlobal)(Cc)||uM.NOOP_METER_PROVIDER}getMeter(e,t,n){return this.getMeterProvider().getMeter(e,t,n)}disable(){(0,Ic.unregisterGlobal)(Cc,My.DiagAPI.instance())}}jy.MetricsAPI=kc});var Uy=ye(function(Dy){Object.defineProperty(Dy,"__esModule",{value:!0});Dy.metrics=void 0;var dM=Ny();Dy.metrics=dM.MetricsAPI.getInstance()});var Fy=ye(function(Ly){Object.defineProperty(Ly,"__esModule",{value:!0});Ly.NoopTextMapPropagator=void 0;class qy{inject(e,t){}extract(e,t){return e}fields(){return[]}}Ly.NoopTextMapPropagator=qy});var Hy=ye(function(Gy){Object.defineProperty(Gy,"__esModule",{value:!0});Gy.deleteBaggage=Gy.setBaggage=Gy.getActiveBaggage=Gy.getBaggage=void 0;var pM=Si(),mM=bi(),Rc=(0,mM.createContextKey)("OpenTelemetry Baggage Key");function By(e){return e.getValue(Rc)||void 0}Gy.getBaggage=By;function gM(){return By(pM.ContextAPI.getInstance().active())}Gy.getActiveBaggage=gM;function fM(e,t){return e.setValue(Rc,t)}Gy.setBaggage=fM;function hM(e){return e.deleteValue(Rc)}Gy.deleteBaggage=hM});var Qy=ye(function(Zy){Object.defineProperty(Zy,"__esModule",{value:!0});Zy.PropagationAPI=void 0;var Ec=jn(),_M=Fy(),Wy=ic(),Ga=Hy(),SM=Wl(),Vy=On(),Ac="propagation",wM=new _M.NoopTextMapPropagator;class Pc{constructor(){this.createBaggage=SM.createBaggage,this.getBaggage=Ga.getBaggage,this.getActiveBaggage=Ga.getActiveBaggage,this.setBaggage=Ga.setBaggage,this.deleteBaggage=Ga.deleteBaggage}static getInstance(){if(!this._instance)this._instance=new Pc;return this._instance}setGlobalPropagator(e){return(0,Ec.registerGlobal)(Ac,e,Vy.DiagAPI.instance())}inject(e,t,n=Wy.defaultTextMapSetter){return this._getGlobalPropagator().inject(e,t,n)}extract(e,t,n=Wy.defaultTextMapGetter){return this._getGlobalPropagator().extract(e,t,n)}fields(){return this._getGlobalPropagator().fields()}disable(){(0,Ec.unregisterGlobal)(Ac,Vy.DiagAPI.instance())}_getGlobalPropagator(){return(0,Ec.getGlobal)(Ac)||wM}}Zy.PropagationAPI=Pc});var ev=ye(function(Yy){Object.defineProperty(Yy,"__esModule",{value:!0});Yy.propagation=void 0;var xM=Qy();Yy.propagation=xM.PropagationAPI.getInstance()});var av=ye(function(ov){Object.defineProperty(ov,"__esModule",{value:!0});ov.TraceAPI=void 0;var Mc=jn(),tv=vc(),rv=Ba(),go=mc(),nv=On(),jc="trace";class Oc{constructor(){this._proxyTracerProvider=new tv.ProxyTracerProvider,this.wrapSpanContext=rv.wrapSpanContext,this.isSpanContextValid=rv.isSpanContextValid,this.deleteSpan=go.deleteSpan,this.getSpan=go.getSpan,this.getActiveSpan=go.getActiveSpan,this.getSpanContext=go.getSpanContext,this.setSpan=go.setSpan,this.setSpanContext=go.setSpanContext}static getInstance(){if(!this._instance)this._instance=new Oc;return this._instance}setGlobalTracerProvider(e){let t=(0,Mc.registerGlobal)(jc,this._proxyTracerProvider,nv.DiagAPI.instance());if(t)this._proxyTracerProvider.setDelegate(e);return t}getTracerProvider(){return(0,Mc.getGlobal)(jc)||this._proxyTracerProvider}getTracer(e,t){return this.getTracerProvider().getTracer(e,t)}disable(){(0,Mc.unregisterGlobal)(jc,nv.DiagAPI.instance()),this._proxyTracerProvider=new tv.ProxyTracerProvider}}ov.TraceAPI=Oc});var cv=ye(function(sv){Object.defineProperty(sv,"__esModule",{value:!0});sv.trace=void 0;var TM=av();sv.trace=TM.TraceAPI.getInstance()});var zc=ye(function(Ze){Object.defineProperty(Ze,"__esModule",{value:!0});Ze.trace=Ze.propagation=Ze.metrics=Ze.diag=Ze.context=Ze.INVALID_SPAN_CONTEXT=Ze.INVALID_TRACEID=Ze.INVALID_SPANID=Ze.isValidSpanId=Ze.isValidTraceId=Ze.isSpanContextValid=Ze.createTraceState=Ze.TraceFlags=Ze.SpanStatusCode=Ze.SpanKind=Ze.SamplingDecision=Ze.ProxyTracerProvider=Ze.ProxyTracer=Ze.defaultTextMapSetter=Ze.defaultTextMapGetter=Ze.ValueType=Ze.createNoopMeter=Ze.DiagLogLevel=Ze.DiagConsoleLogger=Ze.ROOT_CONTEXT=Ze.createContextKey=Ze.baggageEntryMetadataFromString=void 0;var IM=Wl();Object.defineProperty(Ze,"baggageEntryMetadataFromString",{enumerable:!0,get:function(){return IM.baggageEntryMetadataFromString}});var uv=bi();Object.defineProperty(Ze,"createContextKey",{enumerable:!0,get:function(){return uv.createContextKey}});Object.defineProperty(Ze,"ROOT_CONTEXT",{enumerable:!0,get:function(){return uv.ROOT_CONTEXT}});var CM=ih();Object.defineProperty(Ze,"DiagConsoleLogger",{enumerable:!0,get:function(){return CM.DiagConsoleLogger}});var kM=Da();Object.defineProperty(Ze,"DiagLogLevel",{enumerable:!0,get:function(){return kM.DiagLogLevel}});var RM=nc();Object.defineProperty(Ze,"createNoopMeter",{enumerable:!0,get:function(){return RM.createNoopMeter}});var EM=yh();Object.defineProperty(Ze,"ValueType",{enumerable:!0,get:function(){return EM.ValueType}});var dv=ic();Object.defineProperty(Ze,"defaultTextMapGetter",{enumerable:!0,get:function(){return dv.defaultTextMapGetter}});Object.defineProperty(Ze,"defaultTextMapSetter",{enumerable:!0,get:function(){return dv.defaultTextMapSetter}});var AM=yc();Object.defineProperty(Ze,"ProxyTracer",{enumerable:!0,get:function(){return AM.ProxyTracer}});var PM=vc();Object.defineProperty(Ze,"ProxyTracerProvider",{enumerable:!0,get:function(){return PM.ProxyTracerProvider}});var MM=iy();Object.defineProperty(Ze,"SamplingDecision",{enumerable:!0,get:function(){return MM.SamplingDecision}});var jM=sy();Object.defineProperty(Ze,"SpanKind",{enumerable:!0,get:function(){return jM.SpanKind}});var OM=cy();Object.defineProperty(Ze,"SpanStatusCode",{enumerable:!0,get:function(){return OM.SpanStatusCode}});var NM=uc();Object.defineProperty(Ze,"TraceFlags",{enumerable:!0,get:function(){return NM.TraceFlags}});var DM=wy();Object.defineProperty(Ze,"createTraceState",{enumerable:!0,get:function(){return DM.createTraceState}});var Nc=Ba();Object.defineProperty(Ze,"isSpanContextValid",{enumerable:!0,get:function(){return Nc.isSpanContextValid}});Object.defineProperty(Ze,"isValidTraceId",{enumerable:!0,get:function(){return Nc.isValidTraceId}});Object.defineProperty(Ze,"isValidSpanId",{enumerable:!0,get:function(){return Nc.isValidSpanId}});var Dc=La();Object.defineProperty(Ze,"INVALID_SPANID",{enumerable:!0,get:function(){return Dc.INVALID_SPANID}});Object.defineProperty(Ze,"INVALID_TRACEID",{enumerable:!0,get:function(){return Dc.INVALID_TRACEID}});Object.defineProperty(Ze,"INVALID_SPAN_CONTEXT",{enumerable:!0,get:function(){return Dc.INVALID_SPAN_CONTEXT}});var pv=Iy();Object.defineProperty(Ze,"context",{enumerable:!0,get:function(){return pv.context}});var mv=Ry();Object.defineProperty(Ze,"diag",{enumerable:!0,get:function(){return mv.diag}});var gv=Uy();Object.defineProperty(Ze,"metrics",{enumerable:!0,get:function(){return gv.metrics}});var fv=ev();Object.defineProperty(Ze,"propagation",{enumerable:!0,get:function(){return fv.propagation}});var hv=cv();Object.defineProperty(Ze,"trace",{enumerable:!0,get:function(){return hv.trace}});Ze.default={context:pv.context,diag:mv.diag,metrics:gv.metrics,propagation:fv.propagation,trace:hv.trace}});var ls=ye(function(VS){Object.defineProperty(VS,"__esModule",{value:!0});function HS(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global;console.warn("XState could not find a global object in this environment. Please let the maintainers know and raise an issue here: https://github.com/statelyai/xstate/issues")}function WS(){let e=HS();if(e.__xstate__)return e.__xstate__;return}function aU(e){if(typeof window>"u")return;let t=WS();if(t)t.register(e)}var sU=(e)=>{if(typeof window>"u")return;let t=WS();if(t)t.register(e)};VS.devToolsAdapter=sU;VS.getGlobal=HS;VS.registerService=aU});var Ro=ye(function(hq){var dU=ls();class qu{constructor(e){this._process=e,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){if(this._current)this._current.next=null,this._last=this._current}enqueue(e){let t={value:e,next:null};if(this._current){this._last.next=t,this._last=t;return}if(this._current=t,this._last=t,this._active)this.flush()}flush(){while(this._current){let e=this._current;this._process(e.value),this._current=e.next}this._last=null}}var ew=".",pU="",tw="",mU="#",Lu="*",rw="xstate.init",gU="xstate.error",cs="xstate.stop";function fU(e,t){return{type:`xstate.after.${e}.${t}`}}function $u(e,t){return{type:`xstate.done.state.${e}`,output:t}}function hU(e,t){return{type:`xstate.done.actor.${e}`,output:t,actorId:e}}function nw(e,t){return{type:`xstate.error.actor.${e}`,error:t,actorId:e}}function ow(e){return{type:rw,input:e}}function Ar(e){setTimeout(()=>{throw e})}var yU=(()=>typeof Symbol==="function"&&Symbol.observable||"@@observable")();function Ju(e,t){let n=ZS(e),o=ZS(t);if(typeof o==="string"){if(typeof n==="string")return o===n;return!1}if(typeof n==="string")return n in o;return Object.keys(n).every((i)=>{if(!(i in o))return!1;return Ju(n[i],o[i])})}function Hu(e){if(sw(e))return e;let t=[],n="";for(let o=0;o<e.length;o++){switch(e.charCodeAt(o)){case 92:n+=e[o+1],o++;continue;case 46:t.push(n),n="";continue}n+=e[o]}return t.push(n),t}function ZS(e){if(Iw(e))return e.value;if(typeof e!=="string")return e;let t=Hu(e);return iw(t)}function iw(e){if(e.length===1)return e[0];let t={},n=t;for(let o=0;o<e.length-1;o++)if(o===e.length-2)n[e[o]]=e[o+1];else{let i=n;n={},i[e[o]]=n}return t}function vU(e,t){let n={},o=Object.keys(e);for(let i=0;i<o.length;i++){let a=o[i];n[a]=t(e[a],a,e,i)}return n}function aw(e){if(sw(e))return e;return[e]}function Gi(e){if(e===void 0)return[];return aw(e)}function Fu(e,t,n,o){if(typeof e==="function")return e({context:t,event:n,self:o});if(!!e&&typeof e==="object"&&Object.values(e).some((i)=>typeof i==="function"))console.warn(`Dynamically mapping values to individual properties is deprecated. Use a single function that returns the mapped object instead.
|
|
4
4
|
Found object containing properties whose values are possibly mapping functions: ${Object.entries(e).filter(([,i])=>typeof i==="function").map(([i,a])=>`
|
|
5
5
|
- ${i}: ${a.toString().replace(/\n\s*/g,"")}`).join("")}`);return e}function sw(e){return Array.isArray(e)}function bU(e){return e.type.startsWith("xstate.error.actor")}function So(e){return aw(e).map((t)=>{if(typeof t>"u"||typeof t==="string")return{target:t};return t})}function lw(e){if(e===void 0||e===pU)return;return Gi(e)}function Fi(e,t,n){let o=typeof e==="object",i=o?e:void 0;return{next:(o?e.next:e)?.bind(i),error:(o?e.error:t)?.bind(i),complete:(o?e.complete:n)?.bind(i)}}function _U(e,t){return`${t}.${e}`}function cw(e,t){let n=t.match(/^xstate\.invoke\.(\d+)\.(.*)/);if(!n)return e.implementations.actors[t];let[,o,i]=n,s=e.getStateNodeById(i).config.invoke;return(Array.isArray(s)?s[o]:s).src}function SU(e){return[...new Set([...e._nodes.flatMap((t)=>t.ownEvents)])]}function uw(e,t){if(t===e)return!0;if(t===Lu)return!0;if(!t.endsWith(".*"))return!1;if(/.*\*.+/.test(t))console.warn(`Wildcards can only be the last token of an event descriptor (e.g., "event.*") or the entire event descriptor ("*"). Check the "${t}" event.`);let n=t.split("."),o=e.split(".");for(let i=0;i<n.length;i++){let a=n[i],s=o[i];if(a==="*"){let l=i===n.length-1;if(!l)console.warn(`Infix wildcards in transition events are not allowed. Check the "${t}" transition.`);return l}if(a!==s)return!1}return!0}function KS(e,t){return`${e.sessionId}.${t}`}var wU=0;function dw(e,t){let n=new Map,o=new Map,i=new WeakMap,a=new Set,s={},{clock:l,logger:c}=t,u={schedule:(p,f,g,h,v=Math.random().toString(36).slice(2))=>{let x={source:p,target:f,event:g,delay:h,id:v,startedAt:Date.now()},b=KS(p,v);m._snapshot._scheduledEvents[b]=x;let y=l.setTimeout(()=>{delete s[b],delete m._snapshot._scheduledEvents[b],m._relay(p,f,g)},h);s[b]=y},cancel:(p,f)=>{let g=KS(p,f),h=s[g];if(delete s[g],delete m._snapshot._scheduledEvents[g],h!==void 0)l.clearTimeout(h)},cancelAll:(p)=>{for(let f in m._snapshot._scheduledEvents){let g=m._snapshot._scheduledEvents[f];if(g.source===p)u.cancel(p,g.id)}}},d=(p)=>{if(!a.size)return;let f={...p,rootId:e.sessionId};a.forEach((g)=>g.next?.(f))},m={_snapshot:{_scheduledEvents:(t?.snapshot&&t.snapshot.scheduler)??{}},_bookId:()=>`x:${wU++}`,_register:(p,f)=>(n.set(p,f),p),_unregister:(p)=>{n.delete(p.sessionId);let f=i.get(p);if(f!==void 0)o.delete(f),i.delete(p)},get:(p)=>o.get(p),getAll:()=>Object.fromEntries(o.entries()),_set:(p,f)=>{let g=o.get(p);if(g&&g!==f)throw Error(`Actor with system ID '${p}' already exists.`);o.set(p,f),i.set(f,p)},inspect:(p)=>{let f=Fi(p);return a.add(f),{unsubscribe(){a.delete(f)}}},_sendInspectionEvent:d,_relay:(p,f,g)=>{m._sendInspectionEvent({type:"@xstate.event",sourceRef:p,actorRef:f,event:g}),f._send(g)},scheduler:u,getSnapshot:()=>({_scheduledEvents:{...m._snapshot._scheduledEvents}}),start:()=>{let p=m._snapshot._scheduledEvents;m._snapshot._scheduledEvents={};for(let f in p){let{source:g,target:h,event:v,delay:x,id:b}=p[f];u.schedule(g,h,v,x,b)}},_clock:l,_logger:c};return m}hq.executingCustomAction=!1;var Wu=1,Ht=function(e){return e[e.NotStarted=0]="NotStarted",e[e.Running=1]="Running",e[e.Stopped=2]="Stopped",e}({}),xU={clock:{setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:(e)=>clearTimeout(e)},logger:console.log.bind(console),devTools:!1};class Vu{constructor(e,t){this.logic=e,this._snapshot=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new qu(this._process.bind(this)),this.observers=new Set,this.eventListeners=new Map,this.logger=void 0,this._processingStatus=Ht.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this.systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];let n={...xU,...t},{clock:o,logger:i,parent:a,syncSnapshot:s,id:l,systemId:c,inspect:u}=n;if(this.system=a?a.system:dw(this,{clock:o,logger:i}),u&&!a)this.system.inspect(Fi(u));if(this.sessionId=this.system._bookId(),this.id=l??this.sessionId,this.logger=t?.logger??this.system._logger,this.clock=t?.clock??this.system._clock,this._parent=a,this._syncSnapshot=s,this.options=n,this.src=n.src??e,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:(d)=>{this._deferred.push(d)},system:this.system,stopChild:(d)=>{if(d._parent!==this)throw Error(`Cannot stop child actor ${d.id} of ${this.id} because it is not a child`);d._stop()},emit:(d)=>{let m=this.eventListeners.get(d.type),p=this.eventListeners.get("*");if(!m&&!p)return;let f=[...m?m.values():[],...p?p.values():[]];for(let g of f)try{g(d)}catch(h){Ar(h)}},actionExecutor:(d)=>{let m=()=>{if(this._actorScope.system._sendInspectionEvent({type:"@xstate.action",actorRef:this,action:{type:d.type,params:d.params}}),!d.exec)return;let p=hq.executingCustomAction;try{hq.executingCustomAction=!0,d.exec(d.info,d.params)}finally{hq.executingCustomAction=p}};if(this._processingStatus===Ht.Running)m();else this._deferred.push(m)}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),c)this.systemId=c,this.system._set(c,this);if(this._initState(t?.snapshot??t?.state),c&&this._snapshot.status!=="active")this.system._unregister(this)}_initState(e){try{this._snapshot=e?this.logic.restoreSnapshot?this.logic.restoreSnapshot(e,this._actorScope):e:this.logic.getInitialSnapshot(this._actorScope,this.options?.input)}catch(t){this._snapshot={status:"error",output:void 0,error:t}}}update(e,t){this._snapshot=e;let n;while(n=this._deferred.shift())try{n()}catch(o){this._deferred.length=0,this._snapshot={...e,status:"error",error:o}}switch(this._snapshot.status){case"active":for(let o of this.observers)try{o.next?.(e)}catch(i){Ar(i)}break;case"done":for(let o of this.observers)try{o.next?.(e)}catch(i){Ar(i)}if(this._stopProcedure(),this._complete(),this._doneEvent=hU(this.id,this._snapshot.output),this._parent)this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._error(this._snapshot.error);break}this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:t,snapshot:e})}subscribe(e,t,n){let o=Fi(e,t,n);if(this._processingStatus!==Ht.Stopped)this.observers.add(o);else switch(this._snapshot.status){case"done":try{o.complete?.()}catch(i){Ar(i)}break;case"error":{let i=this._snapshot.error;if(!o.error)Ar(i);else try{o.error(i)}catch(a){Ar(a)}break}}return{unsubscribe:()=>{this.observers.delete(o)}}}on(e,t){let n=this.eventListeners.get(e);if(!n)n=new Set,this.eventListeners.set(e,n);let o=t.bind(void 0);return n.add(o),{unsubscribe:()=>{n.delete(o)}}}select(e,t=Object.is){return{subscribe:(n)=>{let o=Fi(n),i=this.getSnapshot(),a=e(i);return this.subscribe((s)=>{let l=e(s);if(!t(a,l))a=l,o.next?.(l)})},get:()=>e(this.getSnapshot())}}start(){if(this._processingStatus===Ht.Running)return this;if(this._syncSnapshot)this.subscribe({next:(n)=>{if(n.status==="active")this.system._relay(this,this._parent,{type:`xstate.snapshot.${this.id}`,snapshot:n})},error:()=>{}});if(this.system._register(this.sessionId,this),this.systemId)this.system._set(this.systemId,this);this._processingStatus=Ht.Running;let e=ow(this.options.input);switch(this.system._sendInspectionEvent({type:"@xstate.event",sourceRef:this._parent,actorRef:this,event:e}),this._snapshot.status){case"done":return this.update(this._snapshot,e),this;case"error":return this._error(this._snapshot.error),this}if(!this._parent)this.system.start();if(this.logic.start)try{this.logic.start(this._snapshot,this._actorScope)}catch(n){return this._snapshot={...this._snapshot,status:"error",error:n},this._error(n),this}if(this.update(this._snapshot,e),this.options.devTools)this.attachDevTools();return this.mailbox.start(),this}_process(e){let t,n;try{t=this.logic.transition(this._snapshot,e,this._actorScope)}catch(o){n={err:o}}if(n){let{err:o}=n;this._snapshot={...this._snapshot,status:"error",error:o},this._error(o);return}if(this.update(t,e),e.type===cs)this._stopProcedure(),this._complete()}_stop(){if(this._processingStatus===Ht.Stopped)return this;if(this.mailbox.clear(),this._processingStatus===Ht.NotStarted)return this._processingStatus=Ht.Stopped,this;return this.mailbox.enqueue({type:cs}),this}stop(){if(this._parent)throw Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(let e of this.observers)try{e.complete?.()}catch(t){Ar(t)}this.observers.clear(),this.eventListeners.clear()}_reportError(e){if(!this.observers.size){if(!this._parent)Ar(e);this.eventListeners.clear();return}let t=!1;for(let n of this.observers){let o=n.error;t||=!o;try{o?.(e)}catch(i){Ar(i)}}if(this.observers.clear(),this.eventListeners.clear(),t)Ar(e)}_error(e){if(this._stopProcedure(),this._reportError(e),this._parent)this.system._relay(this,this._parent,nw(this.id,e))}_stopProcedure(){if(this._processingStatus!==Ht.Running)return this;return this.system.scheduler.cancelAll(this),this.mailbox.clear(),this.mailbox=new qu(this._process.bind(this)),this._processingStatus=Ht.Stopped,this.system._unregister(this),this}_send(e){if(this._processingStatus===Ht.Stopped){{let t=JSON.stringify(e);console.warn(`Event "${e.type}" was sent to stopped actor "${this.id} (${this.sessionId})". This actor has already reached its final state, and will not transition.
|
|
@@ -186,9 +186,9 @@ ${JS}`:""),tools:w,activeTools:y,...i!==void 0&&c.supportsTemperature&&{temperat
|
|
|
186
186
|
`),s=cp(i,a,{timeout:100});if(!s)return"Full content replacement (line diff omitted: comparison exceeded its time limit).";return s.filter((l)=>l.added||l.removed).flatMap((l)=>l.value.map((c)=>`${l.added?"+":"-"} ${c}`)).join(`
|
|
187
187
|
`)}function kC(e,t,n,o){return qJ(e,t,n,o)??LJ(e.entityType,t,n)??$J(e.entityType,t,n)}function RC(e,t,n){return wC(e.entityType,e.metadata.status,FJ(e,t,n),n)==="non-publish"?"update":"publish"}function EC(e,t,n){return t.content!==void 0?DJ(e,t.content,n):TC(e,t.fields??{},n)}function vn(e){return{success:!1,error:e}}async function BJ(e,t,n,o){if([t.fields,t.content,t.edits,t.source].filter((c)=>c!==void 0).length>1)return vn("Provide only one of 'fields', 'content', 'edits', or 'source'.");if(t.confirmed&&t.contentHash&&n.contentHash!==t.contentHash)return vn("Entity was modified since you reviewed the changes. Please try again.");if(t.edits!==void 0)return{operation:{content:tC(n.content,t.edits)}};let a,s;if(t.source!==void 0){let c=await Gs(e,t.source,o);if(!c.success)return c;a=Js(t.source,c),s={content:c.content}}else s=WI({...t.fields!==void 0?{fields:t.fields}:{},...t.content!==void 0?{content:t.content}:{}});if(s.content===void 0)return s.fields?{operation:s}:vn("Provide 'content' (full replacement) or 'fields' (partial update)");let l=IC(n,s.content,e.entityRegistry);if(typeof l!=="string")return l;return{operation:{content:l},...a?{source:a}:{}}}function AC(e){let{entityService:t,logger:n,entityRegistry:o}=e,i=Xr({label:"update",requestNoun:"the update"}),a=(c,u)=>{if(!c.confirmed||!c.confirmationToken||c.edits!==void 0||c.fields!==void 0||c.source!==void 0||c.content?.trim())return{input:c,replayed:!1};let d=sp.safeParse(i.takePending(c.confirmationToken));if(!d.success||d.data.entityType!==u.entityType||d.data.id!==u.id)return vn("No pending update confirmation found for this entity. Please request the update again.");return{input:d.data,replayed:!0}},s=async(c,u,d,m,p)=>{if(!m){let g=i.validateConfirmed(c.confirmationToken,c);if(g)return g}let f=EC(u,d,o);if(f.visibility!==u.visibility&&!Vs(p.userPermissionLevel,f.visibility))return vn(`Cannot set entity visibility to "${f.visibility}" \u2014 caller permission "${p.userPermissionLevel??"public"}" is not allowed to write at that level.`);try{let g=zo(p);if((await t.updateEntity({entity:f,options:{expectedContentHash:u.contentHash,...g?{eventContext:g}:{}}})).skipReason==="content-conflict")return vn("Entity was modified before the update could be saved. Please request and confirm the update again.")}catch(g){return vn(Ce(g,"Failed to update entity"))}return{success:!0,data:{updated:u.id}}},l=(c,u,{operation:d,source:m})=>{let{fields:p,content:f,source:g,...h}=c;return{needsConfirmation:!0,toolName:"system_update",summary:`Update "${Ws(u)}"?`,completionSummary:`Updated ${VI(u.entityType)}.`,preview:CC(u,d,o),args:i.buildArgs((v)=>({...h,...c.edits!==void 0?{edits:c.edits}:m?{source:m}:d,id:u.id,confirmed:!0,confirmationToken:v,contentHash:u.contentHash}))}};return jr("update","Update an entity's fields or content. For small content changes, fetch the entity and use edits with exact oldText/newText pairs instead of regenerating the whole document. For a large rewrite whose text the user supplied, use source with exact user-message boundaries instead of copying it into content. Use only one of fields, content, edits, or source. Requires confirmation; call this tool without confirmed to request that confirmation instead of asking for plain-text approval. For direct requests that provide exact IDs to set an existing image as an entity cover, call this tool on the target entity with fields.coverImageId set to the image ID; do not stop after lookup.",sp,async(c,u)=>{let d=await Or(t,c.entityType,c.id,n,void 0,Wt(u.userPermissionLevel));if(!d.ok)return vn(d.error);let{entity:m}=d,p=a(c,m);if("success"in p)return p;let{input:f,replayed:g}=p,h=await BJ(e,f,m,u);if("success"in h)return h;let{operation:v}=h,x=kC(m,v,o,t);if(x)return x;let b=Mr(e,f.entityType,RC(m,v,o),u);if(b)return b;return f.confirmed?s(f,m,v,g,u):l(f,m,h)},{visibility:"trusted",sideEffects:"writes"})}function PC(e){return[QI(e),XI(e),eC(e),AC(e)]}function rl(e){if(e.interfaceType!==ct)return;if(e.userPermissionLevel!=="public"||e.isAnchor)throw Error("Guest execution denied")}var GJ=0.5,yp=(e)=>e==="public"?{publishedOnly:!0}:{};function JJ(e,t){if(e.length===0)return;let n=Math.round(Math.max(...e.map((o)=>o.score))*100)/100;return{minScore:t,weakerMatches:e.length,bestScore:n,hint:`No result reached minScore ${t}, but ${e.length} weaker match${e.length===1?"":"es"} exist (best score ${n}). Broad or abstract questions match content weakly: search again with a lower minScore, such as 0.3, before concluding that nothing relevant exists.`}}function MC(e){let{entityService:t,logger:n}=e;return[bn("system","search","Search entities using semantic search. For broad search, make one system_search call with scope.kind all. Use scope.kind type only when the user asks for a specific entity type. Applies a default minScore of 0.5 to reduce weak matches; lower minScore only for exploratory or loose recall. An empty result with belowThreshold means weaker matches exist: search again with a lower minScore before concluding that nothing relevant exists. Search results include each matched entity's content. When relevant results already contain the complete evidence needed, answer from those results instead of redundantly listing or getting the same entities. Search results are candidates; do not present weak or unrelated candidates as exact matches.",NI,async(o,i)=>{rl(i);let a=Wt(i.userPermissionLevel),s=o.minScore??GJ,l=await t.search({query:o.query,options:{limit:o.limit??e.searchLimit,...o.scope.kind==="type"&&{types:[o.scope.entityType]},...o.includeUngenerated!==void 0&&{includeUngenerated:o.includeUngenerated},visibilityScope:a,...yp(a)}}),c=l.filter((d)=>d.score>=s),u=c.length===0?JJ(l,s):void 0;return{success:!0,data:{results:c.map((d)=>{let m=lp(d.entity,e.entityRegistry);return{...d,entity:m,...m!==d.entity?{excerpt:m.content}:{}}}),...u&&{belowThreshold:u}}}},{visibility:"public",sideEffects:"none",cli:{name:"search"}}),bn("system","get","Retrieve a specific entity by type and identifier (ID, slug, or title). If retrieval fails, report the entity as not found rather than describing related generation work as pending.",DI,async(o,i)=>{if(rl(i),!t.getEntityTypes().includes(o.entityType))return{success:!1,error:`Unknown entity type: ${o.entityType}. Available: ${t.getEntityTypes().join(", ")}`};let a=Wt(i.userPermissionLevel),s=await Or(t,o.entityType,o.id,n,void 0,a,yp(a));if(!s.ok)return{success:!1,error:s.error};return{success:!0,data:{entity:lp(s.entity,e.entityRegistry)}}},{visibility:"public",sideEffects:"none",cli:{name:"get"}}),bn("system","list","List entities by a known entity type. Returns metadata only \u2014 use system_get for full content. Use system_search, not system_list, for broad or vague lookup requests. Use system_list to inspect metadata dates such as publishedAt when the user asks for the latest item of a known type, such as latest blog post.",zI,async(o,i)=>{if(rl(i),!t.getEntityTypes().includes(o.entityType))return{success:!1,error:`Unknown entity type: ${o.entityType}. Available: ${t.getEntityTypes().join(", ")}`};let a=Wt(i.userPermissionLevel),s={visibilityScope:a};if(o.status&&o.status!=="any")s.metadata={status:o.status};let{defaultSort:l}=e.entityRegistry.getEntityTypeConfig(o.entityType),u=(await t.listEntities({entityType:o.entityType,options:{limit:o.limit??20,filter:s,...yp(a),...l?{sortFields:l}:{}}})).map(({content:d,contentHash:m,...p})=>p);return{success:!0,data:{entities:u,count:u.length}}},{visibility:"public",sideEffects:"none",cli:{name:"list"}})]}function jC(e){let{entityService:t}=e;return[bn("system","insights",`Get aggregate content insights and analytics only. For a general overview of actual content, use system_list instead. Available types: ${e.insights.getTypes().join(", ")}.`,BI,async(n,o)=>{let i=Wt(o.userPermissionLevel);return{success:!0,data:await e.insights.get(n.type,t,i)}},{visibility:"public",sideEffects:"none"})]}function OC(e){let{jobs:t}=e;return[jr("job_status","Inspect runtime job status for ready checks only when the prior operation created a job, or for status disputes. With a known batch ID, pass batchId. Without an ID, call this tool with no arguments to list active jobs and batches; do not ask the user for an ID first. Do not argue from the transcript alone.",FI,async(n)=>{if(n.batchId){let a=await t.getBatchStatus(n.batchId);if(!a)return{success:!1,error:`No batch found with ID: ${n.batchId}`};let s=a.totalOperations>0?Math.round(a.completedOperations/a.totalOperations*100):0;return{success:!0,data:{batchId:n.batchId,status:a.status,progress:{total:a.totalOperations,completed:a.completedOperations,failed:a.failedOperations,percentComplete:s},currentOperation:a.currentOperation,errors:a.errors}}}let o=await t.getActiveJobs(n.jobTypes),i=await t.getActiveBatches();return{success:!0,data:{summary:{activeJobs:o.length,activeBatches:i.length},jobs:o.map((a)=>({id:a.id,type:a.type,status:a.status,priority:a.priority,retryCount:a.retryCount,createdAt:new Date(a.createdAt).toISOString(),startedAt:a.startedAt?new Date(a.startedAt).toISOString():null})),batches:i.map((a)=>({batchId:a.batchId,status:a.status.status,totalOperations:a.status.totalOperations,completedOperations:a.status.completedOperations,failedOperations:a.status.failedOperations,currentOperation:a.status.currentOperation,pluginId:a.metadata.metadata.pluginId,errors:a.status.errors}))}}},{visibility:"public",sideEffects:"none"})]}function HJ(e){let{entityCounts:t,daemons:n,endpoints:o,interactions:i,...a}=e;return a}function NC(e){return[bn("system","status","Get system status including model, version, interfaces, and tools",r.object({}),async()=>({success:!0,data:HJ(await e.getAppInfo())}),{visibility:"public",sideEffects:"none",cli:{name:"status"}})]}function DC(e){return[...MC(e),...OC(e),...NC(e),...PC(e),...jC(e)]}function zC(e){return[{uri:"entity://types",name:"Entity Types",description:"List of registered entity types",mimeType:"text/plain",handler:async()=>({contents:[{uri:"entity://types",mimeType:"text/plain",text:e.entityService.getEntityTypes().join(`
|
|
188
188
|
`)}]})},{uri:"brain://identity",name:"Brain Identity",description:"Brain character \u2014 name, role, purpose, values",mimeType:"application/json",handler:async()=>({contents:[{uri:"brain://identity",mimeType:"application/json",text:JSON.stringify(e.getIdentity(),null,2)}]})},{uri:"brain://profile",name:"Anchor Profile",description:"Brain owner profile \u2014 name, bio, expertise",mimeType:"application/json",handler:async()=>({contents:[{uri:"brain://profile",mimeType:"application/json",text:JSON.stringify(e.getProfile(),null,2)}]})},{uri:"brain://status",name:"Brain Status",description:"System status \u2014 version, model, interfaces, tools",mimeType:"application/json",handler:async()=>({contents:[{uri:"brain://status",mimeType:"application/json",text:JSON.stringify(await e.getAppInfo(),null,2)}]})}]}function UC(e){let{entityService:t}=e;return[{name:"entity-list",uriTemplate:"entity://{type}",description:"List entities of a given type",mimeType:"application/json",list:async()=>t.getEntityTypes().map((o)=>({uri:`entity://${o}`,name:`${o} entities`})),complete:{type:async()=>t.getEntityTypes()},handler:async({type:n})=>{let o=t.getEntityTypes();if(!o.includes(n))throw Error(`Unknown entity type: ${n}. Available: ${o.join(", ")}`);let a=(await t.listEntities({entityType:n})).map((s)=>({id:s.id,entityType:s.entityType,...s.metadata,updated:s.updated}));return{contents:[{uri:`entity://${n}`,mimeType:"application/json",text:JSON.stringify(a,null,2)}]}}},{name:"entity-detail",uriTemplate:"entity://{type}/{id}",description:"Read a single entity by type and ID",mimeType:"text/markdown",complete:{type:async(n)=>{let o=t.getEntityTypes();return n?o.filter((i)=>i.startsWith(n)):o},id:async()=>[]},handler:async({type:n,id:o})=>{let i=await t.getEntity({entityType:n,id:o});if(!i)throw Error(`Entity not found: ${n}/${o}`);return{contents:[{uri:`entity://${n}/${o}`,mimeType:"text/markdown",text:i.content}]}}}]}function qC(e){return[{name:"create",description:"Create new content of any type",args:{type:{description:"Entity type (e.g. post, deck, note)",required:!0},topic:{description:"Topic or title for the content"}},handler:async({topic:n,type:o})=>({messages:[{role:"user",content:{type:"text",text:n?`Create a new ${o} about: ${n}`:`Create a new ${o}. Ask me what it should be about.`}}]})},{name:"generate",description:"AI-generate content with a prompt",args:{type:{description:`Entity type (${(()=>e.entityService.getEntityTypes().join(", "))()})`,required:!0},topic:{description:"What to generate",required:!0}},handler:async({type:n,topic:o})=>({messages:[{role:"user",content:{type:"text",text:`Generate a ${n} about: ${o}`}}]})},{name:"review",description:"Review and improve existing content",args:{type:{description:"Entity type",required:!0},id:{description:"Entity ID or slug",required:!0}},handler:async({type:n,id:o})=>({messages:[{role:"user",content:{type:"text",text:`Review my ${n} "${o}". Read it first, then give me specific feedback on structure, clarity, and impact. Suggest concrete improvements.`}}]})},{name:"publish",description:"Publish content \u2014 preview, confirm, and publish",args:{type:{description:"Entity type",required:!0},id:{description:"Entity ID or slug",required:!0}},handler:async({type:n,id:o})=>({messages:[{role:"user",content:{type:"text",text:`I want to publish my ${n} "${o}". Show me a preview first, then publish it.`}}]})},{name:"brainstorm",description:"Brainstorm ideas using brain context and expertise",args:{topic:{description:"Topic to brainstorm about",required:!0}},handler:async({topic:n})=>({messages:[{role:"user",content:{type:"text",text:`Let's brainstorm about: ${n}. Use my existing content and expertise as context. Give me fresh angles and concrete ideas.`}}]})}]}function LC(e){let t=e.entityService.getEntityTypes(),n=t.map((o)=>`- ${o}: ${e.entityRegistry.getAdapter(o).purpose}`);return["## Entity CRUD","","Use these system tools for ALL entity operations:","","Treat explicit verbs such as save, create, capture, remember, import, add/connect an agent, approve/archive an agent, update, delete, generate, publish, or sync as mutation requests. Entity-specific instructions may require proactively recording the user's request itself for demand or workflow tracking; follow those instructions even when the user did not use a separate save/create verb. Ordinary status questions like 'what is the status', 'is it ready', 'did that finish', or 'what happened' are not capture requests; answer them by using the relevant status/read tool for the prior operation. Never call system_create for a status follow-up.","",`- **system_create**: Create an entity from existing/concrete material. Requires confirmation before persisting; call system_create without \`confirmed\` to request that confirmation, and never pass \`confirmed: true\` on the initial user request. Use the typed \`visibility\` field instead of rewriting exact source text: omit it for public content, use \`shared\` for team/collaborator content, and use \`restricted\` for private/admin-only content. Public callers may write only public content, Trusted callers public or shared, and Admin callers all three levels. If the user only says 'not public' without clarifying team/shared versus private/admin-only, ask which scope they mean. Required \`source\` union: \`{ kind: "text", content }\` stores exact/direct content; \`{ kind: "url", url }\` creates URL/domain-backed records such as links (preserve bare domains as bare domains); \`{ kind: "upload", upload, transform: "extract-markdown" }\` imports extractable upload bytes as a markdown note; \`{ kind: "upload", upload, transform: "preserve" }\` preserves raw uploaded bytes as their durable file entity; \`{ kind: "prior-response", messageId? }\` saves a previous assistant answer/summary by reference without copying or paraphrasing it. If a direct save request includes the content in the same message, that content is sufficient, even if it is a short sentence or fragment after a colon or embedded in the request phrase (for example, "Save this memo about the launch timeline"); call system_create instead of asking the user to paste it again. If the immediate context is an assistant summary/answer about an upload and the user asks to save it/that/this/summary, create a note with \`source.kind: "prior-response"\`; do this even when the prior answer says there was limited readable content. Do not ask whether they meant the summary or the file after you just summarized/answered about the upload: save the visible prior response as a note. Do not treat a bare upload receipt like "I got filename. What would you like me to do?" as a summary/answer; if the user then says "save it", preserve the latest uploaded file itself with upload \`preserve\` (image uploads as entityType image, PDFs/documents as their file entity type). Only use \`source.kind: "upload"\` when the runtime supplies an actual upload reference/attachment; if the message contains a pasted uploaded-file transcript with readable content (for example, \`User uploaded a file "name.md": ...\`), save the visible transcript content as \`source.kind: "text"\`. Only use upload \`preserve\` otherwise when they explicitly want to save the uploaded file/document itself. Use system_generate, not system_create, for AI generation, generated images, cover images, and source-derived artifacts. Available entity types: ${t.join(", ")}.`,'- **system_generate**: Generate a new durable entity or deterministic artifact. Requires confirmation before queueing generation; call system_generate without `confirmed` to request that confirmation, and never pass `confirmed: true` on the initial user request. When the user asks you to create, write, draft, or generate new durable content and has not supplied final exact content to store, call system_generate instead of drafting the content in chat or asking for separate prose approval first. An underspecified generation request still supplies a usable prompt: preserve the user\'s wording and call system_generate rather than stopping to ask what details to highlight. If generation depends on an existing source entity (for example, a newsletter from a blog post), resolve the source with read/search/list tools first unless the user gives an exact entity id in quotes, then call system_generate with `operation.kind: "prompt-from-source"` in the same turn when a clear source is found. If you identify the latest source entity, do not stop after saying you found it or can generate from it; call system_generate immediately. If no existing durable source entity is resolved, use `operation.kind: "prompt"` in the same turn, including after an optional search returns no source; never invent source IDs, use upload IDs/filenames as entity refs, use profile/brain-character as a generic source, or create placeholder source refs. For broad topical prompts like \'about AI\' or \'about continuous learning\', use `operation.kind: "prompt"`. If the user asks for the latest published/blog source, use system_list for that entity type (for blog posts, entityType post) to inspect publishedAt dates; do not rely on semantic search result order. Choose the newest matching candidate by publishedAt (not updated/created order) and proceed with system_generate rather than asking for separate prose approval; do not say \'if that is the one you mean\' when a newest dated candidate is visible. Do not say \'I can generate it if you want\' or \'I need to queue it first\'; calling system_generate without `confirmed` is the confirmation request. Required `operation` union: `{ kind: "prompt", entityType, prompt }` generates a new non-image durable entity from a broad prompt with no source; `{ kind: "prompt-from-source", entityType, source: { entityType, entityId }, prompt }` generates from an existing resolved entity, such as a newsletter from a blog post. `{ kind: "standalone-image", prompt }` generates an unattached image; `{ kind: "cover-image", target: { entityType, entityId }, prompt }` generates an image and attaches it to an existing canonical entity as `coverImageId`; `{ kind: "attachment", source: { entityType, entityId }, attachmentType }` renders a deterministic artifact from an existing entity attachment provider. For save/render/regenerate/replace requests for source-derived artifacts, call `system_generate` with `operation.kind: "attachment"` immediately; do not say you can queue it later. Use `replace: true` when the user says regenerate, replace, refresh, or update an existing artifact. For OG/social preview renders, use `attachmentType: "og-image"`; the provider derives the output image and updates `ogImageId`. For deck carousel PDFs use `attachmentType: "carousel"`; for printable post/project PDFs use `attachmentType: "printable"`. If the user asks to attach a generated artifact to another entity, generate the artifact first in the same turn; do not ask whether they mean an existing artifact when the source entity is explicit or given as a quoted id such as deck `distributed-systems-primer`. Update the target only after the real artifact ID exists. To create an entity and a cover image, first create/generate only the entity, then after confirmation and after the real canonical entity ID is known call system_generate with operation.kind cover-image. When the user asks to create/regenerate a cover for an existing entity and search/get resolves a clear target, call system_generate with operation.kind cover-image in the same turn; do not stop after saying you found it. In a single initial request for \'a post with a cover image\', do not also call standalone-image; never guess a future target ID, and do not generate a standalone image as a substitute for a requested cover image.','- **system_update**: Modify an entity\'s fields or content. Use `edits` for small content changes: fetch the entity, then send exact oldText/newText pairs, with each oldText matching once in the original Markdown. Put multiple non-overlapping edits in one call. Do not regenerate the whole note for a small change; omit `content` and `fields` when using `edits`. Never replace unchanged content with placeholders or ellipses. For a whole-document rewrite, when the user supplies the replacement text, use `source: { kind: "user-message", startAfter, endBefore }` with exact unique boundaries (`boundaryMode: "lines"` for delimiter lines) so the server reads it verbatim; never copy pasted text into `content` or long `edits`. Use full `content` only for whole-document replacements you write yourself. Text without frontmatter replaces the body and keeps the stored frontmatter; text with frontmatter replaces the whole document. Use only one of `fields`, `content`, `edits`, or `source`. Use `fields` for title, status, coverImageId, ogImageId, and other frontmatter/metadata changes. To remove or clear a cover image, set `fields.coverImageId` to null, not an empty string. Use system_update for coverImageId when an existing image entity id is known; if the user says to set an existing image as a cover, update `coverImageId` even when `ogImageId` already points at that image. To generate a new cover image for an existing entity, use system_generate with operation.kind cover-image. Cover images use `coverImageId`; OG/social previews use `ogImageId`; do not treat them as interchangeable. Requires confirmation before applying changes; call system_update without `confirmed` to request that confirmation, rather than asking for prose approval. For explicit publish requests, use the publishing tool if available instead of changing status with system_update; follow-up pronouns like \'publish it\' should target the entity just read or updated in the conversation.',"- **system_delete**: Admin-only entity removal. Requires confirmation before deleting. Never pass `confirmed: true` on the initial user request; call without `confirmed` so the confirmation flow can ask an administrator first. If system_delete is not available in the current tool surface, say deletion requires Admin access; do not imply a confirmation flow is available. Protected identity/profile records such as brain-character and anchor-profile cannot be deleted; update them instead.","- **system_get**: Retrieve a specific entity by type and ID/slug/title.","- **system_list**: List entities by type with optional filters. For simple list/show-all/summary requests that name or browse a known type or synonym (for example essays/articles/blog posts => post), use system_list with that entity type instead of semantic search. For 'summarize my blog posts' or similar whole-type summaries, first call system_list for entityType post, then summarize those returned entities. For 'latest' requests, use system_list metadata dates such as publishedAt to choose the newest candidate.","- **system_search**: Semantic search across all entities. Search results include matched entity content; when relevant results already provide the complete evidence needed, answer from them instead of redundantly calling system_list or system_get for those same entities. For each new user question about what they have written, mentioned, discussed, or saved, run a fresh search for that turn instead of answering from prior-turn search results or memory; this includes analysis phrasing such as 'How do I discuss X in my writing?' even if prior turns searched related topics.","","Do not ask for prose confirmation instead of calling the applicable mutating tool; for create, update, delete, generate, publish, sync, and similar state-changing requests, the initial tool call without `confirmed` is how you create the pending confirmation. Never claim a durable create/update/delete change was saved, created, done, or completed unless the relevant tool call succeeded or returned a pending confirmation. If a create/update/delete tool is unavailable, unauthorized, or intentionally not called, say you can't make that durable change from the current context; never say saved/created/done. For an explicit write request from an unauthorized/currently unwritable context, refuse directly; do not call system_status or system_search to check permission or look up related content. Entity type descriptions may mark projection-owned or system-maintained types read-only; refuse mutation requests for those types directly without calling read or write tools, searching for a target, or asking which record to mutate.","","Entity types \u2014 select `entityType` by what the type is for:",...n].join(`
|
|
189
|
-
`)}var Uo="system",WJ=r.object({toolName:r.string(),args:r.unknown(),...FC.partial().shape});function nl(e,t,n,o,i){for(let a of e)try{t(a)}catch{i.debug(`System ${o} ${n(a)} already registered, skipping`)}}function BC(e,t,n,o){let i=DC(e);nl(i,(d)=>t.registerTool(Uo,d),(d)=>d.name,"tool",o);let a=n.subscribe($C.toolExecute(Uo),async(d)=>{let m=WJ.safeParse(d.payload);if(!m.success)return{success:!1,error:"Invalid system tool execute payload"};let{toolName:p,args:f,interfaceType:g,actor:h,conversationId:v,channelId:x,userPermissionLevel:b}=m.data,y=i.find((C)=>C.name===p);if(!y)return{success:!1,error:`System tool not found: ${p}`};let w={interfaceType:g??"system",actor:h??{kind:"service",serviceId:"system"}};if(v)w.conversationId=v;if(x)w.channelId=x;if(b)w.userPermissionLevel=b;return{success:!0,data:await y.handler(f,w)}});o.debug(`Registered ${i.length} system tools`);let s=zC(e);nl(s,(d)=>t.registerResource(Uo,d),(d)=>d.uri,"resource",o),o.debug(`Registered ${s.length} system resources`);let l=UC(e);nl(l,(d)=>t.registerResourceTemplate(Uo,d),(d)=>d.uriTemplate,"resource template",o),o.debug(`Registered ${l.length} system resource templates`);let c=qC(e);nl(c,(d)=>t.registerPrompt(Uo,d),(d)=>d.name,"prompt",o),o.debug(`Registered ${c.length} system prompts`);let u=LC(e);try{t.registerInstructions(Uo,u)}catch{o.debug("System instructions already registered, skipping")}return o.debug("Registered system instructions"),a}function WC(e){let{services:t,jobs:n,insights:o,query:i,getAppInfo:a}=e,s=t.jobQueueService,l=t.logger.child("system"),c=BC({entityService:t.entityService,entityRegistry:t.entityRegistry,jobs:{...n,enqueue:GC(s,"system",!1),enqueueBatch:JC(n,"system"),registerHandler:HC(s,"system")},conversationService:t.conversationService,runtimeUploads:t.runtimeUploadRegistry,attachments:ol(t.attachmentRegistry),logger:l,query:i,getIdentity:()=>t.identityService.getCharacter(),getProfile:()=>t.profileService.getProfile(),getAppInfo:a,searchLimit:10,insights:o,permissionService:t.permissionService},t.mcpService,t.messageBus,l);t.disposables.push(c)}class vp{scope;closePromise=null;closed=!1;constructor(){this.scope=se.runSync(Xe.make())}buildLayer(e){this.assertOpen();let t=se.runSyncExit(Yr.buildWithScope(e,this.scope));if(ot.isFailure(t))throw Pr.squash(t.cause);return t.value}addFinalizer(e){this.assertOpen(),se.runSync(Xe.addFinalizer(this.scope,se.promise(async()=>{await e()})))}addSyncFinalizer(e){this.assertOpen(),se.runSync(Xe.addFinalizer(this.scope,se.sync(()=>{e()})))}async fork(e){if(this.closed)throw Error("Cannot start background work after shell shutdown");await se.runPromise(se.forkIn(e,this.scope))}close(e=ot.void){if(this.closePromise)return this.closePromise;if(this.closed)return Promise.resolve();return this.closed=!0,this.closePromise=se.runPromise(Xe.close(this.scope,e)),this.closePromise}closeSync(e){if(this.closed)return;this.closed=!0,se.runSync(Xe.close(this.scope,e))}assertOpen(){if(this.closed)throw Error("Cannot register cleanup after shell shutdown")}}class oa{config;services;lifecycle;bootloader;initialized=!1;lifecycleState="constructed";bootMode;bootPromise=null;shutdownPromise=null;insightsRegistry;bootTime=Date.now();endpointRegistry=new op;interactionRegistry=new ip;httpRouteRegistry=Fs.createFresh();jobs;static createFresh(e,t,n){return new oa(da(e),t,n)}constructor(e,t,n){this.config=e,this.lifecycle=new vp,QC(this,()=>this.httpRouteRegistry.getSnapshot());let o=t?.logger??fr.getInstance(),i=qs.createFresh(o,this.config,n?.processRole);try{this.services=i.initializeServices(this.lifecycle,t),this.jobs=RI(this.services.batchJobManager,this.services.jobQueueService),this.insightsRegistry=TI(this.services.entityRegistry),this.bootloader=new rp(this.config,this.services,this.lifecycle,i,n?.processRole,{registerCoreDataSources:()=>Op(this.services,this.config),finalizeHttpRoutes:()=>{this.httpRouteRegistry.finalize(PI(this.services.pluginManager))},registerSystemCapabilities:()=>WC({services:this.services,jobs:this.jobs,insights:this.insightsRegistry,query:(a,s)=>this.query(a,s),getAppInfo:()=>this.getAppInfo()}),createProjectionInputContext:()=>({entities:this.services.entityService,resolvePrompt:(a,s)=>pa(this.services.entityService,a,s),appInfo:()=>this.getAppInfo(),identityInput:()=>{let a=this.getIdentity(),s=this.getProfile();return ZC.parse({brainName:a.name,role:a.role,purpose:a.purpose,values:a.values,profileName:s.name,...s.description!==void 0?{profileDescription:s.description}:{},...s.organization!==void 0?{profileOrganization:s.organization}:{}})}}),createProjectionExecutionContext:()=>({ai:KC(this),logger:this.services.logger.child("ProjectionRuntime")}),...t?.projectionRuntime&&{projectionRuntime:t.projectionRuntime}}),i.wireShell(this.services,this),jI(this.lifecycle,this.services)}catch(a){try{this.lifecycle.closeSync(ot.fail(a))}catch(s){o.error("Failed to roll back Shell service construction",s)}throw a}}getInsightsRegistry(){return this.insightsRegistry}async initialize(e){this.services.logger.debug("Shell.initialize() called");let t=e?.mode;if(this.lifecycleState==="running")return this.services.logger.warn("Shell already initialized"),Promise.resolve();if(this.lifecycleState==="booting"){if(this.bootMode!==t)return Promise.reject(Error(`Shell is already initializing in ${this.bootMode??"normal"} mode; cannot join ${t??"normal"} mode`));return this.bootPromise??Promise.resolve()}if(this.lifecycleState==="closing"||this.lifecycleState==="closed")return Promise.reject(Error("Cannot initialize a closing shell"));if(this.lifecycleState==="failed")return Promise.reject(Error("Cannot initialize a shell after boot failure"));return this.lifecycleState="booting",this.bootMode=t,this.bootPromise=this.boot(e),this.bootPromise}async boot(e){try{if(await this.bootloader.boot(e),this.lifecycleState==="booting"){if(this.lifecycleState="running",this.initialized=!0,e?.mode===void 0)await this.services.messageBus.send({type:Do.shellReady,payload:{timestamp:new Date().toISOString()},sender:"shell",broadcast:!0}),this.services.logger.debug("Emitted shell ready event")}}catch(t){if(this.initialized=!1,this.services.logger.error("Failed to initialize Shell",t),this.lifecycleState!=="closing")this.lifecycleState="failed";try{await this.lifecycle.close(ot.fail(t))}catch(n){this.services.logger.error("Failed to clean up Shell after initialization failure",n)}throw t}}registerTemplates(e,t){this.services.logger.debug("Registering templates",{pluginId:t,count:Object.keys(e).length});for(let[n,o]of Object.entries(e))this.registerTemplate(n,o,t)}shutdown(){return this.shutdownPromise??=this.shutdownShell(),this.shutdownPromise}async shutdownShell(){if(this.services.logger.debug("Shutting down Shell"),this.lifecycleState==="closed")return;let e=this.bootPromise;if(this.lifecycleState="closing",this.initialized=!1,e)try{await e}catch{}await this.lifecycle.close(),this.lifecycleState="closed",this.services.logger.debug("Shell shutdown complete")}async generateContent(e){return this.requireInitialized("Shell content generation"),Np(this.services,e)}async query(e,t){this.requireInitialized("Shell query");let n=await this.getAppInfo(),o={...t,appInfo:n,timestamp:new Date().toISOString()},{conversationHistory:i,...a}=o;return VC.parse(await this.generateContent({prompt:e,templateName:Zo.KNOWLEDGE_QUERY,...i&&{conversationHistory:i},data:a,interfacePermissionGrant:"public"}))}registerPlugin(e){this.requireInitialized("Plugin registration"),this.services.pluginManager.registerPlugin(e)}isInitialized(){return this.initialized}requireInitialized(e){if(!this.initialized)throw Error(`${e} attempted before initialization`)}getEntityService(){return this.services.entityService}getConversationService(){return this.services.conversationService}getEntityRegistry(){return this.services.entityRegistry}async generateObject(e,t,n){this.requireInitialized("Shell generateObject");let{object:o}=await this.services.aiService.generateObject("You are a helpful assistant. Respond with the requested structured data.",e,t,n);return{object:o}}async judge(e){return this.requireInitialized("Shell judge"),this.services.aiService.judge(e)}getAIService(){return this.services.aiService}generateImage(e,t){return this.services.aiService.generateImage(e,t)}canGenerateImages(){return this.services.aiService.canGenerateImages()}getPluginManager(){return this.services.pluginManager}getContentService(){return this.services.contentService}getRenderService(){return this.services.renderService}getAttachmentRegistry(){return ol(this.services.attachmentRegistry)}getRuntimeUploadRegistry(){return YC(this.services.runtimeUploadRegistry)}getRuntimeState(){return this.services.runtimeStateService}getRecurringChecks(e){return this.services.recurringCheckService.namespace(e)}isJobQueueWorkerRunning(){return this.services.jobQueueWorker.isWorkerRunning()}getMessageBus(){return this.services.messageBus}getLogger(){return this.services.logger}getJobQueueService(){return this.services.jobQueueService}getMCPService(){return this.services.mcpService}listToolsForPermissionLevel(e){return this.services.mcpService.listToolsForPermissionLevel(e).map(({pluginId:t,tool:n})=>({name:n.name,description:n.description,pluginId:t}))}getPermissionService(){return this.services.permissionService}getAgentService(){return this.services.agentService}registerTools(e,t){for(let n of t)this.services.mcpService.registerTool(e,n)}registerResources(e,t){for(let n of t)this.services.mcpService.registerResource(e,n)}registerResourceTemplate(e,t){this.services.mcpService.registerResourceTemplate(e,t)}registerPrompt(e,t){this.services.mcpService.registerPrompt(e,t)}registerInstructions(e,t){if(this.services.mcpService.registerInstructions(e,t),this.initialized)this.services.agentService.invalidateAgent()}async unregisterPluginCapabilities(e){this.services.mcpService.unregisterPlugin?.(e),this.services.jobQueueService.unregisterPluginHandlers(e),this.endpointRegistry.unregister(e),this.interactionRegistry.unregister(e);for(let n of this.services.templateRegistry.getNames())if(n.startsWith(`${e}:`))this.services.templateRegistry.unregister(n);let t=this.config.evalHandlerRegistry;if(t){for(let n of t.list())if(n.pluginId===e)t.unregister(e,n.handlerId)}this.services.agentService.invalidateAgent(),await this.services.recurringCheckService.unregisterPlugin(e)}getPluginPackageName(e){return this.services.pluginManager.getPluginPackageName(e)}hasPlugin(e){return this.services.pluginManager.hasPlugin(e)}getPluginHttpRouteManifest(){return this.httpRouteRegistry.getManifest()}getPluginApiRoutes(){return this.httpRouteRegistry.getApiRoutes()}getPluginWebRoutes(){return this.httpRouteRegistry.getWebRoutes()}registerDaemon(e,t,n){this.services.daemonRegistry.register(e,t,n)}registerEndpoint(e){this.endpointRegistry.register(e)}listEndpoints(){return this.endpointRegistry.list()}registerInteraction(e){this.interactionRegistry.register(e)}listInteractions(){return this.interactionRegistry.list()}registerTemplate(e,t,n){let o=n?`${n}:${e}`:`shell:${e}`;this.services.templateRegistry.register(o,t),this.services.logger.debug(`Registered template: ${o}`)}getTemplate(e){return this.services.templateRegistry.get(e)}getDataSourceRegistry(){return this.services.dataSourceRegistry}getIdentity(){return this.services.identityService.getCharacter()}getProfile(){return this.services.profileService.getProfile()}getProfileKindRegistry(){return this.services.profileKindRegistry}getChannelRegistry(){return this.services.channelRegistry}getInboxRegistry(){return this.services.inboxRegistry}getInboxFollowUpRegistry(){return this.services.inboxFollowUpRegistry}getOperationalHealthRegistry(){return this.services.operationalHealthRegistry}getAccountSettingsRegistry(){return this.services.accountSettingsRegistry}getDomain(){return this.config.siteBaseUrl}getLocalSiteUrl(){return this.config.localSiteUrl}shouldPreferLocalUrls(){return this.config.preferLocalUrls}getThemeCSS(){return this.config.themeCSS}getSpaces(){return this.config.spaces}getDataDir(){return this.config.dataDir}getGitBrokerSocket(){return this.config.gitBrokerSocket}getGitBrokerCheckout(){return this.config.gitBrokerCheckout}registerEvalHandler(e,t,n){this.config.evalHandlerRegistry?.register(e,t,n)}async getAppInfo(){return Rp({config:this.config,services:this.services,bootTime:this.bootTime,endpoints:()=>this.listEndpoints(),interactions:()=>this.listInteractions()})}getRuntimeReadiness(){return Pp(this.services)}}var XC={kind:"service",serviceId:"brain-cli"},bp=`${XC.kind}:${XC.serviceId}`;var VJ=r.object({provider:r.enum(["hetzner","docker"]).default("hetzner"),serverSize:r.string().default("cx33"),location:r.string().default("fsn1"),domain:r.string().optional(),docker:r.object({enabled:r.boolean().default(!0),image:r.string().optional()}).prefault({}),ports:r.object({default:r.number().default(3333),preview:r.number().default(4321),production:r.number().default(8080)}).prefault({}),cdn:r.object({enabled:r.boolean().default(!1),provider:r.enum(["bunny","none"]).default("none")}).prefault({}),dns:r.object({enabled:r.boolean().default(!1),provider:r.enum(["bunny","none"]).default("none")}).prefault({}),paths:r.object({install:r.string().optional(),data:r.string().optional()}).prefault({})}),t0=r.object({name:r.string().default("brain-app"),version:r.string().default("1.0.0"),database:r.string().optional(),aiApiKey:r.string().optional(),aiImageKey:r.string().optional(),aiModel:r.string().optional(),aiReasoningEffort:Xn.optional(),logLevel:Yn.optional(),logFile:r.string().optional(),profileKind:r.string().trim().min(1).optional(),plugins:r.array(ua).default([]),spaces:r.array(r.string()).default([]),identity:e0.optional(),agentInstructions:r.array(r.string()).optional(),deployment:VJ.prefault({})});async function p0(e,t){await _n({label:"entity",config:e,schema:{assets:n0,entities:r0,entityMutationReceipts:o0,projectionDirtyInputs:i0,projectionWaves:a0,projectionIncidents:s0,projectionWaveInputs:l0,projectionWaveRules:c0,projectionRuleMemos:u0},migrationsFolder:Sn(import.meta.url,"entity-service"),authTokenEnv:"DATABASE_AUTH_TOKEN",logger:t,afterMigrate:d0})}async function f0(e,t){await _n({label:"job-queue",config:e,schema:{jobQueue:m0,jobWorkerSessions:g0},migrationsFolder:Sn(import.meta.url,"job-queue"),authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",logger:t})}async function b0(e,t){await _n({label:"conversation",config:e,schema:{conversations:h0,messages:y0,summaryTracking:v0},migrationsFolder:Sn(import.meta.url,"conversation-service"),authTokenEnv:"CONVERSATION_DATABASE_AUTH_TOKEN",logger:t})}async function _0(e,t){await _n({label:"runtime-state",config:e,schema:{runtimeStateRecords:$e},migrationsFolder:Sn(import.meta.url,"runtime-state"),authTokenEnv:"RUNTIME_STATE_DATABASE_AUTH_TOKEN",logger:t})}import{mkdir as _p}from"fs/promises";import{isAbsolute as ZJ}from"path";function S0(e=process.env){return{dataDir:e.XDG_DATA_HOME??"./data",cacheDir:e.XDG_CACHE_HOME??"./cache",distDir:"./dist"}}function w0(e=process.env){let t=e.BRAIN_GIT_BROKER_CHECKOUT;if(!t)return;if(!ZJ(t))throw Error(`Git broker checkout path must be absolute: ${t}`);return t}function x0(e=process.env){let t=e.BRAIN_GIT_BROKER_SOCKET;if(!t)return;let n=107;if(Buffer.byteLength(t)>n)throw Error(`Git broker socket path is too long for a unix socket (${Buffer.byteLength(t)} > ${n} bytes): ${t}`);return t}function T0(e=process.env){return Tn(S0(e))}async function I0(e=process.env){let t=S0(e);try{await _p(t.dataDir,{recursive:!0}),await _p(t.cacheDir,{recursive:!0}),await _p(t.distDir,{recursive:!0})}catch(n){let o=n instanceof Error&&n.message.includes("EACCES")?`Cannot create data directories \u2014 permission denied. Run from a writable directory or check permissions on ${t.dataDir}`:`Cannot create data directories: ${Ce(n)}`;throw Error(o,{cause:n})}return Tn(t)}class Sp{logger;migrations;constructor(e,t){this.logger=e,this.migrations=t??{getStandardConfigWithDirectories:()=>I0(),migrateEntities:p0,migrateJobQueue:f0,migrateConversations:b0,migrateRuntimeState:_0}}async runAllMigrations(e){this.logger.debug("Running database migrations...");let t=await this.migrations.getStandardConfigWithDirectories();if(e?.database)t.database.url=e.database;if(e?.jobQueueDatabase)t.jobQueueDatabase.url=e.jobQueueDatabase;if(e?.conversationDatabase)t.conversationDatabase.url=e.conversationDatabase;if(e?.runtimeStateDatabase)t.runtimeStateDatabase.url=e.runtimeStateDatabase;await this.migrateEntityDatabase(t),await this.migrateJobQueueDatabase(t),await this.migrateConversationDatabase(t),await this.migrateRuntimeStateDatabase(t),this.logger.debug("All database migrations completed successfully")}async migrateEntityDatabase(e){this.logger.debug("Running entity database migrations..."),await this.migrations.migrateEntities({url:e.database.url,...e.database.authToken&&{authToken:e.database.authToken}},this.logger)}async migrateJobQueueDatabase(e){this.logger.debug("Running job queue database migrations..."),await this.migrations.migrateJobQueue({url:e.jobQueueDatabase.url,...e.jobQueueDatabase.authToken&&{authToken:e.jobQueueDatabase.authToken}},this.logger)}async migrateConversationDatabase(e){this.logger.debug("Running conversation database migrations..."),await this.migrations.migrateConversations({url:e.conversationDatabase.url,...e.conversationDatabase.authToken&&{authToken:e.conversationDatabase.authToken}},this.logger)}async migrateRuntimeStateDatabase(e){this.logger.debug("Running runtime state database migrations..."),await this.migrations.migrateRuntimeState({url:e.runtimeStateDatabase.url,...e.runtimeStateDatabase.authToken&&{authToken:e.runtimeStateDatabase.authToken}},this.logger)}}var KJ="NODE_ENV";function QJ(){return process.env[KJ]}function C0(){return QJ()!=="production"}var YJ="startup-check";function XJ(e){let n={...t0.parse(e??{}),plugins:e?.plugins??[]};if(e?.permissions)n.permissions=e.permissions;if(e?.spaces)n.spaces=e.spaces;if(e?.cliConfig)n.cliConfig=e.cliConfig;if(e?.shellConfig)n.shellConfig=e.shellConfig;return n}function e4(e,t){let n={plugins:e.plugins??[],...e.shellConfig};return t4(n),r4(e,n),n4(e,n,t),o4(e,n),i4(e,n),a4(e,n),s4(e,n),l4(e,n),c4(e,n),n}function t4(e){let t=T0();e.database??=t.database,e.jobQueueDatabase??=t.jobQueueDatabase,e.conversationDatabase??=t.conversationDatabase,e.runtimeStateDatabase??=t.runtimeStateDatabase,e.embeddingDatabase??=t.embeddingDatabase,e.embedding??=t.embedding,e.gitBrokerSocket??=x0(),e.gitBrokerCheckout??=w0()}function r4(e,t){if(e.database)t.database={url:e.database};if(e.profileKind)t.profileKind=e.profileKind;t.features={}}function n4(e,t,n){let o=n?.mode==="startup-check";if(!e.aiApiKey&&!e.aiImageKey&&!e.aiModel&&!e.aiReasoningEffort&&!o)return;t.ai={...t.ai,...o&&!t.ai?.apiKey&&{apiKey:YJ},...e.aiApiKey&&{apiKey:e.aiApiKey},...e.aiImageKey&&{imageApiKey:e.aiImageKey},...e.aiModel&&{model:e.aiModel},...e.aiReasoningEffort&&{reasoningEffort:e.aiReasoningEffort}}}function o4(e,t){if(!e.logLevel&&!e.logFile)return;t.logging={level:e.logLevel??"info",format:"text",context:e.name,...e.logFile&&{file:e.logFile}}}function i4(e,t){let n=e.permissions?.rules??[];t.permissions={...e.permissions,rules:n.some((o)=>o.pattern===bp)?n:[{pattern:bp,level:"admin"},...n]}}function a4(e,t){if(e.spaces)t.spaces=e.spaces}function s4(e,t){if(e.identity)t.identity=e.identity}function l4(e,t){if(e.agentInstructions)t.agentInstructions=e.agentInstructions}function c4(e,t){if(t.name=e.name,t.version=e.version,e.deployment.domain)t.siteBaseUrl=e.deployment.domain;t.localSiteUrl=`http://localhost:${e.deployment.ports.production}`,t.preferLocalUrls=C0()}class xp{shell=null;config;signalScope=null;signalShutdownFiber=null;stopPromise=null;hasCLI=!1;static create(e,t){return new xp(XJ(e),t)}constructor(e,t){if(this.config=e,this.hasCLI=process.argv.slice(2).includes("--cli"),t)this.shell=t}async migrate(){let e=fr.getInstance();await new Sp(e).runAllMigrations({database:this.config.shellConfig?.database?.url??this.config.database,jobQueueDatabase:this.config.shellConfig?.jobQueueDatabase?.url,conversationDatabase:this.config.shellConfig?.conversationDatabase?.url,runtimeStateDatabase:this.config.shellConfig?.runtimeStateDatabase?.url})}createShell(e,t){this.shell=oa.createFresh(e4(this.config,e),void 0,{...t&&{processRole:t}})}async registerCLIInterface(){if(!this.hasCLI)return;let e=this.getShell().getPluginManager(),{CLIInterface:t}=await import("./index-a5na8p4p.js"),n=new t(this.config.cliConfig);e.registerPlugin(n)}async initialize(e,t){if(!this.shell){if(!t?.migrationsCompleted)await this.migrate();this.createShell(e,t?.processRole)}await this.registerCLIInterface(),await this.getShell().initialize(e)}async start(){if(this.stopPromise)return;this.setupSignalHandlers()}stop(){return this.stopPromise??=this.stopApp(),this.stopPromise}async stopApp(){await this.closeSignalScope(),await this.shell?.shutdown()}async run(e){let n={debug:qt.DEBUG,info:qt.INFO,warn:qt.WARN,error:qt.ERROR}[this.config.logLevel??"info"]??qt.INFO,o=fr.createFresh({level:n,context:this.config.name,useStderr:this.hasCLI});if(this.hasCLI)fr.getInstance().setUseStderr(!0);try{await this.initialize(void 0,e),await this.start(),e?.onRuntimeReady?.(),o.info(`\u2705 ${this.config.name} v${this.config.version} ready`),process.stdin.resume()}catch(i){o.error(`\u274C Failed to start ${this.config.name}:`,i),process.exit(1)}}static async run(e,t,n){await xp.create(e,t).run(n)}setupSignalHandlers(){if(this.signalScope)return;let e=se.runSync(Xe.make()),t=()=>{this.requestGracefulShutdown("SIGINT")},n=()=>{this.requestGracefulShutdown("SIGTERM")},o=wp(["SIGINT"],t),i=wp(["SIGTERM"],n);se.runSync(Xe.addFinalizer(e,se.sync(()=>{i(),o()}))),this.signalScope=e}requestGracefulShutdown(e){if(this.signalShutdownFiber)return;let t=fr.getInstance();t.info(`
|
|
189
|
+
`)}var Uo="system",WJ=r.object({toolName:r.string(),args:r.unknown(),...FC.partial().shape});function nl(e,t,n,o,i){for(let a of e)try{t(a)}catch{i.debug(`System ${o} ${n(a)} already registered, skipping`)}}function BC(e,t,n,o){let i=DC(e);nl(i,(d)=>t.registerTool(Uo,d),(d)=>d.name,"tool",o);let a=n.subscribe($C.toolExecute(Uo),async(d)=>{let m=WJ.safeParse(d.payload);if(!m.success)return{success:!1,error:"Invalid system tool execute payload"};let{toolName:p,args:f,interfaceType:g,actor:h,conversationId:v,channelId:x,userPermissionLevel:b}=m.data,y=i.find((C)=>C.name===p);if(!y)return{success:!1,error:`System tool not found: ${p}`};let w={interfaceType:g??"system",actor:h??{kind:"service",serviceId:"system"}};if(v)w.conversationId=v;if(x)w.channelId=x;if(b)w.userPermissionLevel=b;return{success:!0,data:await y.handler(f,w)}});o.debug(`Registered ${i.length} system tools`);let s=zC(e);nl(s,(d)=>t.registerResource(Uo,d),(d)=>d.uri,"resource",o),o.debug(`Registered ${s.length} system resources`);let l=UC(e);nl(l,(d)=>t.registerResourceTemplate(Uo,d),(d)=>d.uriTemplate,"resource template",o),o.debug(`Registered ${l.length} system resource templates`);let c=qC(e);nl(c,(d)=>t.registerPrompt(Uo,d),(d)=>d.name,"prompt",o),o.debug(`Registered ${c.length} system prompts`);let u=LC(e);try{t.registerInstructions(Uo,u)}catch{o.debug("System instructions already registered, skipping")}return o.debug("Registered system instructions"),a}function WC(e){let{services:t,jobs:n,insights:o,query:i,getAppInfo:a}=e,s=t.jobQueueService,l=t.logger.child("system"),c=BC({entityService:t.entityService,entityRegistry:t.entityRegistry,jobs:{...n,enqueue:GC(s,"system",!1),enqueueBatch:JC(n,"system"),registerHandler:HC(s,"system")},conversationService:t.conversationService,runtimeUploads:t.runtimeUploadRegistry,attachments:ol(t.attachmentRegistry),logger:l,query:i,getIdentity:()=>t.identityService.getCharacter(),getProfile:()=>t.profileService.getProfile(),getAppInfo:a,searchLimit:10,insights:o,permissionService:t.permissionService},t.mcpService,t.messageBus,l);t.disposables.push(c)}class vp{scope;closePromise=null;closed=!1;constructor(){this.scope=se.runSync(Xe.make())}buildLayer(e){this.assertOpen();let t=se.runSyncExit(Yr.buildWithScope(e,this.scope));if(ot.isFailure(t))throw Pr.squash(t.cause);return t.value}addFinalizer(e){this.assertOpen(),se.runSync(Xe.addFinalizer(this.scope,se.promise(async()=>{await e()})))}addSyncFinalizer(e){this.assertOpen(),se.runSync(Xe.addFinalizer(this.scope,se.sync(()=>{e()})))}async fork(e){if(this.closed)throw Error("Cannot start background work after shell shutdown");await se.runPromise(se.forkIn(e,this.scope))}close(e=ot.void){if(this.closePromise)return this.closePromise;if(this.closed)return Promise.resolve();return this.closed=!0,this.closePromise=se.runPromise(Xe.close(this.scope,e)),this.closePromise}closeSync(e){if(this.closed)return;this.closed=!0,se.runSync(Xe.close(this.scope,e))}assertOpen(){if(this.closed)throw Error("Cannot register cleanup after shell shutdown")}}class oa{config;services;lifecycle;bootloader;initialized=!1;lifecycleState="constructed";bootMode;bootPromise=null;shutdownPromise=null;insightsRegistry;bootTime=Date.now();endpointRegistry=new op;interactionRegistry=new ip;httpRouteRegistry=Fs.createFresh();jobs;static createFresh(e,t,n){return new oa(da(e),t,n)}constructor(e,t,n){this.config=e,this.lifecycle=new vp,QC(this,()=>this.httpRouteRegistry.getSnapshot());let o=t?.logger??fr.getInstance(),i=qs.createFresh(o,this.config,n?.processRole);try{this.services=i.initializeServices(this.lifecycle,t),this.jobs=RI(this.services.batchJobManager,this.services.jobQueueService),this.insightsRegistry=TI(this.services.entityRegistry),this.bootloader=new rp(this.config,this.services,this.lifecycle,i,n?.processRole,{registerCoreDataSources:()=>Op(this.services,this.config),finalizeHttpRoutes:()=>{this.httpRouteRegistry.finalize(PI(this.services.pluginManager))},registerSystemCapabilities:()=>WC({services:this.services,jobs:this.jobs,insights:this.insightsRegistry,query:(a,s)=>this.query(a,s),getAppInfo:()=>this.getAppInfo()}),createProjectionInputContext:()=>({entities:this.services.entityService,resolvePrompt:(a,s)=>pa(this.services.entityService,a,s),appInfo:()=>this.getAppInfo(),identityInput:()=>{let a=this.getIdentity(),s=this.getProfile();return ZC.parse({brainName:a.name,role:a.role,purpose:a.purpose,values:a.values,profileName:s.name,...s.description!==void 0?{profileDescription:s.description}:{},...s.organization!==void 0?{profileOrganization:s.organization}:{}})}}),createProjectionExecutionContext:()=>({ai:KC(this),logger:this.services.logger.child("ProjectionRuntime")}),...t?.projectionRuntime&&{projectionRuntime:t.projectionRuntime}}),i.wireShell(this.services,this),jI(this.lifecycle,this.services)}catch(a){try{this.lifecycle.closeSync(ot.fail(a))}catch(s){o.error("Failed to roll back Shell service construction",s)}throw a}}getInsightsRegistry(){return this.insightsRegistry}async initialize(e){this.services.logger.debug("Shell.initialize() called");let t=e?.mode;if(this.lifecycleState==="running")return this.services.logger.warn("Shell already initialized"),Promise.resolve();if(this.lifecycleState==="booting"){if(this.bootMode!==t)return Promise.reject(Error(`Shell is already initializing in ${this.bootMode??"normal"} mode; cannot join ${t??"normal"} mode`));return this.bootPromise??Promise.resolve()}if(this.lifecycleState==="closing"||this.lifecycleState==="closed")return Promise.reject(Error("Cannot initialize a closing shell"));if(this.lifecycleState==="failed")return Promise.reject(Error("Cannot initialize a shell after boot failure"));return this.lifecycleState="booting",this.bootMode=t,this.bootPromise=this.boot(e),this.bootPromise}async boot(e){try{if(await this.bootloader.boot(e),this.lifecycleState==="booting"){if(this.lifecycleState="running",this.initialized=!0,e?.mode===void 0)await this.services.messageBus.send({type:Do.shellReady,payload:{timestamp:new Date().toISOString()},sender:"shell",broadcast:!0}),this.services.logger.debug("Emitted shell ready event")}}catch(t){if(this.initialized=!1,this.services.logger.error("Failed to initialize Shell",t),this.lifecycleState!=="closing")this.lifecycleState="failed";try{await this.lifecycle.close(ot.fail(t))}catch(n){this.services.logger.error("Failed to clean up Shell after initialization failure",n)}throw t}}registerTemplates(e,t){this.services.logger.debug("Registering templates",{pluginId:t,count:Object.keys(e).length});for(let[n,o]of Object.entries(e))this.registerTemplate(n,o,t)}shutdown(){return this.shutdownPromise??=this.shutdownShell(),this.shutdownPromise}async shutdownShell(){if(this.services.logger.debug("Shutting down Shell"),this.lifecycleState==="closed")return;let e=this.bootPromise;if(this.lifecycleState="closing",this.initialized=!1,e)try{await e}catch{}await this.lifecycle.close(),this.lifecycleState="closed",this.services.logger.debug("Shell shutdown complete")}async generateContent(e){return this.requireInitialized("Shell content generation"),Np(this.services,e)}async query(e,t){this.requireInitialized("Shell query");let n=await this.getAppInfo(),o={...t,appInfo:n,timestamp:new Date().toISOString()},{conversationHistory:i,...a}=o;return VC.parse(await this.generateContent({prompt:e,templateName:Zo.KNOWLEDGE_QUERY,...i&&{conversationHistory:i},data:a,interfacePermissionGrant:"public"}))}registerPlugin(e){this.requireInitialized("Plugin registration"),this.services.pluginManager.registerPlugin(e)}isInitialized(){return this.initialized}requireInitialized(e){if(!this.initialized)throw Error(`${e} attempted before initialization`)}getEntityService(){return this.services.entityService}getConversationService(){return this.services.conversationService}getEntityRegistry(){return this.services.entityRegistry}async generateObject(e,t,n){this.requireInitialized("Shell generateObject");let{object:o}=await this.services.aiService.generateObject("You are a helpful assistant. Respond with the requested structured data.",e,t,n);return{object:o}}async judge(e){return this.requireInitialized("Shell judge"),this.services.aiService.judge(e)}getAIService(){return this.services.aiService}generateImage(e,t){return this.services.aiService.generateImage(e,t)}canGenerateImages(){return this.services.aiService.canGenerateImages()}getPluginManager(){return this.services.pluginManager}getContentService(){return this.services.contentService}getRenderService(){return this.services.renderService}getAttachmentRegistry(){return ol(this.services.attachmentRegistry)}getRuntimeUploadRegistry(){return YC(this.services.runtimeUploadRegistry)}getRuntimeState(){return this.services.runtimeStateService}getRecurringChecks(e){return this.services.recurringCheckService.namespace(e)}isJobQueueWorkerRunning(){return this.services.jobQueueWorker.isWorkerRunning()}getMessageBus(){return this.services.messageBus}getLogger(){return this.services.logger}getJobQueueService(){return this.services.jobQueueService}getMCPService(){return this.services.mcpService}listToolsForPermissionLevel(e){return this.services.mcpService.listToolsForPermissionLevel(e).map(({pluginId:t,tool:n})=>({name:n.name,description:n.description,pluginId:t}))}getPermissionService(){return this.services.permissionService}getAgentService(){return this.services.agentService}registerTools(e,t){for(let n of t)this.services.mcpService.registerTool(e,n)}registerResources(e,t){for(let n of t)this.services.mcpService.registerResource(e,n)}registerResourceTemplate(e,t){this.services.mcpService.registerResourceTemplate(e,t)}registerPrompt(e,t){this.services.mcpService.registerPrompt(e,t)}registerInstructions(e,t){if(this.services.mcpService.registerInstructions(e,t),this.initialized)this.services.agentService.invalidateAgent()}async unregisterPluginCapabilities(e){this.services.mcpService.unregisterPlugin?.(e),this.services.jobQueueService.unregisterPluginHandlers(e),this.endpointRegistry.unregister(e),this.interactionRegistry.unregister(e);for(let n of this.services.templateRegistry.getNames())if(n.startsWith(`${e}:`))this.services.templateRegistry.unregister(n);let t=this.config.evalHandlerRegistry;if(t){for(let n of t.list())if(n.pluginId===e)t.unregister(e,n.handlerId)}this.services.agentService.invalidateAgent(),await this.services.recurringCheckService.unregisterPlugin(e)}getPluginPackageName(e){return this.services.pluginManager.getPluginPackageName(e)}hasPlugin(e){return this.services.pluginManager.hasPlugin(e)}getPluginHttpRouteManifest(){return this.httpRouteRegistry.getManifest()}getPluginApiRoutes(){return this.httpRouteRegistry.getApiRoutes()}getPluginWebRoutes(){return this.httpRouteRegistry.getWebRoutes()}registerDaemon(e,t,n){this.services.daemonRegistry.register(e,t,n)}registerEndpoint(e){this.endpointRegistry.register(e)}listEndpoints(){return this.endpointRegistry.list()}registerInteraction(e){this.interactionRegistry.register(e)}listInteractions(){return this.interactionRegistry.list()}registerTemplate(e,t,n){let o=n?`${n}:${e}`:`shell:${e}`;this.services.templateRegistry.register(o,t),this.services.logger.debug(`Registered template: ${o}`)}getTemplate(e){return this.services.templateRegistry.get(e)}getDataSourceRegistry(){return this.services.dataSourceRegistry}getIdentity(){return this.services.identityService.getCharacter()}getProfile(){return this.services.profileService.getProfile()}getProfileKindRegistry(){return this.services.profileKindRegistry}getChannelRegistry(){return this.services.channelRegistry}getInboxRegistry(){return this.services.inboxRegistry}getInboxFollowUpRegistry(){return this.services.inboxFollowUpRegistry}getOperationalHealthRegistry(){return this.services.operationalHealthRegistry}getAccountSettingsRegistry(){return this.services.accountSettingsRegistry}getDomain(){return this.config.siteBaseUrl}getLocalSiteUrl(){return this.config.localSiteUrl}shouldPreferLocalUrls(){return this.config.preferLocalUrls}getThemeCSS(){return this.config.themeCSS}getSpaces(){return this.config.spaces}getDataDir(){return this.config.dataDir}getGitBrokerSocket(){return this.config.gitBrokerSocket}getGitBrokerCheckout(){return this.config.gitBrokerCheckout}registerEvalHandler(e,t,n){this.config.evalHandlerRegistry?.register(e,t,n)}async getAppInfo(){return Rp({config:this.config,services:this.services,bootTime:this.bootTime,endpoints:()=>this.listEndpoints(),interactions:()=>this.listInteractions()})}getRuntimeReadiness(){return Pp(this.services)}}var XC={kind:"service",serviceId:"brain-cli"},bp=`${XC.kind}:${XC.serviceId}`;var VJ=r.object({provider:r.enum(["hetzner","docker"]).default("hetzner"),serverSize:r.string().default("cx33"),location:r.string().default("fsn1"),domain:r.string().optional(),docker:r.object({enabled:r.boolean().default(!0),image:r.string().optional()}).prefault({}),ports:r.object({default:r.number().default(3333),preview:r.number().default(4321),production:r.number().default(8080)}).prefault({}),cdn:r.object({enabled:r.boolean().default(!1),provider:r.enum(["bunny","none"]).default("none")}).prefault({}),dns:r.object({enabled:r.boolean().default(!1),provider:r.enum(["bunny","none"]).default("none")}).prefault({}),paths:r.object({install:r.string().optional(),data:r.string().optional()}).prefault({})}),t0=r.object({name:r.string().default("brain-app"),version:r.string().default("1.0.0"),database:r.string().optional(),aiApiKey:r.string().optional(),aiImageKey:r.string().optional(),aiModel:r.string().optional(),aiReasoningEffort:Xn.optional(),logLevel:Yn.optional(),logFile:r.string().optional(),profileKind:r.string().trim().min(1).optional(),plugins:r.array(ua).default([]),spaces:r.array(r.string()).default([]),identity:e0.optional(),agentInstructions:r.array(r.string()).optional(),deployment:VJ.prefault({})});async function p0(e,t){await _n({label:"entity",config:e,schema:{assets:n0,entities:r0,entityMutationReceipts:o0,projectionDirtyInputs:i0,projectionWaves:a0,projectionIncidents:s0,projectionWaveInputs:l0,projectionWaveRules:c0,projectionRuleMemos:u0},migrationsFolder:Sn(import.meta.url,"entity-service"),authTokenEnv:"DATABASE_AUTH_TOKEN",logger:t,afterMigrate:d0})}async function f0(e,t){await _n({label:"job-queue",config:e,schema:{jobQueue:m0,jobWorkerSessions:g0},migrationsFolder:Sn(import.meta.url,"job-queue"),authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",logger:t})}async function b0(e,t){await _n({label:"conversation",config:e,schema:{conversations:h0,messages:y0,summaryTracking:v0},migrationsFolder:Sn(import.meta.url,"conversation-service"),authTokenEnv:"CONVERSATION_DATABASE_AUTH_TOKEN",logger:t})}async function _0(e,t){await _n({label:"runtime-state",config:e,schema:{runtimeStateRecords:$e},migrationsFolder:Sn(import.meta.url,"runtime-state"),authTokenEnv:"RUNTIME_STATE_DATABASE_AUTH_TOKEN",logger:t})}import{mkdir as _p}from"fs/promises";import{isAbsolute as ZJ}from"path";function S0(e=process.env){return{dataDir:e.XDG_DATA_HOME??"./data",cacheDir:e.XDG_CACHE_HOME??"./cache",distDir:"./dist"}}function w0(e=process.env){let t=e.BRAIN_GIT_BROKER_CHECKOUT;if(!t)return;if(!ZJ(t))throw Error(`Git broker checkout path must be absolute: ${t}`);return t}function x0(e=process.env){let t=e.BRAIN_GIT_BROKER_SOCKET;if(!t)return;let n=107;if(Buffer.byteLength(t)>n)throw Error(`Git broker socket path is too long for a unix socket (${Buffer.byteLength(t)} > ${n} bytes): ${t}`);return t}function T0(e=process.env){return Tn(S0(e))}async function I0(e=process.env){let t=S0(e);try{await _p(t.dataDir,{recursive:!0}),await _p(t.cacheDir,{recursive:!0}),await _p(t.distDir,{recursive:!0})}catch(n){let o=n instanceof Error&&n.message.includes("EACCES")?`Cannot create data directories \u2014 permission denied. Run from a writable directory or check permissions on ${t.dataDir}`:`Cannot create data directories: ${Ce(n)}`;throw Error(o,{cause:n})}return Tn(t)}class Sp{logger;migrations;constructor(e,t){this.logger=e,this.migrations=t??{getStandardConfigWithDirectories:()=>I0(),migrateEntities:p0,migrateJobQueue:f0,migrateConversations:b0,migrateRuntimeState:_0}}async runAllMigrations(e){this.logger.debug("Running database migrations...");let t=await this.migrations.getStandardConfigWithDirectories();if(e?.database)t.database.url=e.database;if(e?.jobQueueDatabase)t.jobQueueDatabase.url=e.jobQueueDatabase;if(e?.conversationDatabase)t.conversationDatabase.url=e.conversationDatabase;if(e?.runtimeStateDatabase)t.runtimeStateDatabase.url=e.runtimeStateDatabase;await this.migrateEntityDatabase(t),await this.migrateJobQueueDatabase(t),await this.migrateConversationDatabase(t),await this.migrateRuntimeStateDatabase(t),this.logger.debug("All database migrations completed successfully")}async migrateEntityDatabase(e){this.logger.debug("Running entity database migrations..."),await this.migrations.migrateEntities({url:e.database.url,...e.database.authToken&&{authToken:e.database.authToken}},this.logger)}async migrateJobQueueDatabase(e){this.logger.debug("Running job queue database migrations..."),await this.migrations.migrateJobQueue({url:e.jobQueueDatabase.url,...e.jobQueueDatabase.authToken&&{authToken:e.jobQueueDatabase.authToken}},this.logger)}async migrateConversationDatabase(e){this.logger.debug("Running conversation database migrations..."),await this.migrations.migrateConversations({url:e.conversationDatabase.url,...e.conversationDatabase.authToken&&{authToken:e.conversationDatabase.authToken}},this.logger)}async migrateRuntimeStateDatabase(e){this.logger.debug("Running runtime state database migrations..."),await this.migrations.migrateRuntimeState({url:e.runtimeStateDatabase.url,...e.runtimeStateDatabase.authToken&&{authToken:e.runtimeStateDatabase.authToken}},this.logger)}}var KJ="NODE_ENV";function QJ(){return process.env[KJ]}function C0(){return QJ()!=="production"}var YJ="startup-check";function XJ(e){let n={...t0.parse(e??{}),plugins:e?.plugins??[]};if(e?.permissions)n.permissions=e.permissions;if(e?.spaces)n.spaces=e.spaces;if(e?.cliConfig)n.cliConfig=e.cliConfig;if(e?.shellConfig)n.shellConfig=e.shellConfig;return n}function e4(e,t){let n={plugins:e.plugins??[],...e.shellConfig};return t4(n),r4(e,n),n4(e,n,t),o4(e,n),i4(e,n),a4(e,n),s4(e,n),l4(e,n),c4(e,n),n}function t4(e){let t=T0();e.database??=t.database,e.jobQueueDatabase??=t.jobQueueDatabase,e.conversationDatabase??=t.conversationDatabase,e.runtimeStateDatabase??=t.runtimeStateDatabase,e.embeddingDatabase??=t.embeddingDatabase,e.embedding??=t.embedding,e.gitBrokerSocket??=x0(),e.gitBrokerCheckout??=w0()}function r4(e,t){if(e.database)t.database={url:e.database};if(e.profileKind)t.profileKind=e.profileKind;t.features={}}function n4(e,t,n){let o=n?.mode==="startup-check";if(!e.aiApiKey&&!e.aiImageKey&&!e.aiModel&&!e.aiReasoningEffort&&!o)return;t.ai={...t.ai,...o&&!t.ai?.apiKey&&{apiKey:YJ},...e.aiApiKey&&{apiKey:e.aiApiKey},...e.aiImageKey&&{imageApiKey:e.aiImageKey},...e.aiModel&&{model:e.aiModel},...e.aiReasoningEffort&&{reasoningEffort:e.aiReasoningEffort}}}function o4(e,t){if(!e.logLevel&&!e.logFile)return;t.logging={level:e.logLevel??"info",format:"text",context:e.name,...e.logFile&&{file:e.logFile}}}function i4(e,t){let n=e.permissions?.rules??[];t.permissions={...e.permissions,rules:n.some((o)=>o.pattern===bp)?n:[{pattern:bp,level:"admin"},...n]}}function a4(e,t){if(e.spaces)t.spaces=e.spaces}function s4(e,t){if(e.identity)t.identity=e.identity}function l4(e,t){if(e.agentInstructions)t.agentInstructions=e.agentInstructions}function c4(e,t){if(t.name=e.name,t.version=e.version,e.deployment.domain)t.siteBaseUrl=e.deployment.domain;t.localSiteUrl=`http://localhost:${e.deployment.ports.production}`,t.preferLocalUrls=C0()}class xp{shell=null;config;signalScope=null;signalShutdownFiber=null;stopPromise=null;hasCLI=!1;static create(e,t){return new xp(XJ(e),t)}constructor(e,t){if(this.config=e,this.hasCLI=process.argv.slice(2).includes("--cli"),t)this.shell=t}async migrate(){let e=fr.getInstance();await new Sp(e).runAllMigrations({database:this.config.shellConfig?.database?.url??this.config.database,jobQueueDatabase:this.config.shellConfig?.jobQueueDatabase?.url,conversationDatabase:this.config.shellConfig?.conversationDatabase?.url,runtimeStateDatabase:this.config.shellConfig?.runtimeStateDatabase?.url})}createShell(e,t){this.shell=oa.createFresh(e4(this.config,e),void 0,{...t&&{processRole:t}})}async registerCLIInterface(){if(!this.hasCLI)return;let e=this.getShell().getPluginManager(),{CLIInterface:t}=await import("./index-r6a0hpn8.js"),n=new t(this.config.cliConfig);e.registerPlugin(n)}async initialize(e,t){if(!this.shell){if(!t?.migrationsCompleted)await this.migrate();this.createShell(e,t?.processRole)}await this.registerCLIInterface(),await this.getShell().initialize(e)}async start(){if(this.stopPromise)return;this.setupSignalHandlers()}stop(){return this.stopPromise??=this.stopApp(),this.stopPromise}async stopApp(){await this.closeSignalScope(),await this.shell?.shutdown()}async run(e){let n={debug:qt.DEBUG,info:qt.INFO,warn:qt.WARN,error:qt.ERROR}[this.config.logLevel??"info"]??qt.INFO,o=fr.createFresh({level:n,context:this.config.name,useStderr:this.hasCLI});if(this.hasCLI)fr.getInstance().setUseStderr(!0);try{await this.initialize(void 0,e),await this.start(),e?.onRuntimeReady?.(),o.info(`\u2705 ${this.config.name} v${this.config.version} ready`),process.stdin.resume()}catch(i){o.error(`\u274C Failed to start ${this.config.name}:`,i),process.exit(1)}}static async run(e,t,n){await xp.create(e,t).run(n)}setupSignalHandlers(){if(this.signalScope)return;let e=se.runSync(Xe.make()),t=()=>{this.requestGracefulShutdown("SIGINT")},n=()=>{this.requestGracefulShutdown("SIGTERM")},o=wp(["SIGINT"],t),i=wp(["SIGTERM"],n);se.runSync(Xe.addFinalizer(e,se.sync(()=>{i(),o()}))),this.signalScope=e}requestGracefulShutdown(e){if(this.signalShutdownFiber)return;let t=fr.getInstance();t.info(`
|
|
190
190
|
Received ${e}, shutting down gracefully...`);let n=se.tryPromise({try:()=>this.stop(),catch:(o)=>o}).pipe(se.match({onFailure:(o)=>{t.error("Error during shutdown:",o),process.exit(1)},onSuccess:()=>{process.exit(0)}}));this.signalShutdownFiber=se.runFork(n)}async closeSignalScope(){let e=this.signalScope;if(this.signalScope=null,e)await se.runPromise(Xe.close(e,ot.void))}getShell(){if(!this.shell)throw Error("Shell not initialized. Call initialize() first.");return this.shell}}
|
|
191
191
|
export{Yn as S,Xn as T,xO as U,Q6 as V,ue as W,pI as X,ra as Y,sC as Z,uC as _,Ys as $,IJ as aa,up as ba,kJ as ca,Xs as da,RJ as ea,yre as fa,vC as ga,PJ as ha,pp as ia,mp as ja,MJ as ka,jJ as la,OJ as ma,YJ as na,XJ as oa,e4 as pa,xp as qa};
|
|
192
192
|
|
|
193
193
|
//# debugId=77FB268EA83634C464756E2164756E21
|
|
194
|
-
//# sourceMappingURL=index-
|
|
194
|
+
//# sourceMappingURL=index-1af7q36h.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{S as c,T as y}from"./index-
|
|
2
|
+
import{S as c,T as y}from"./index-1af7q36h.js";import{Cl as R,Vl as z,do as a}from"./index-5bq8yawt.js";import{bq as i}from"./index-pzx4w8bw.js";import{gt as l,ht as h,it as C,wq as e}from"./index-q9w9db40.js";function _(t,n={}){if(!a(t))throw Error("use() expects a package definition returned by a @rizom/brain define helper");return Object.freeze({kind:"rizom-configured-plugin",definition:t,config:Object.freeze({...n})})}function O(t){if(t===null||typeof t!=="object")return!1;return Reflect.get(t,"kind")==="rizom-configured-plugin"&&a(Reflect.get(t,"definition"))&&typeof Reflect.get(t,"config")==="object"}var Ee=e.array(e.string()),Ie=e.record(e.string(),e.unknown()),Ae=e.unknown();var Be=e.enum(["eval"]),p=e.enum(["person","team","organization"]);function K(t){if(t.bundleContract?.trim().length===0)throw Error("Brain bundleContract must not be empty");return t}function f(t){if(Array.isArray(t))return t.map((n)=>f(n));if(i(t))return Object.fromEntries(Object.entries(t).map(([n,o])=>[n,f(o)]));return t}function u(t){return f(t)}var r=e.string().min(1),V=e.strictObject({member:r,value:e.record(e.string(),e.unknown()),overrides:r.optional()}),G=e.custom(i,{message:"Expected an opaque permission config object"}),q=e.strictObject({member:r,config:G,overrides:r.optional()}),U=e.strictObject({id:r,members:e.array(r),config:e.array(V).optional(),permissions:e.array(q).optional(),agentInstructions:e.array(e.string().min(1)).optional(),evalDisable:e.array(r).optional()});function E(t,n,o,Z){let w=new Set;for(let[j,g]of t.entries()){if(w.has(g))Z.addIssue({code:e.ZodIssueCode.custom,message:`Duplicate ${n} "${g}"`,path:[o,j]});w.add(g)}}var H=U.superRefine((t,n)=>{E(t.members,"member","members",n),E(t.evalDisable??[],"eval exclusion","evalDisable",n)});function I(t){return u(H.parse(t))}function J(t){if(t===void 0)return[];return Array.isArray(t)?t:[t]}var W=e.record(e.string(),e.unknown()),ut=e.record(e.string(),e.unknown()),Y=e.enum(["eval"]),Q=l,s=h,X=e.strictObject({create:s.optional(),update:s.optional(),delete:s.optional(),extract:s.optional(),publish:s.optional()}),ee=e.record(e.string(),X),A=W.superRefine((t,n)=>{if(typeof t.package!=="string")return;n.addIssue({code:"custom",message:'"package" uses the removed alpha external-plugin contract. Default-export a declarative package definition from a @rizom/brain define helper and compose it with use() in defineBrain().'})}),mt=e.strictObject({brain:e.string().optional(),bundleContract:e.string().trim().min(1).optional(),anchor:p.optional(),site:e.object({package:e.string().optional(),variant:e.string().optional(),theme:e.string().optional(),themeOverride:e.string().optional()}).optional(),name:e.string().optional(),kind:e.string().trim().min(1).optional(),logLevel:c.optional(),logFile:e.string().optional(),port:e.number().optional(),domain:e.string().optional(),database:e.string().optional(),embedding:e.strictObject({enabled:e.boolean().optional()}).optional(),model:e.string().optional(),reasoningEffort:y.optional(),bundles:e.array(e.string().min(1)).optional(),mode:Y.optional(),add:e.array(e.string()).optional(),remove:e.array(e.string()).optional(),admins:e.array(e.string()).optional(),anchors:e.array(e.string()).optional(),trusted:e.array(e.string()).optional(),spaces:e.array(e.string()).optional(),plugins:e.record(e.string(),A).optional(),permissions:e.object({admins:e.array(e.string()).optional(),anchors:e.array(e.string()).optional(),trusted:e.array(e.string()).optional(),rules:e.array(e.object({pattern:e.string(),level:Q})).optional(),entityActions:ee.optional()}).optional()});var Pt=e.record(e.string(),e.unknown());var ne=e.strictObject({pattern:e.string(),level:l}),Et=e.strictObject({admins:e.array(e.string()).optional(),anchors:e.array(e.string()).optional(),trusted:e.array(e.string()).optional(),rules:e.array(ne).optional(),entityActions:C.optional()});var D=`/* ============================================
|
|
3
3
|
THEME BASE - Shared utilities for all themes
|
|
4
4
|
============================================
|
|
5
5
|
This file contains CSS that is IDENTICAL across all themes.
|
|
@@ -528,4 +528,4 @@ import{S as c,T as y}from"./index-390n8ge8.js";import{Cl as R,Vl as z,do as a}fr
|
|
|
528
528
|
`+t}var B=e.custom((t)=>z.safeParse(t).success),se=e.custom((t)=>{if(!i(t))return!1;let{plugin:n,...o}=t;if(n!==void 0&&typeof n!=="function")return!1;return R.safeParse(o).success});var ce=e.looseObject({id:e.string().min(1)}),de=e.looseObject({label:e.string().min(1)}),ge=e.custom((t)=>typeof t==="function"),pe=e.looseObject({layouts:e.record(e.string(),e.unknown()).optional(),plugin:ge.optional(),pluginConfig:e.record(e.string(),e.unknown()).optional(),routes:e.array(ce).optional(),entityDisplay:e.record(e.string(),de).optional(),content:e.unknown().optional(),themeOverride:e.string().optional(),headScripts:e.array(e.string()).optional(),staticAssets:e.record(e.string(),e.string()).optional()}),Ut=e.custom((t)=>pe.safeParse(t).success);var In=e.looseObject({name:e.string().min(1),version:e.string().min(1),dependencies:e.record(e.string(),e.string()).optional(),peerDependencies:e.record(e.string(),e.string()).optional()});export{_ as M,O as N,K as O,I as P,J as Q,re as R};
|
|
529
529
|
|
|
530
530
|
//# debugId=0A0D28B34F6AD10764756E2164756E21
|
|
531
|
-
//# sourceMappingURL=index-
|
|
531
|
+
//# sourceMappingURL=index-4jdfvr30.js.map
|