@rizom/brain 0.2.0-alpha.859 → 0.2.0-alpha.860

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.
@@ -1,7 +1,7 @@
1
1
  // @bun
2
- import{fe as p}from"./index-e0qz6mam.js";import{bf as m,gf as d,jf as v,kf as S}from"./index-dbc02tv7.js";import{rl as h}from"./index-stpp3r8b.js";import{nu as n,pu as a}from"./index-y95tc91a.js";import{Iy as f,WB as s,Xy as l}from"./index-954p4889.js";import{RD as g}from"./index-3w684dmw.js";async function u(i){let[{default:e},{default:t}]=await Promise.all([import("./index-gecxg7ew.js"),import("./package-r6q4rydp.js")]);return h(e,i??{},{name:t.name,version:t.version},{pluginId:"cli"})}class c{shell=null;config;signalScope=null;signalShutdownFiber=null;stopPromise=null;migrationPromise=null;hasCLI=!1;static create(i,e){return new c(v(i),e)}constructor(i,e){if(this.config=i,this.hasCLI=process.argv.slice(2).includes("--cli"),e)this.shell=e}async migrate(){let i=a.getInstance();await new d(i).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(i,e){this.shell=m.createFresh(S(this.config,i),void 0,{...e?.processRole&&{processRole:e.processRole},...e?.peerChannel&&{peerChannel:e.peerChannel}})}wantsCLI(i){return this.hasCLI||i?.cli===!0}async registerCLIInterface(i){if(!this.wantsCLI(i))return;let e=this.getShell().getPluginManager();for(let t of await u(this.config.cliConfig))e.registerPlugin(t)}async initialize(i,e){if(!this.shell){if(!e?.migrationsCompleted){this.migrationPromise=this.migrate();try{await this.migrationPromise}finally{this.migrationPromise=null}}if(this.stopPromise)return;this.createShell(i,e)}if(await this.registerCLIInterface(e),this.stopPromise)return;await this.getShell().initialize(i)}async start(){if(this.stopPromise)return;this.setupSignalHandlers()}stop(){return this.stopPromise??=this.stopApp(),this.stopPromise}async stopApp(){if(await this.closeSignalScope(),this.migrationPromise)await this.migrationPromise.catch(()=>{return});await this.shell?.shutdown()}async run(i){let t={debug:n.DEBUG,info:n.INFO,warn:n.WARN,error:n.ERROR}[this.config.logLevel??"info"]??n.INFO,o=this.wantsCLI(i),r=a.createFresh({level:t,context:this.config.name,useStderr:o});if(o)a.getInstance().setUseStderr(!0);r.info(`\uD83D\uDE80 Starting ${this.config.name} v${this.config.version}...`),this.setupSignalHandlers();try{if(await this.initialize(void 0,i),this.stopPromise)return;await this.start(),i?.onRuntimeReady?.(),r.info(`\u2705 ${this.config.name} v${this.config.version} ready`),process.stdin.resume()}catch(C){r.error(`\u274C Failed to start ${this.config.name}:`,C),process.exit(1)}}static async run(i,e,t){await c.create(i,e).run(t)}setupSignalHandlers(){if(this.signalScope)return;let i=s.runSync(l.make()),e=()=>{this.requestGracefulShutdown("SIGINT")},t=()=>{this.requestGracefulShutdown("SIGTERM")},o=p(["SIGINT"],e),r=p(["SIGTERM"],t);s.runSync(l.addFinalizer(i,s.sync(()=>{r(),o()}))),this.signalScope=i}requestGracefulShutdown(i){if(this.signalShutdownFiber)return;let e=a.getInstance();e.info(`
2
+ import{fe as p}from"./index-e0qz6mam.js";import{bf as m,gf as d,jf as v,kf as S}from"./index-n7f1g306.js";import{rl as h}from"./index-cj5gzzsn.js";import{nu as n,pu as a}from"./index-y95tc91a.js";import{Iy as f,WB as s,Xy as l}from"./index-954p4889.js";import{RD as g}from"./index-3w684dmw.js";async function u(i){let[{default:e},{default:t}]=await Promise.all([import("./index-tfn1jn8z.js"),import("./package-73axy3ng.js")]);return h(e,i??{},{name:t.name,version:t.version},{pluginId:"cli"})}class c{shell=null;config;signalScope=null;signalShutdownFiber=null;stopPromise=null;migrationPromise=null;hasCLI=!1;static create(i,e){return new c(v(i),e)}constructor(i,e){if(this.config=i,this.hasCLI=process.argv.slice(2).includes("--cli"),e)this.shell=e}async migrate(){let i=a.getInstance();await new d(i).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(i,e){this.shell=m.createFresh(S(this.config,i),void 0,{...e?.processRole&&{processRole:e.processRole},...e?.peerChannel&&{peerChannel:e.peerChannel}})}wantsCLI(i){return this.hasCLI||i?.cli===!0}async registerCLIInterface(i){if(!this.wantsCLI(i))return;let e=this.getShell().getPluginManager();for(let t of await u(this.config.cliConfig))e.registerPlugin(t)}async initialize(i,e){if(!this.shell){if(!e?.migrationsCompleted){this.migrationPromise=this.migrate();try{await this.migrationPromise}finally{this.migrationPromise=null}}if(this.stopPromise)return;this.createShell(i,e)}if(await this.registerCLIInterface(e),this.stopPromise)return;await this.getShell().initialize(i)}async start(){if(this.stopPromise)return;this.setupSignalHandlers()}stop(){return this.stopPromise??=this.stopApp(),this.stopPromise}async stopApp(){if(await this.closeSignalScope(),this.migrationPromise)await this.migrationPromise.catch(()=>{return});await this.shell?.shutdown()}async run(i){let t={debug:n.DEBUG,info:n.INFO,warn:n.WARN,error:n.ERROR}[this.config.logLevel??"info"]??n.INFO,o=this.wantsCLI(i),r=a.createFresh({level:t,context:this.config.name,useStderr:o});if(o)a.getInstance().setUseStderr(!0);r.info(`\uD83D\uDE80 Starting ${this.config.name} v${this.config.version}...`),this.setupSignalHandlers();try{if(await this.initialize(void 0,i),this.stopPromise)return;await this.start(),i?.onRuntimeReady?.(),r.info(`\u2705 ${this.config.name} v${this.config.version} ready`),process.stdin.resume()}catch(C){r.error(`\u274C Failed to start ${this.config.name}:`,C),process.exit(1)}}static async run(i,e,t){await c.create(i,e).run(t)}setupSignalHandlers(){if(this.signalScope)return;let i=s.runSync(l.make()),e=()=>{this.requestGracefulShutdown("SIGINT")},t=()=>{this.requestGracefulShutdown("SIGTERM")},o=p(["SIGINT"],e),r=p(["SIGTERM"],t);s.runSync(l.addFinalizer(i,s.sync(()=>{r(),o()}))),this.signalScope=i}requestGracefulShutdown(i){if(this.signalShutdownFiber)return;let e=a.getInstance();e.info(`
3
3
  Received ${i}, shutting down gracefully...`);let t=s.tryPromise({try:()=>this.stop(),catch:(o)=>o}).pipe(s.match({onFailure:(o)=>{e.error("Error during shutdown:",o),process.exit(1)},onSuccess:()=>{process.exit(0)}}));this.signalShutdownFiber=s.runFork(t)}async closeSignalScope(){let i=this.signalScope;if(this.signalScope=null,i)await s.runPromise(l.close(i,f.void))}getShell(){if(!this.shell)throw Error("Shell not initialized. Call initialize() first.");return this.shell}}
4
4
  export{c as B};
5
5
 
6
6
  //# debugId=9B73B14A3259F2E164756E2164756E21
7
- //# sourceMappingURL=index-1kwdw5vs.js.map
7
+ //# sourceMappingURL=index-cwrpfjer.js.map
@@ -1,6 +1,6 @@
1
1
  // @bun
2
- import{ql as n}from"./index-stpp3r8b.js";function t(i,e={}){if(!n(i))throw Error("use() expects a package definition returned by a @rizom/brain define helper");return Object.freeze({kind:"rizom-configured-plugin",definition:i,config:Object.freeze({...e})})}function f(i){if(i===null||typeof i!=="object")return!1;return Reflect.get(i,"kind")==="rizom-configured-plugin"&&n(Reflect.get(i,"definition"))&&typeof Reflect.get(i,"config")==="object"}
2
+ import{ql as n}from"./index-cj5gzzsn.js";function t(i,e={}){if(!n(i))throw Error("use() expects a package definition returned by a @rizom/brain define helper");return Object.freeze({kind:"rizom-configured-plugin",definition:i,config:Object.freeze({...e})})}function f(i){if(i===null||typeof i!=="object")return!1;return Reflect.get(i,"kind")==="rizom-configured-plugin"&&n(Reflect.get(i,"definition"))&&typeof Reflect.get(i,"config")==="object"}
3
3
  export{t as nf,f as of};
4
4
 
5
5
  //# debugId=9501E80E7710598064756E2164756E21
6
- //# sourceMappingURL=index-3erkk0g4.js.map
6
+ //# sourceMappingURL=index-g9bpep2g.js.map
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{lf as Zs,mf as Ws}from"./index-8evv41se.js";import{$i as Ps,$k as qd,Ag as fr,Ak as Wi,Bf as le,Bg as ri,Bh as Ss,Bk as ul,Cg as Tl,Ck as pl,Co as Qs,Df as Do,Dg as qo,Dk as Ts,Do as is,Eg as Jo,Ek as Es,Em as qe,Eo as Fs,Fg as Go,Fk as ks,Fm as gn,Fn as Pc,Fo as ns,Gn as Cc,Hm as kn,Hn as ht,Im as be,Jg as _r,Jm as An,Jn as Gd,Kg as Fr,Km as jn,Kn as _s,Lf as zo,Lm as Mr,Mm as Ms,Nm as Dn,Og as Id,Oo as Ks,Po as Qd,Qf as Qr,Qg as hr,Rf as kt,Ro as Ns,Sf as Po,Sk as As,So as Sc,Tf as Co,To as rr,Uk as js,Vf as To,Vi as oc,Vk as Ve,Wf as Kd,Wi as wt,Wk as gc,Xj as du,Xk as fc,Yj as uu,Zf as Eo,Zj as pu,Zk as hc,_f as Mo,_h as Sr,_i as go,_k as yc,aj as zn,al as Dc,bg as ge,bj as Cs,bl as Qo,cg as fe,ci as Nl,ck as ar,dg as Vd,dj as na,dk as ol,eg as Yd,ei as qs,ej as ti,ek as ho,el as Cr,en as Ls,fg as Xd,fk as Su,fl as Ds,fn as Us,gg as eu,gh as Zd,gi as Js,gl as De,gn as qc,hg as tu,hh as oa,hi as yl,hj as au,hn as Bs,ig as ru,ih as Io,ij as cu,il as Jd,in as Ko,jg as iu,ji as Gl,jj as ss,jl as zs,jn as $s,kg as nu,ki as Ql,kj as as,kl as Ec,lg as ou,lh as Td,lj as cs,ll as tc,mg as So,mh as bo,mi as Kl,ml as Ci,mn as Fo,ng as wo,ni as ws,nj as ls,nn as Vo,og as Ro,oj as Ud,on as Yo,pj as Bd,pn as Xo,qg as Bt,qi as W,qj as $d,qn as es,rf as Bl,rg as vs,ri as sa,rj as _d,sf as ut,sg as xt,sj as Wd,tg as je,tj as cd,tk as On,ug as V,uk as bt,vf as sn,vg as Dd,vk as mc,wf as ft,wg as Mc,wk as Hd,xf as we,xg as Jl,yf as jo,yn as ts,yo as Gs,zf as U,zg as A,zo as rs}from"./index-stpp3r8b.js";import{$o as Ll,$r as Yt,$s as ec,Bs as ms,Gr as Ke,Ht as nl,Lr as ia,Mr as er,Nq as Wo,Pt as Rs,Uq as Ho,Vr as dc,Vt as Is,Wr as uc,Wt as xs,Xq as po,Xt as Md,Yp as K,Zs as Xa,ap as se,aq as rc,bq as H,bu as Os,cp as _,dp as _e,du as Va,ep as Re,fp as at,gp as Pe,gu as me,jt as oe,kr as Ee,mr as P,mu as Z,nr as Qe,pt as ee,st as re,tq as ve,tt as qi,ur as mo,ws as jd,xs as Nd}from"./index-431k3883.js";import{nu as Xe,pu as ke}from"./index-y95tc91a.js";import{Iy as D,WB as R,Xy as z,dz as Y,kC as ae,mC as tr,nC as pc,qC as bc,qw as T,uy as ce,wy as bs}from"./index-954p4889.js";import{ID as l}from"./index-7mq8b26b.js";function zr(e,t){let r=new Set(t.map((i)=>i.type));return e.byType.filter((i)=>(i.status==="pending"||i.status==="processing")&&!r.has(i.type))}function We(e,t){let r=e.workerSessions,i=r.active===0?"missing":r.stale>0?"stale":"active",n=e.duePending>0&&(e.oldestDuePendingAgeMs??0)>=120000&&e.totals.processing===0&&(e.latestClaimAgeMs===null||e.latestClaimAgeMs>=120000),o=[];if(i==="missing")o.push("No live worker session");else if(i==="stale")o.push(`${r.stale} stale worker session(s)`);if(n)o.push(`${e.duePending} due job(s) have remained unclaimed for at least 120000ms`);if(t){let s=zr(e,t).reduce((a,c)=>a+c.count,0);if(s>0)o.push(`${s} active job(s) have no declared executor`)}return{status:o.length===0?"operational":"degraded",reasons:o,worker:{state:i,activeSessions:r.active,staleSessions:r.stale,latestHeartbeatAgeMs:r.latestHeartbeatAgeMs},queue:{duePending:e.duePending,processing:e.totals.processing,oldestDuePendingAgeMs:e.oldestDuePendingAgeMs,latestClaimAgeMs:e.latestClaimAgeMs,stalled:n}}}async function xn(e){let{config:t,services:r,bootTime:i,endpoints:n,interactions:o}=e,[s,a,c,d]=await Promise.all([r.entityService.getEntityCounts(ft("runtime app info reports operator-facing aggregate status")),r.entityService.countEmbeddings(),r.daemonRegistry.getStatuses(),r.jobQueueService.getDiagnostics()]),u=s.reduce((p,m)=>p+m.count,0);return{model:t.name||"brain-app",version:t.version||"1.0.0",uptime:Math.floor((Date.now()-i)/1000),entities:u,entityCounts:s,embeddings:a,backgroundWork:We(d,r.jobQueueService.getExecutionRegistrations()),ai:{model:t.ai.model,embeddingModel:r.embeddingService.identity.model},daemons:c,endpoints:n(),interactions:o()}}import{readdir as Pn,readFile as _u}from"fs/promises";var Fu=10;async function Nu(e="/proc"){let t=null;try{t=(await Pn(`${e}/self/fd`)).length}catch{}try{let i=(await Pn(e,{withFileTypes:!0})).filter((s)=>s.isDirectory()&&/^\d+$/.test(s.name)).map((s)=>s.name),n=0,o=0;return await Promise.all(i.map(async(s)=>{try{let a=await _u(`${e}/${s}/status`,"utf8");if(o++,/^State:\s+Z\b/m.test(a))n++}catch{}})),{fileDescriptors:t,processCount:o,zombieCount:n}}catch{return{fileDescriptors:t,processCount:null,zombieCount:null}}}function Cn(e,t,r){return t.status==="fulfilled"?{name:e,status:"healthy",message:r}:{name:e,status:"unhealthy",message:P(t.reason)}}function Zu(e){if(!e)return{name:"job-worker",status:"degraded",message:"Worker session state is unavailable"};let t=e.workerSessions,r=We(e).worker;if(r.state==="missing")return{name:"job-worker",status:"degraded",message:"No live worker session",details:{sessions:t}};if(r.state==="stale")return{name:"job-worker",status:"degraded",message:`${t.stale} stale worker session(s)`,details:{sessions:t}};return{name:"job-worker",status:"healthy",message:`${t.active} live worker session(s)`,details:{sessions:t}}}function Wu(e){if(!e)return{name:"job-queue-progress",status:"degraded",message:"Queue progress state is unavailable"};let t=We(e).queue;return t.stalled?{name:"job-queue-progress",status:"degraded",message:`${t.duePending} due job(s) are not being claimed`,details:{queue:t}}:{name:"job-queue-progress",status:"healthy",message:"Due jobs are being claimed",details:{queue:t}}}function Hu(e,t){if(!e||!t)return{name:"job-execution-inventory",status:"degraded",message:"Job execution inventory is unavailable"};let r=zr(e,t),i=r.reduce((n,o)=>n+o.count,0);return i===0?{name:"job-execution-inventory",status:"healthy",message:"Every active job type has a declared executor"}:{name:"job-execution-inventory",status:"degraded",message:`${i} active job(s) have no declared executor`,details:{jobs:r}}}function qu(e){if(!e)return{name:"attempt-leases",status:"degraded",message:"Lease state is unavailable"};return e.staleLeaseCount===0?{name:"attempt-leases",status:"healthy",message:"No stale processing leases"}:{name:"attempt-leases",status:"degraded",message:`${e.staleLeaseCount} processing lease(s) are stale`,details:{staleLeaseCount:e.staleLeaseCount}}}function Ju(e){if(!e.initialized)return{name:"projection-circuits",status:"degraded",message:"Projection runtime supervisor is not initialized"};if(e.openCircuits.length===0)return{name:"projection-circuits",status:"healthy",message:"No projection circuits are open"};return{name:"projection-circuits",status:"degraded",message:`${e.openCircuits.length} projection circuit(s) open`,details:{circuits:e.openCircuits}}}async function Gu(e){let t=e.entityService.getProjectionStore(),[r,i,n]=await Promise.all([t.getActiveWave(),t.getUnresolvedProjectionIncidentDiagnostics(Fu),t.getProjectionBatchDiagnostics?.()??Promise.resolve({preparing:0,open:0,abandoned:0,expiredCallbackLeases:0,oldestActiveAgeMs:null,oldestProgressAgeMs:null})]);if(!r)return{waveId:null,batches:n,strandedRules:[],incidentCount:i.total,incidents:i.incidents};let s=(await t.listWaveRules(r.id)).filter((c)=>c.status==="queued"||c.status==="failed"),a=(await Promise.all(s.map(async(c)=>{let d=c.jobId?await e.jobQueueService.getStatus(c.jobId):null;if(c.status!=="failed"&&d&&(d.status==="pending"||d.status==="processing"))return null;return{ruleId:c.ruleId,jobId:c.jobId,jobStatus:d?.status??"missing"}}))).filter((c)=>c!==null);return{waveId:r.id,batches:n,strandedRules:a,incidentCount:i.total,incidents:i.incidents}}function Qu(e){if(e.batches.abandoned>0)return{name:"projection-waves",status:"degraded",message:`${e.batches.abandoned} projection batch(es) await recovery`,details:{batches:e.batches}};if(e.batches.expiredCallbackLeases>0)return{name:"projection-waves",status:"degraded",message:"A callback projection batch lease has expired",details:{batches:e.batches}};if(e.incidentCount>0)return{name:"projection-waves",status:"degraded",message:`${e.incidentCount} unresolved terminal projection incident(s)`,details:{incidentCount:e.incidentCount,incidentsTruncated:e.incidentCount>e.incidents.length,incidents:e.incidents.map((t)=>({waveId:t.waveId,ruleId:t.ruleId,jobId:t.jobId,failureReason:t.failureReason,createdAt:t.createdAt}))}};if(!e.waveId)return{name:"projection-waves",status:"healthy",message:e.batches.open+e.batches.preparing>0?`${e.batches.open+e.batches.preparing} projection batch(es) active`:"No active projection wave",...e.batches.open+e.batches.preparing>0&&{details:{batches:e.batches}}};if(e.strandedRules.length===0)return{name:"projection-waves",status:"healthy",message:`Projection wave ${e.waveId} is progressing`};return{name:"projection-waves",status:"degraded",message:`Projection wave ${e.waveId} has ${e.strandedRules.length} stranded rule job(s)`,details:{waveId:e.waveId,strandedRules:e.strandedRules}}}function Ku(e){let t=e.filter((r)=>r.status!=="running"||r.health?.status==="error");return t.length===0?{name:"daemons",status:"healthy",message:`${e.length} daemon(s) healthy`}:{name:"daemons",status:"degraded",message:`${t.length} daemon(s) unhealthy`,details:{daemons:t.map((r)=>({name:r.name,status:r.status,health:r.health?.status,message:r.health?.message}))}}}async function Tn(e){let t=e.now?.()??Date.now(),r=(e.memoryUsage??process.memoryUsage)(),[i,n,o,s,a,c,d,u]=await Promise.allSettled([e.entityService.getEntityCounts(ft("runtime readiness database probe")),e.jobQueueService.getDiagnostics(t),Promise.resolve(e.jobQueueService.getExecutionRegistrations()),e.daemonRegistry.getStatuses(),(e.readProcessSignals??Nu)(),e.projectionRuntimeSupervisor.getDiagnostics(),Gu(e),e.operationalHealthRegistry.getChecks()]),p=n.status==="fulfilled"?n.value:null,m=o.status==="fulfilled"?o.value??null:null,g=s.status==="fulfilled"?s.value:[],f=a.status==="fulfilled"?a.value:{fileDescriptors:null,processCount:null,zombieCount:null},h=c.status==="fulfilled"?c.value:{status:"unhealthy",initialized:!1,trackedRoots:0,openCircuits:[]},w=[Cn("entity-database",i,"Entity database is accessible"),Cn("job-queue-database",n,"Job queue database is accessible"),Zu(p),Wu(p),Hu(p,m),qu(p),c.status==="fulfilled"?Ju(h):{name:"projection-circuits",status:"degraded",message:P(c.reason)},d.status==="fulfilled"?Qu(d.value):{name:"projection-waves",status:"degraded",message:P(d.reason)},s.status==="fulfilled"?Ku(g):{name:"daemons",status:"degraded",message:P(s.reason)}],b=u.status==="fulfilled"?u.value:[{name:"plugin-operational-health",status:"degraded",message:"Plugin operational health is unavailable"}],S=[...w,...b];return{status:w.some((y)=>y.status==="unhealthy")?"not_ready":"ready",operationalStatus:S.some((y)=>y.status!=="healthy")?"degraded":"operational",checkedAt:new Date(t).toISOString(),checks:S,resources:{memory:{rssBytes:r.rss,heapUsedBytes:r.heapUsed,heapTotalBytes:r.heapTotal},fileDescriptors:f.fileDescriptors,processes:{total:f.processCount,zombies:f.zombieCount},queue:p,projection:{initialized:h.initialized,trackedRoots:h.trackedRoots,openCircuits:h.openCircuits},worker:p?.workerSessions??{total:0,active:0,stale:0,latestHeartbeatAgeMs:null}}}}function En(){return{dataDir:"./data",cacheDir:"./cache",distDir:"./dist"}}function ye(e){return{database:{url:`file:${e.dataDir}/brain.db`},jobQueueDatabase:{url:`file:${e.dataDir}/brain-jobs.db`},conversationDatabase:{url:`file:${e.dataDir}/conversations.db`},runtimeStateDatabase:{url:`file:${e.dataDir}/runtime-state.db`},embeddingDatabase:{url:`file:${e.dataDir}/embeddings.db`},embedding:{enabled:!0}}}var He=l.strictObject({enabled:l.boolean().optional().describe("Serve HTTP; defaults to whether the selected bundles host the web surface"),preview:l.boolean().optional().describe("Serve the preview site; defaults to whether a site builder runs"),hostname:l.string().trim().min(1).optional().describe("Bind address; use 127.0.0.1 for isolated local tests"),productionDistDir:l.string().min(1).optional().describe("Directory of the production site, when no site builder writes it"),previewDistDir:l.string().min(1).optional().describe("Directory of the preview site, when no site builder writes it"),sharedImagesDir:l.string().min(1).optional().describe("Directory of shared optimized images")}),Or=He.extend({enabled:l.boolean().default(!1),preview:l.boolean().default(!0),port:l.number().default(8080).describe("Port of the production listener")});var ne=l.enum(["debug","info","warn","error"]);var Lr=En(),Vu=l.looseObject({label:l.string().min(1),pluralName:l.string().optional(),layout:l.string().optional(),paginate:l.boolean().optional(),pageSize:l.number().optional(),navigation:l.object({show:l.boolean().optional(),slot:l.enum(["primary","secondary"]).optional(),priority:l.number().optional()}).optional()});function Ur(){return ye(Lr)}var Br=l.object({name:l.string().default("brain-app"),version:l.string().default("1.0.0"),database:Ee,jobQueueDatabase:Ee,jobQueue:l.object({workerConcurrency:l.number().int().min(1).max(32).default(4)}).prefault({}),conversationDatabase:Ee,runtimeStateDatabase:Ee,embeddingDatabase:Ee,ai:l.object({providerKeys:qe.default({}),model:l.string().refine(kn,{error:(e)=>`Unsupported model "${String(e.input)}"`}),embeddingModel:l.string().refine((e)=>Mr(e)!==void 0,{error:(e)=>Dn(String(e.input))}).default(jn),modelRuntimeUrl:l.string().url().optional(),answerModel:l.string().optional(),visionModel:l.string().optional(),imageModel:l.string().optional(),temperature:l.number().min(0).max(2).default(0.7),webSearch:l.boolean().default(!0),reasoningEffort:oe.optional()}).superRefine((e,t)=>{if(e.answerModel&&be(e.answerModel)!=="local")t.addIssue({code:"custom",path:["answerModel"],message:`answerModel must be a local: model, not ${e.answerModel}`});if(e.visionModel&&be(e.visionModel)!=="local")t.addIssue({code:"custom",path:["visionModel"],message:`visionModel must be a local: model, not ${e.visionModel}`});if(e.modelRuntimeUrl)return;let r=[...be(e.model)==="local"?[e.model]:[],...[e.answerModel,e.visionModel].filter((i)=>i!==void 0&&be(i)==="local"),...e.imageModel&&An(e.imageModel).provider==="local"?[e.imageModel]:[],...Mr(e.embeddingModel)?.provider==="local"?[e.embeddingModel]:[]];for(let i of r)t.addIssue({code:"custom",path:["modelRuntimeUrl"],message:`${i} needs modelRuntime.url`})}),embedding:l.object({enabled:l.boolean().default(!0)}),logging:l.object({level:ne.default("info"),format:l.enum(["text","json"]).default("text"),file:l.string().optional(),context:l.string().default("shell")}).prefault({level:"info",context:"shell"}),features:l.object({}).default({}),plugins:l.array(ht).default([]),dataDir:l.string().default("./brain-data"),gitBrokerSocket:l.string().min(1).optional(),gitBrokerCheckout:l.string().min(1).optional(),spaces:l.array(l.string()).default([]),siteBaseUrl:l.string().optional(),localSiteUrl:l.string().optional(),preferLocalUrls:l.boolean().default(!1),production:l.boolean().default(!1),themeCSS:l.string().default(""),entityDisplay:l.record(l.string(),Vu).optional(),profileKind:l.string().trim().min(1).optional(),http:Or.prefault({})});function yt(e={}){let{plugins:t=[],permissions:r={},identity:i,profile:n,agentInstructions:o,evalHandlerRegistry:s,ai:a,logging:c,embedding:d,jobQueue:u,...p}=e,{entityDisplay:m,...g}=Br.parse({...Ur(),...H(p),ai:H({...a}),logging:H({...c}),embedding:H({...d}),jobQueue:H({...u}),plugins:[]});return{...g,plugins:t,permissions:r,...H({entityDisplay:m,identity:i,profile:n,agentInstructions:o,evalHandlerRegistry:s})}}var B={NOTE:"note",BRAIN_CHARACTER:"brain-character",ANCHOR_PROFILE:"anchor-profile"},Je={KNOWLEDGE_QUERY:"shell:knowledge-query",BASE_ENTITY_DISPLAY:"shell:base-entity-display",CONTENT_GENERATION:"shell:content-generation"},$r={ENTITIES:"shell:entities"};var Yu=zn.extend({templateName:l.string()}),Xu=l.object({slug:l.string()}),ep="The style guide governs voice, tone, wording and form: paragraphing, sentence rhythm, hooks, rhetorical questions and calls to action. The instructions below and any additional instructions in the request govern the task, required content, length limits, platform constraints and output format. When either conflicts with the style guide on voice or form, follow the style guide.",tp="Generate the content described in your instructions.";function rp(e){return e instanceof l.ZodType}function ip(e){if(!e)return;return e.replace(/^https?:\/\//,"").replace(/\/$/,"")}class vt{aiService;entityService;templateRegistry;getIdentityContent;getProfileContent;entityUrls;id="ai-content";name="AI Content Generator";description="Generates content using AI based on templates and prompts";constructor(e,t,r,i,n,o,s){this.aiService=e,this.entityService=t,this.templateRegistry=r,this.getIdentityContent=i,this.getProfileContent=n,this.entityUrls=o,this.siteBaseUrl=ip(s)}siteBaseUrl;async generate(e,t,r){return this.generateWithContext(e,t,r)}async generateScoped(e,t,r){return this.generateWithContext(e,t,r.signal,r)}async generateWithContext(e,t,r,i){r?.throwIfAborted();let n=Yu.parse(e),o=this.templateRegistry.get(n.templateName);if(!o)throw Error(`Template not found: ${n.templateName}`);if(!o.basePrompt)throw Error(`Template ${n.templateName} must have basePrompt for content generation`);let s=i?await On((w,b)=>i.getEntity(w,b),n.templateName,o.basePrompt):await bt(this.entityService,n.templateName,o.basePrompt);r?.throwIfAborted();let a=[s,n.prompt].filter(Boolean).join(" "),c=a.length>0&&o.useKnowledgeContext===!0,d=this.entityService.getWeightMap(),u=Object.keys(d).length>0,p=c?i?await i.search(a,{limit:5,...u&&{weight:d}}):await this.entityService.search({query:a,options:{limit:5,...u&&{weight:d},...r&&{signal:r}}}):[];r?.throwIfAborted();let m=this.buildPrompt(n,p),g=i?await this.readIdentities(i,n.representedIdentity):void 0,f=this.buildSystemPrompt(s,n,g);if(!rp(o.schema))throw Error(`Template ${o.name} cannot be used for AI generation: schema is not an AI generation schema`);r?.throwIfAborted();let h=await this.aiService.generateObject(f,m,o.schema,r);return r?.throwIfAborted(),t.parse(h.object)}async readIdentities(e,t){let r=async(o)=>(await e.getEntity(o,o))?.content??"",[i,n]=await Promise.all([t!=="none"?r(B.BRAIN_CHARACTER):"",t===void 0||t==="anchor"?r(B.ANCHOR_PROFILE):""]);return{brain:i,anchor:n}}buildSystemPrompt(e,t,r){let i=[];if(t.representedIdentity===void 0||t.representedIdentity==="brain"||t.representedIdentity==="anchor")i.push("# Brain Identity",r?.brain??this.getIdentityContent(),"");if(t.representedIdentity===void 0||t.representedIdentity==="anchor")i.push("# Represented Anchor",r?.anchor??this.getProfileContent(),"");let n=this.selectStyleGuidance(t);if(n)i.push("# Style Guide",n,"","# Precedence",ep,"");return i.push("# Instructions",e),i.join(`
2
+ import{lf as Zs,mf as Ws}from"./index-8evv41se.js";import{$i as Ps,$k as qd,Ag as fr,Ak as Wi,Bf as le,Bg as ri,Bh as Ss,Bk as ul,Cg as Tl,Ck as pl,Co as Qs,Df as Do,Dg as qo,Dk as Ts,Do as is,Eg as Jo,Ek as Es,Em as qe,Eo as Fs,Fg as Go,Fk as ks,Fm as gn,Fn as Pc,Fo as ns,Gn as Cc,Hm as kn,Hn as ht,Im as be,Jg as _r,Jm as An,Jn as Gd,Kg as Fr,Km as jn,Kn as _s,Lf as zo,Lm as Mr,Mm as Ms,Nm as Dn,Og as Id,Oo as Ks,Po as Qd,Qf as Qr,Qg as hr,Rf as kt,Ro as Ns,Sf as Po,Sk as As,So as Sc,Tf as Co,To as rr,Uk as js,Vf as To,Vi as oc,Vk as Ve,Wf as Kd,Wi as wt,Wk as gc,Xj as du,Xk as fc,Yj as uu,Zf as Eo,Zj as pu,Zk as hc,_f as Mo,_h as Sr,_i as go,_k as yc,aj as zn,al as Dc,bg as ge,bj as Cs,bl as Qo,cg as fe,ci as Nl,ck as ar,dg as Vd,dj as na,dk as ol,eg as Yd,ei as qs,ej as ti,ek as ho,el as Cr,en as Ls,fg as Xd,fk as Su,fl as Ds,fn as Us,gg as eu,gh as Zd,gi as Js,gl as De,gn as qc,hg as tu,hh as oa,hi as yl,hj as au,hn as Bs,ig as ru,ih as Io,ij as cu,il as Jd,in as Ko,jg as iu,ji as Gl,jj as ss,jl as zs,jn as $s,kg as nu,ki as Ql,kj as as,kl as Ec,lg as ou,lh as Td,lj as cs,ll as tc,mg as So,mh as bo,mi as Kl,ml as Ci,mn as Fo,ng as wo,ni as ws,nj as ls,nn as Vo,og as Ro,oj as Ud,on as Yo,pj as Bd,pn as Xo,qg as Bt,qi as W,qj as $d,qn as es,rf as Bl,rg as vs,ri as sa,rj as _d,sf as ut,sg as xt,sj as Wd,tg as je,tj as cd,tk as On,ug as V,uk as bt,vf as sn,vg as Dd,vk as mc,wf as ft,wg as Mc,wk as Hd,xf as we,xg as Jl,yf as jo,yn as ts,yo as Gs,zf as U,zg as A,zo as rs}from"./index-cj5gzzsn.js";import{$o as Ll,$r as Yt,$s as ec,Bs as ms,Gr as Ke,Ht as nl,Lr as ia,Mr as er,Nq as Wo,Pt as Rs,Uq as Ho,Vr as dc,Vt as Is,Wr as uc,Wt as xs,Xq as po,Xt as Md,Yp as K,Zs as Xa,ap as se,aq as rc,bq as H,bu as Os,cp as _,dp as _e,du as Va,ep as Re,fp as at,gp as Pe,gu as me,jt as oe,kr as Ee,mr as P,mu as Z,nr as Qe,pt as ee,st as re,tq as ve,tt as qi,ur as mo,ws as jd,xs as Nd}from"./index-431k3883.js";import{nu as Xe,pu as ke}from"./index-y95tc91a.js";import{Iy as D,WB as R,Xy as z,dz as Y,kC as ae,mC as tr,nC as pc,qC as bc,qw as T,uy as ce,wy as bs}from"./index-954p4889.js";import{ID as l}from"./index-7mq8b26b.js";function zr(e,t){let r=new Set(t.map((i)=>i.type));return e.byType.filter((i)=>(i.status==="pending"||i.status==="processing")&&!r.has(i.type))}function We(e,t){let r=e.workerSessions,i=r.active===0?"missing":r.stale>0?"stale":"active",n=e.duePending>0&&(e.oldestDuePendingAgeMs??0)>=120000&&e.totals.processing===0&&(e.latestClaimAgeMs===null||e.latestClaimAgeMs>=120000),o=[];if(i==="missing")o.push("No live worker session");else if(i==="stale")o.push(`${r.stale} stale worker session(s)`);if(n)o.push(`${e.duePending} due job(s) have remained unclaimed for at least 120000ms`);if(t){let s=zr(e,t).reduce((a,c)=>a+c.count,0);if(s>0)o.push(`${s} active job(s) have no declared executor`)}return{status:o.length===0?"operational":"degraded",reasons:o,worker:{state:i,activeSessions:r.active,staleSessions:r.stale,latestHeartbeatAgeMs:r.latestHeartbeatAgeMs},queue:{duePending:e.duePending,processing:e.totals.processing,oldestDuePendingAgeMs:e.oldestDuePendingAgeMs,latestClaimAgeMs:e.latestClaimAgeMs,stalled:n}}}async function xn(e){let{config:t,services:r,bootTime:i,endpoints:n,interactions:o}=e,[s,a,c,d]=await Promise.all([r.entityService.getEntityCounts(ft("runtime app info reports operator-facing aggregate status")),r.entityService.countEmbeddings(),r.daemonRegistry.getStatuses(),r.jobQueueService.getDiagnostics()]),u=s.reduce((p,m)=>p+m.count,0);return{model:t.name||"brain-app",version:t.version||"1.0.0",uptime:Math.floor((Date.now()-i)/1000),entities:u,entityCounts:s,embeddings:a,backgroundWork:We(d,r.jobQueueService.getExecutionRegistrations()),ai:{model:t.ai.model,embeddingModel:r.embeddingService.identity.model},daemons:c,endpoints:n(),interactions:o()}}import{readdir as Pn,readFile as _u}from"fs/promises";var Fu=10;async function Nu(e="/proc"){let t=null;try{t=(await Pn(`${e}/self/fd`)).length}catch{}try{let i=(await Pn(e,{withFileTypes:!0})).filter((s)=>s.isDirectory()&&/^\d+$/.test(s.name)).map((s)=>s.name),n=0,o=0;return await Promise.all(i.map(async(s)=>{try{let a=await _u(`${e}/${s}/status`,"utf8");if(o++,/^State:\s+Z\b/m.test(a))n++}catch{}})),{fileDescriptors:t,processCount:o,zombieCount:n}}catch{return{fileDescriptors:t,processCount:null,zombieCount:null}}}function Cn(e,t,r){return t.status==="fulfilled"?{name:e,status:"healthy",message:r}:{name:e,status:"unhealthy",message:P(t.reason)}}function Zu(e){if(!e)return{name:"job-worker",status:"degraded",message:"Worker session state is unavailable"};let t=e.workerSessions,r=We(e).worker;if(r.state==="missing")return{name:"job-worker",status:"degraded",message:"No live worker session",details:{sessions:t}};if(r.state==="stale")return{name:"job-worker",status:"degraded",message:`${t.stale} stale worker session(s)`,details:{sessions:t}};return{name:"job-worker",status:"healthy",message:`${t.active} live worker session(s)`,details:{sessions:t}}}function Wu(e){if(!e)return{name:"job-queue-progress",status:"degraded",message:"Queue progress state is unavailable"};let t=We(e).queue;return t.stalled?{name:"job-queue-progress",status:"degraded",message:`${t.duePending} due job(s) are not being claimed`,details:{queue:t}}:{name:"job-queue-progress",status:"healthy",message:"Due jobs are being claimed",details:{queue:t}}}function Hu(e,t){if(!e||!t)return{name:"job-execution-inventory",status:"degraded",message:"Job execution inventory is unavailable"};let r=zr(e,t),i=r.reduce((n,o)=>n+o.count,0);return i===0?{name:"job-execution-inventory",status:"healthy",message:"Every active job type has a declared executor"}:{name:"job-execution-inventory",status:"degraded",message:`${i} active job(s) have no declared executor`,details:{jobs:r}}}function qu(e){if(!e)return{name:"attempt-leases",status:"degraded",message:"Lease state is unavailable"};return e.staleLeaseCount===0?{name:"attempt-leases",status:"healthy",message:"No stale processing leases"}:{name:"attempt-leases",status:"degraded",message:`${e.staleLeaseCount} processing lease(s) are stale`,details:{staleLeaseCount:e.staleLeaseCount}}}function Ju(e){if(!e.initialized)return{name:"projection-circuits",status:"degraded",message:"Projection runtime supervisor is not initialized"};if(e.openCircuits.length===0)return{name:"projection-circuits",status:"healthy",message:"No projection circuits are open"};return{name:"projection-circuits",status:"degraded",message:`${e.openCircuits.length} projection circuit(s) open`,details:{circuits:e.openCircuits}}}async function Gu(e){let t=e.entityService.getProjectionStore(),[r,i,n]=await Promise.all([t.getActiveWave(),t.getUnresolvedProjectionIncidentDiagnostics(Fu),t.getProjectionBatchDiagnostics?.()??Promise.resolve({preparing:0,open:0,abandoned:0,expiredCallbackLeases:0,oldestActiveAgeMs:null,oldestProgressAgeMs:null})]);if(!r)return{waveId:null,batches:n,strandedRules:[],incidentCount:i.total,incidents:i.incidents};let s=(await t.listWaveRules(r.id)).filter((c)=>c.status==="queued"||c.status==="failed"),a=(await Promise.all(s.map(async(c)=>{let d=c.jobId?await e.jobQueueService.getStatus(c.jobId):null;if(c.status!=="failed"&&d&&(d.status==="pending"||d.status==="processing"))return null;return{ruleId:c.ruleId,jobId:c.jobId,jobStatus:d?.status??"missing"}}))).filter((c)=>c!==null);return{waveId:r.id,batches:n,strandedRules:a,incidentCount:i.total,incidents:i.incidents}}function Qu(e){if(e.batches.abandoned>0)return{name:"projection-waves",status:"degraded",message:`${e.batches.abandoned} projection batch(es) await recovery`,details:{batches:e.batches}};if(e.batches.expiredCallbackLeases>0)return{name:"projection-waves",status:"degraded",message:"A callback projection batch lease has expired",details:{batches:e.batches}};if(e.incidentCount>0)return{name:"projection-waves",status:"degraded",message:`${e.incidentCount} unresolved terminal projection incident(s)`,details:{incidentCount:e.incidentCount,incidentsTruncated:e.incidentCount>e.incidents.length,incidents:e.incidents.map((t)=>({waveId:t.waveId,ruleId:t.ruleId,jobId:t.jobId,failureReason:t.failureReason,createdAt:t.createdAt}))}};if(!e.waveId)return{name:"projection-waves",status:"healthy",message:e.batches.open+e.batches.preparing>0?`${e.batches.open+e.batches.preparing} projection batch(es) active`:"No active projection wave",...e.batches.open+e.batches.preparing>0&&{details:{batches:e.batches}}};if(e.strandedRules.length===0)return{name:"projection-waves",status:"healthy",message:`Projection wave ${e.waveId} is progressing`};return{name:"projection-waves",status:"degraded",message:`Projection wave ${e.waveId} has ${e.strandedRules.length} stranded rule job(s)`,details:{waveId:e.waveId,strandedRules:e.strandedRules}}}function Ku(e){let t=e.filter((r)=>r.status!=="running"||r.health?.status==="error");return t.length===0?{name:"daemons",status:"healthy",message:`${e.length} daemon(s) healthy`}:{name:"daemons",status:"degraded",message:`${t.length} daemon(s) unhealthy`,details:{daemons:t.map((r)=>({name:r.name,status:r.status,health:r.health?.status,message:r.health?.message}))}}}async function Tn(e){let t=e.now?.()??Date.now(),r=(e.memoryUsage??process.memoryUsage)(),[i,n,o,s,a,c,d,u]=await Promise.allSettled([e.entityService.getEntityCounts(ft("runtime readiness database probe")),e.jobQueueService.getDiagnostics(t),Promise.resolve(e.jobQueueService.getExecutionRegistrations()),e.daemonRegistry.getStatuses(),(e.readProcessSignals??Nu)(),e.projectionRuntimeSupervisor.getDiagnostics(),Gu(e),e.operationalHealthRegistry.getChecks()]),p=n.status==="fulfilled"?n.value:null,m=o.status==="fulfilled"?o.value??null:null,g=s.status==="fulfilled"?s.value:[],f=a.status==="fulfilled"?a.value:{fileDescriptors:null,processCount:null,zombieCount:null},h=c.status==="fulfilled"?c.value:{status:"unhealthy",initialized:!1,trackedRoots:0,openCircuits:[]},w=[Cn("entity-database",i,"Entity database is accessible"),Cn("job-queue-database",n,"Job queue database is accessible"),Zu(p),Wu(p),Hu(p,m),qu(p),c.status==="fulfilled"?Ju(h):{name:"projection-circuits",status:"degraded",message:P(c.reason)},d.status==="fulfilled"?Qu(d.value):{name:"projection-waves",status:"degraded",message:P(d.reason)},s.status==="fulfilled"?Ku(g):{name:"daemons",status:"degraded",message:P(s.reason)}],b=u.status==="fulfilled"?u.value:[{name:"plugin-operational-health",status:"degraded",message:"Plugin operational health is unavailable"}],S=[...w,...b];return{status:w.some((y)=>y.status==="unhealthy")?"not_ready":"ready",operationalStatus:S.some((y)=>y.status!=="healthy")?"degraded":"operational",checkedAt:new Date(t).toISOString(),checks:S,resources:{memory:{rssBytes:r.rss,heapUsedBytes:r.heapUsed,heapTotalBytes:r.heapTotal},fileDescriptors:f.fileDescriptors,processes:{total:f.processCount,zombies:f.zombieCount},queue:p,projection:{initialized:h.initialized,trackedRoots:h.trackedRoots,openCircuits:h.openCircuits},worker:p?.workerSessions??{total:0,active:0,stale:0,latestHeartbeatAgeMs:null}}}}function En(){return{dataDir:"./data",cacheDir:"./cache",distDir:"./dist"}}function ye(e){return{database:{url:`file:${e.dataDir}/brain.db`},jobQueueDatabase:{url:`file:${e.dataDir}/brain-jobs.db`},conversationDatabase:{url:`file:${e.dataDir}/conversations.db`},runtimeStateDatabase:{url:`file:${e.dataDir}/runtime-state.db`},embeddingDatabase:{url:`file:${e.dataDir}/embeddings.db`},embedding:{enabled:!0}}}var He=l.strictObject({enabled:l.boolean().optional().describe("Serve HTTP; defaults to whether the selected bundles host the web surface"),preview:l.boolean().optional().describe("Serve the preview site; defaults to whether a site builder runs"),hostname:l.string().trim().min(1).optional().describe("Bind address; use 127.0.0.1 for isolated local tests"),productionDistDir:l.string().min(1).optional().describe("Directory of the production site, when no site builder writes it"),previewDistDir:l.string().min(1).optional().describe("Directory of the preview site, when no site builder writes it"),sharedImagesDir:l.string().min(1).optional().describe("Directory of shared optimized images")}),Or=He.extend({enabled:l.boolean().default(!1),preview:l.boolean().default(!0),port:l.number().default(8080).describe("Port of the production listener")});var ne=l.enum(["debug","info","warn","error"]);var Lr=En(),Vu=l.looseObject({label:l.string().min(1),pluralName:l.string().optional(),layout:l.string().optional(),paginate:l.boolean().optional(),pageSize:l.number().optional(),navigation:l.object({show:l.boolean().optional(),slot:l.enum(["primary","secondary"]).optional(),priority:l.number().optional()}).optional()});function Ur(){return ye(Lr)}var Br=l.object({name:l.string().default("brain-app"),version:l.string().default("1.0.0"),database:Ee,jobQueueDatabase:Ee,jobQueue:l.object({workerConcurrency:l.number().int().min(1).max(32).default(4)}).prefault({}),conversationDatabase:Ee,runtimeStateDatabase:Ee,embeddingDatabase:Ee,ai:l.object({providerKeys:qe.default({}),model:l.string().refine(kn,{error:(e)=>`Unsupported model "${String(e.input)}"`}),embeddingModel:l.string().refine((e)=>Mr(e)!==void 0,{error:(e)=>Dn(String(e.input))}).default(jn),modelRuntimeUrl:l.string().url().optional(),answerModel:l.string().optional(),visionModel:l.string().optional(),imageModel:l.string().optional(),temperature:l.number().min(0).max(2).default(0.7),webSearch:l.boolean().default(!0),reasoningEffort:oe.optional()}).superRefine((e,t)=>{if(e.answerModel&&be(e.answerModel)!=="local")t.addIssue({code:"custom",path:["answerModel"],message:`answerModel must be a local: model, not ${e.answerModel}`});if(e.visionModel&&be(e.visionModel)!=="local")t.addIssue({code:"custom",path:["visionModel"],message:`visionModel must be a local: model, not ${e.visionModel}`});if(e.modelRuntimeUrl)return;let r=[...be(e.model)==="local"?[e.model]:[],...[e.answerModel,e.visionModel].filter((i)=>i!==void 0&&be(i)==="local"),...e.imageModel&&An(e.imageModel).provider==="local"?[e.imageModel]:[],...Mr(e.embeddingModel)?.provider==="local"?[e.embeddingModel]:[]];for(let i of r)t.addIssue({code:"custom",path:["modelRuntimeUrl"],message:`${i} needs modelRuntime.url`})}),embedding:l.object({enabled:l.boolean().default(!0)}),logging:l.object({level:ne.default("info"),format:l.enum(["text","json"]).default("text"),file:l.string().optional(),context:l.string().default("shell")}).prefault({level:"info",context:"shell"}),features:l.object({}).default({}),plugins:l.array(ht).default([]),dataDir:l.string().default("./brain-data"),gitBrokerSocket:l.string().min(1).optional(),gitBrokerCheckout:l.string().min(1).optional(),spaces:l.array(l.string()).default([]),siteBaseUrl:l.string().optional(),localSiteUrl:l.string().optional(),preferLocalUrls:l.boolean().default(!1),production:l.boolean().default(!1),themeCSS:l.string().default(""),entityDisplay:l.record(l.string(),Vu).optional(),profileKind:l.string().trim().min(1).optional(),http:Or.prefault({})});function yt(e={}){let{plugins:t=[],permissions:r={},identity:i,profile:n,agentInstructions:o,evalHandlerRegistry:s,ai:a,logging:c,embedding:d,jobQueue:u,...p}=e,{entityDisplay:m,...g}=Br.parse({...Ur(),...H(p),ai:H({...a}),logging:H({...c}),embedding:H({...d}),jobQueue:H({...u}),plugins:[]});return{...g,plugins:t,permissions:r,...H({entityDisplay:m,identity:i,profile:n,agentInstructions:o,evalHandlerRegistry:s})}}var B={NOTE:"note",BRAIN_CHARACTER:"brain-character",ANCHOR_PROFILE:"anchor-profile"},Je={KNOWLEDGE_QUERY:"shell:knowledge-query",BASE_ENTITY_DISPLAY:"shell:base-entity-display",CONTENT_GENERATION:"shell:content-generation"},$r={ENTITIES:"shell:entities"};var Yu=zn.extend({templateName:l.string()}),Xu=l.object({slug:l.string()}),ep="The style guide governs voice, tone, wording and form: paragraphing, sentence rhythm, hooks, rhetorical questions and calls to action. The instructions below and any additional instructions in the request govern the task, required content, length limits, platform constraints and output format. When either conflicts with the style guide on voice or form, follow the style guide.",tp="Generate the content described in your instructions.";function rp(e){return e instanceof l.ZodType}function ip(e){if(!e)return;return e.replace(/^https?:\/\//,"").replace(/\/$/,"")}class vt{aiService;entityService;templateRegistry;getIdentityContent;getProfileContent;entityUrls;id="ai-content";name="AI Content Generator";description="Generates content using AI based on templates and prompts";constructor(e,t,r,i,n,o,s){this.aiService=e,this.entityService=t,this.templateRegistry=r,this.getIdentityContent=i,this.getProfileContent=n,this.entityUrls=o,this.siteBaseUrl=ip(s)}siteBaseUrl;async generate(e,t,r){return this.generateWithContext(e,t,r)}async generateScoped(e,t,r){return this.generateWithContext(e,t,r.signal,r)}async generateWithContext(e,t,r,i){r?.throwIfAborted();let n=Yu.parse(e),o=this.templateRegistry.get(n.templateName);if(!o)throw Error(`Template not found: ${n.templateName}`);if(!o.basePrompt)throw Error(`Template ${n.templateName} must have basePrompt for content generation`);let s=i?await On((w,b)=>i.getEntity(w,b),n.templateName,o.basePrompt):await bt(this.entityService,n.templateName,o.basePrompt);r?.throwIfAborted();let a=[s,n.prompt].filter(Boolean).join(" "),c=a.length>0&&o.useKnowledgeContext===!0,d=this.entityService.getWeightMap(),u=Object.keys(d).length>0,p=c?i?await i.search(a,{limit:5,...u&&{weight:d}}):await this.entityService.search({query:a,options:{limit:5,...u&&{weight:d},...r&&{signal:r}}}):[];r?.throwIfAborted();let m=this.buildPrompt(n,p),g=i?await this.readIdentities(i,n.representedIdentity):void 0,f=this.buildSystemPrompt(s,n,g);if(!rp(o.schema))throw Error(`Template ${o.name} cannot be used for AI generation: schema is not an AI generation schema`);r?.throwIfAborted();let h=await this.aiService.generateObject(f,m,o.schema,r);return r?.throwIfAborted(),t.parse(h.object)}async readIdentities(e,t){let r=async(o)=>(await e.getEntity(o,o))?.content??"",[i,n]=await Promise.all([t!=="none"?r(B.BRAIN_CHARACTER):"",t===void 0||t==="anchor"?r(B.ANCHOR_PROFILE):""]);return{brain:i,anchor:n}}buildSystemPrompt(e,t,r){let i=[];if(t.representedIdentity===void 0||t.representedIdentity==="brain"||t.representedIdentity==="anchor")i.push("# Brain Identity",r?.brain??this.getIdentityContent(),"");if(t.representedIdentity===void 0||t.representedIdentity==="anchor")i.push("# Represented Anchor",r?.anchor??this.getProfileContent(),"");let n=this.selectStyleGuidance(t);if(n)i.push("# Style Guide",n,"","# Precedence",ep,"");return i.push("# Instructions",e),i.join(`
3
3
  `)}selectStyleGuidance(e){if(!e.styleGuide)return"";let t=[];if(e.styleGuide.voice)t.push("## Voice",e.styleGuide.voice);if(e.styleGuide.visual)t.push("## Visual",e.styleGuide.visual);return t.join(`
4
4
  `)}buildPrompt(e,t=[]){let r=[];if(e.conversationHistory)r.push(`Recent conversation context:
5
5
  ${e.conversationHistory}`);if(t.length>0){let i=t.map((n)=>this.formatRelevantEntity(n,this.entityUrls)).join(`
@@ -115,4 +115,4 @@ ${rl(i)}`:a,args:t.buildArgs((d)=>({...c,confirmed:!0,confirmationToken:d}))}}as
115
115
  export{ye as je,He as ke,ne as le,yt as me,k as ne,wp as oe,Rp as pe,Ip as qe,kp as re,ao as se,jp as te,Dp as ue,zp as ve,Op as we,Mp as xe,Lp as ye,Up as ze,ei as Ae,pa as Be,Ri as Ce,Oc as De,Yf as Ee,Al as Fe,rh as Ge,Dl as He,lt as Ie,ih as Je,xe as Ke,Ki as Le,Vi as Me,Yi as Ne,oh as Oe,lh as Pe,dh as Qe,$l as Re,_l as Se,mh as Te,gh as Ue,fh as Ve,hh as We,an as Xe,yh as Ye,bh as Ze,Rh as _e,Kh as $e,Vh as af,mn as bf,su as cf,lu as df,mu as ef,gu as ff,dy as gf,ID as hf,TD as if,WD as jf,HD as kf};
116
116
 
117
117
  //# debugId=25147941FDF0CCD764756E2164756E21
118
- //# sourceMappingURL=index-dbc02tv7.js.map
118
+ //# sourceMappingURL=index-n7f1g306.js.map
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{a as j,b as T}from"./index-yjydtxs6.js";import{d as g,e as m}from"./index-gpe7rmb7.js";import"./index-e84v85w3.js";import{fe as Z}from"./index-e0qz6mam.js";import"./index-x8e40qwv.js";import"./index-8evv41se.js";import{Cn as H,On as w,Pn as M,Sn as D,Zn as O,lo as E,nm as N,om as F,um as I,vm as P,wm as R,xm as L,ym as B}from"./index-stpp3r8b.js";import{aq as S,mr as A}from"./index-431k3883.js";import"./index-y95tc91a.js";import"./index-954p4889.js";import{ID as v}from"./index-7mq8b26b.js";import"./index-1hskk22v.js";import{RD as b}from"./index-3w684dmw.js";var x=v.object({theme:v.object({primaryColor:v.string().describe("Primary color for the CLI theme").default("#0066cc"),accentColor:v.string().describe("Accent color for the CLI theme").default("#ff6600")}).describe("Theme configuration for the CLI interface").default({primaryColor:"#0066cc",accentColor:"#ff6600"})});var V={completed:"\u2713",declined:"\u25CB",failed:"\u2717"},q={deniedCardIds:void 0,resolveUrl:(r)=>r,isHiddenUrl:()=>!1,eventActionUnavailableLabel:void 0},y="cli",k={identity:{kind:"external",externalActorId:S("cli","operator")},interfaceType:"cli",role:"user"};function _(){return{inkApp:null,removeSignalHandlers:void 0,responseCallback:void 0,systemMessageCallback:void 0}}function z(r,e){let{logger:t}=r,o=new D({loadMessages:async(i)=>r.conversations.getMessages(i,{limit:50}),onRestoreError:(i,s)=>{t.debug("Failed to restore pending CLI approvals",{error:i,conversationId:s})}}),n=(i)=>{e.responseCallback?.(i)},a=()=>r.permissions.isAnchor("cli","local"),u=async(i,s)=>{let l=new Set(s);if(!M(i,l))return!1;let c=w({message:Y(i,s),approvalIds:l});if(c.kind==="not-confirmation")return!1;if(c.kind==="notice")return n(`_${c.message}_`),!0;o.removeApproval(y,c.approvalId);let C=await r.agent.confirmPendingAction(y,c.confirmed,c.approvalId,{userPermissionLevel:"admin",isAnchor:a(),interfaceType:"cli",actor:k});return o.syncFromResponse(y,C,c.approvalId),n(K(C.text,C.cards)),!0};return{async processInput(i){r.messages.startProcessingInput();try{let s=[...await o.getApprovalIds(y)];if(s.length>0){if(await u(i,s))return}let l=await r.agent.chat(i,y,{userPermissionLevel:"admin",isAnchor:a(),interfaceType:"cli",channelId:"cli",channelName:"CLI Terminal",actor:k}),c=P(l.cards),C=c.length>0?c.map((p)=>p.id):l.pendingConfirmations?.map((p)=>p.id)??[];o.replaceApprovals(y,C);let h=G(l);t.debug("Agent response received",{textLength:l.text.length,toolResultsCount:l.toolResults?.length??0,toolResults:l.toolResults?.map((p)=>({toolName:p.toolName,hasData:p.data!==void 0}))}),n(h)}catch(s){t.error("Error processing input",{error:s,input:i});let l=A(s,"An unknown error occurred");n(`**Error:** ${l}`)}finally{r.messages.endProcessingInput()}}}}function G(r){let e=O(r,{deniedCardIds:void 0}),t=[],o=[],n="";for(let a of e.directives)switch(a.kind){case"text":n=a.text;break;case"approvals":t.push(...a.cards);break;default:if(a.card.kind==="tool-approval"&&a.card.state==="approval-requested"){t.push(a.card);break}o.push(E(a.card,q))}return[J(n,t),...o].filter((a)=>a.trim().length>0).join(`
2
+ import{a as j,b as T}from"./index-yjydtxs6.js";import{d as g,e as m}from"./index-gpe7rmb7.js";import"./index-e84v85w3.js";import{fe as Z}from"./index-e0qz6mam.js";import"./index-x8e40qwv.js";import"./index-8evv41se.js";import{Cn as H,On as w,Pn as M,Sn as D,Zn as O,lo as E,nm as N,om as F,um as I,vm as P,wm as R,xm as L,ym as B}from"./index-cj5gzzsn.js";import{aq as S,mr as A}from"./index-431k3883.js";import"./index-y95tc91a.js";import"./index-954p4889.js";import{ID as v}from"./index-7mq8b26b.js";import"./index-1hskk22v.js";import{RD as b}from"./index-3w684dmw.js";var x=v.object({theme:v.object({primaryColor:v.string().describe("Primary color for the CLI theme").default("#0066cc"),accentColor:v.string().describe("Accent color for the CLI theme").default("#ff6600")}).describe("Theme configuration for the CLI interface").default({primaryColor:"#0066cc",accentColor:"#ff6600"})});var V={completed:"\u2713",declined:"\u25CB",failed:"\u2717"},q={deniedCardIds:void 0,resolveUrl:(r)=>r,isHiddenUrl:()=>!1,eventActionUnavailableLabel:void 0},y="cli",k={identity:{kind:"external",externalActorId:S("cli","operator")},interfaceType:"cli",role:"user"};function _(){return{inkApp:null,removeSignalHandlers:void 0,responseCallback:void 0,systemMessageCallback:void 0}}function z(r,e){let{logger:t}=r,o=new D({loadMessages:async(i)=>r.conversations.getMessages(i,{limit:50}),onRestoreError:(i,s)=>{t.debug("Failed to restore pending CLI approvals",{error:i,conversationId:s})}}),n=(i)=>{e.responseCallback?.(i)},a=()=>r.permissions.isAnchor("cli","local"),u=async(i,s)=>{let l=new Set(s);if(!M(i,l))return!1;let c=w({message:Y(i,s),approvalIds:l});if(c.kind==="not-confirmation")return!1;if(c.kind==="notice")return n(`_${c.message}_`),!0;o.removeApproval(y,c.approvalId);let C=await r.agent.confirmPendingAction(y,c.confirmed,c.approvalId,{userPermissionLevel:"admin",isAnchor:a(),interfaceType:"cli",actor:k});return o.syncFromResponse(y,C,c.approvalId),n(K(C.text,C.cards)),!0};return{async processInput(i){r.messages.startProcessingInput();try{let s=[...await o.getApprovalIds(y)];if(s.length>0){if(await u(i,s))return}let l=await r.agent.chat(i,y,{userPermissionLevel:"admin",isAnchor:a(),interfaceType:"cli",channelId:"cli",channelName:"CLI Terminal",actor:k}),c=P(l.cards),C=c.length>0?c.map((p)=>p.id):l.pendingConfirmations?.map((p)=>p.id)??[];o.replaceApprovals(y,C);let h=G(l);t.debug("Agent response received",{textLength:l.text.length,toolResultsCount:l.toolResults?.length??0,toolResults:l.toolResults?.map((p)=>({toolName:p.toolName,hasData:p.data!==void 0}))}),n(h)}catch(s){t.error("Error processing input",{error:s,input:i});let l=A(s,"An unknown error occurred");n(`**Error:** ${l}`)}finally{r.messages.endProcessingInput()}}}}function G(r){let e=O(r,{deniedCardIds:void 0}),t=[],o=[],n="";for(let a of e.directives)switch(a.kind){case"text":n=a.text;break;case"approvals":t.push(...a.cards);break;default:if(a.card.kind==="tool-approval"&&a.card.state==="approval-requested"){t.push(a.card);break}o.push(E(a.card,q))}return[J(n,t),...o].filter((a)=>a.trim().length>0).join(`
3
3
 
4
4
  `)}function J(r,e){if(e.length===0)return r;let t=L(r,e);if(e.length===1){let n=e[0];if(!n)return r;let a=n.preview?`
5
5
 
@@ -16,4 +16,4 @@ _Please reply with **yes 1** / **no 1** for the matching action._`}function K(r,
16
16
  ${o.error}`:`${n} ${o.summary}`}function Y(r,e){let t=/^(.*?)\s+#?(\d+)$/.exec(r.trim());if(!t?.[1]||!t[2])return r;let o=e[Number(t[2])-1];return o?`${t[1]} ${o}`:r}var Q=H({id:"cli",config:x,setup:(r)=>(I(r).logger.debug("CLI interface registered with AgentService"),_())}),W=N(Q,(r)=>{let{state:e}=r,t=I(r),{logger:o,messages:n}=t,a=z(t,e),u=()=>{e.responseCallback=void 0,e.systemMessageCallback=void 0},i=()=>{if(n.unregisterProgressCallback(),u(),e.removeSignalHandlers?.(),e.removeSignalHandlers=void 0,e.inkApp)e.inkApp.unmount(),e.inkApp=null};return{id:"cli",start:async()=>{o.debug("Starting CLI interface");try{let[s,l,c]=await Promise.all([import("./index-j7ajy2fp.js"),import("react"),import("./EnhancedApp-kpm7x2f0.js")]),h=l.default.createElement(c.default,{interface:a,registerProgressCallback:(p)=>{n.registerProgressCallback(p)},unregisterProgressCallback:()=>{n.unregisterProgressCallback()},registerResponseCallback:(p)=>{e.responseCallback=p},registerSystemMessageCallback:(p)=>{e.systemMessageCallback=p},unregisterMessageCallbacks:u});e.inkApp=s.render(h),e.removeSignalHandlers=Z(["SIGINT","SIGTERM"],()=>{o.debug("Received termination signal, stopping CLI"),i()})}catch(s){throw o.error("Failed to start CLI interface",{error:s}),s}},stop:async()=>{o.debug("Stopping CLI interface"),i()},healthCheck:async()=>{let s=e.inkApp!==null;return{status:s?"healthy":"error",message:s?"CLI interface is running":"CLI interface not running",lastCheck:new Date,details:{hasInkApp:e.inkApp!==null,hasCallbacks:n.hasProgressCallback()}}}}}),X=F(W,({state:r})=>({send:({message:e})=>{let t=typeof e==="string"?e:e.fallbackText??"";if(!t)return;(r.systemMessageCallback??r.responseCallback)?.(t)}})),ee=X;import{jsx as d,jsxs as f}from"react/jsx-runtime";function re({batchStatus:r,showDetails:e=!0}){let{batchId:t,totalOperations:o,completedOperations:n,failedOperations:a,currentOperation:u,errors:i,status:s}=r,l=s==="processing",c=s==="completed",C=s==="failed",h=n-a;return f(g,{flexDirection:"column",marginY:1,children:[d(g,{marginBottom:1,children:f(m,{bold:!0,color:"cyan",children:["Batch Operation: ",t.slice(0,8),"..."]})}),d(g,{marginBottom:1,children:d(T,{current:n,total:o,message:"Overall Progress:",color:C?"red":c?"green":"yellow"})}),l&&u&&f(g,{marginBottom:1,children:[d(m,{color:"green",children:d(j,{type:"dots"})}),f(m,{color:"gray",children:[" ",u]})]}),e&&f(g,{flexDirection:"column",marginLeft:2,children:[h>0&&f(g,{children:[d(m,{color:"green",children:"\u2713 "}),f(m,{color:"gray",children:[h," successful"]})]}),a>0&&f(g,{children:[d(m,{color:"red",children:"\u2717 "}),f(m,{color:"gray",children:[a," failed"]})]}),i.length>0&&f(g,{flexDirection:"column",marginTop:1,children:[d(m,{color:"red",bold:!0,children:"Errors:"}),i.slice(0,3).map((p,U)=>f(g,{marginLeft:2,children:[d(m,{color:"red",children:"\u2022 "}),d(m,{color:"gray",children:p})]},U)),i.length>3&&d(g,{marginLeft:2,children:f(m,{color:"gray",children:["... and ",i.length-3," more"]})})]})]}),c&&d(g,{marginTop:1,children:d(m,{color:"green",bold:!0,children:"\u2713 Batch completed successfully"})}),C&&d(g,{marginTop:1,children:d(m,{color:"red",bold:!0,children:"\u2717 Batch failed"})})]})}export{re as BatchProgress,T as ProgressBar,x as cliConfigSchema,ee as default};
17
17
 
18
18
  //# debugId=A7A06F0E14D7CC2E64756E2164756E21
19
- //# sourceMappingURL=index-gecxg7ew.js.map
19
+ //# sourceMappingURL=index-tfn1jn8z.js.map
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import"./index-3w684dmw.js";var n="@brains/chat-repl",i="AGPL-3.0-only",t="0.2.0-alpha.859",r={"@brains/contracts":"workspace:*","@brains/sdk":"workspace:*","@brains/utils":"workspace:*",chalk:"^5.4.1",ink:"^7.0.6","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0",marked:"^18.0.5",react:"^19.2.7"},a={"@brains/eslint-config":"workspace:*","@brains/plugins":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.4.0","@types/react":"^19.2.17",typescript:"^7.0.2"},c=["src"],p="./src/index.ts",l="./src/index.ts",o=!0,k={dev:"tsc --watch",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},d="module",b="./src/index.ts",w={name:n,license:i,version:t,dependencies:r,devDependencies:a,files:c,main:p,module:l,private:o,scripts:k,type:d,types:b};export{w as default,r as dependencies,a as devDependencies,c as files,i as license,p as main,l as module,n as name,o as private,k as scripts,d as type,b as types,t as version};
2
+ import"./index-3w684dmw.js";var n="@brains/chat-repl",i="AGPL-3.0-only",t="0.2.0-alpha.860",r={"@brains/contracts":"workspace:*","@brains/sdk":"workspace:*","@brains/utils":"workspace:*",chalk:"^5.4.1",ink:"^7.0.6","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0",marked:"^18.0.5",react:"^19.2.7"},a={"@brains/eslint-config":"workspace:*","@brains/plugins":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.4.0","@types/react":"^19.2.17",typescript:"^7.0.2"},c=["src"],p="./src/index.ts",l="./src/index.ts",o=!0,k={dev:"tsc --watch",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},d="module",b="./src/index.ts",w={name:n,license:i,version:t,dependencies:r,devDependencies:a,files:c,main:p,module:l,private:o,scripts:k,type:d,types:b};export{w as default,r as dependencies,a as devDependencies,c as files,i as license,p as main,l as module,n as name,o as private,k as scripts,d as type,b as types,t as version};
3
3
 
4
- //# debugId=CF4671CED1D80A0864756E2164756E21
5
- //# sourceMappingURL=package-r6q4rydp.js.map
4
+ //# debugId=EC4DAF2D885D470F64756E2164756E21
5
+ //# sourceMappingURL=package-73axy3ng.js.map
@@ -4,6 +4,6 @@
4
4
  "sourcesContent": [
5
5
  ],
6
6
  "mappings": "",
7
- "debugId": "CF4671CED1D80A0864756E2164756E21",
7
+ "debugId": "EC4DAF2D885D470F64756E2164756E21",
8
8
  "names": []
9
9
  }
package/dist/entities.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import"./chunks/index-624fhq2j.js";import{Nl as t,Rl as x,Sl as a,Tl as b,Ul as c,Vl as d,Wl as g,gh as m,ui as p}from"./chunks/index-stpp3r8b.js";import{tq as f}from"./chunks/index-431k3883.js";import"./chunks/index-y95tc91a.js";import"./chunks/index-954p4889.js";import{ID as e}from"./chunks/index-7mq8b26b.js";import"./chunks/index-1hskk22v.js";import"./chunks/index-3w684dmw.js";export{m as ProjectionJsonObjectSchema,f as defineChannel,t as defineDashboardWidget,x as defineDataSource,a as defineEntity,b as defineEntityAnalyticsReport,c as defineEntityJob,g as defineEntityPackage,d as defineProjection,p as defineProjectionRule,e as z};
2
+ import"./chunks/index-624fhq2j.js";import{Nl as t,Rl as x,Sl as a,Tl as b,Ul as c,Vl as d,Wl as g,gh as m,ui as p}from"./chunks/index-cj5gzzsn.js";import{tq as f}from"./chunks/index-431k3883.js";import"./chunks/index-y95tc91a.js";import"./chunks/index-954p4889.js";import{ID as e}from"./chunks/index-7mq8b26b.js";import"./chunks/index-1hskk22v.js";import"./chunks/index-3w684dmw.js";export{m as ProjectionJsonObjectSchema,f as defineChannel,t as defineDashboardWidget,x as defineDataSource,a as defineEntity,b as defineEntityAnalyticsReport,c as defineEntityJob,g as defineEntityPackage,d as defineProjection,p as defineProjectionRule,e as z};
3
3
 
4
4
  //# debugId=4A5DD84A5CBB1E0664756E2164756E21
5
5
  //# sourceMappingURL=entities.js.map
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{nf as d,of as t}from"./chunks/index-3erkk0g4.js";import{pl as a}from"./chunks/index-stpp3r8b.js";import"./chunks/index-431k3883.js";import"./chunks/index-y95tc91a.js";import"./chunks/index-954p4889.js";import"./chunks/index-7mq8b26b.js";import"./chunks/index-1hskk22v.js";import"./chunks/index-3w684dmw.js";function s(e,i){let o=new Set,n=new Set;for(let r of e){if(!t(r))throw Error(`${i} contains a value that was not returned by use()`);if(o.has(r.definition))throw Error(`${i} contains duplicate plugin definition "${r.definition.id}"; include each configured definition only once`);if(n.has(r.definition.id))throw Error(`${i} contains duplicate local plugin id "${r.definition.id}"; give each package definition a unique local id before composing it`);o.add(r.definition),n.add(r.definition.id)}}function l(e){a(e.id,"Bundle id"),s(e.members,`Bundle "${e.id}"`);for(let i of e.config??[])if(!t(i.member))throw Error(`Bundle "${e.id}" config contains a value that was not returned by use()`);for(let i of e.permissions??[])if(!t(i.member))throw Error(`Bundle "${e.id}" permissions contains a value that was not returned by use()`);for(let i of e.evalDisable??[])if(!t(i))throw Error(`Bundle "${e.id}" evalDisable contains a value that was not returned by use()`);return Object.freeze({...e,members:Object.freeze([...e.members]),...e.config?{config:Object.freeze([...e.config])}:{},...e.permissions?{permissions:Object.freeze([...e.permissions])}:{},...e.agentInstructions?{agentInstructions:Object.freeze([...e.agentInstructions])}:{},...e.evalDisable?{evalDisable:Object.freeze([...e.evalDisable])}:{}})}function u(e){if(!e.name.trim())throw Error("Brain name must not be empty");if(e.bundleContract?.trim().length===0)throw Error("Brain bundleContract must not be empty");s(e.plugins,`Brain "${e.name}"`);let i=new Set(e.plugins),o=new Set;for(let n of e.bundles??[]){if(o.has(n.id))throw Error(`Brain "${e.name}" has duplicate bundle "${n.id}"`);o.add(n.id);for(let r of n.members)if(!i.has(r))throw Error(`Brain "${e.name}" bundle "${n.id}" references a plugin outside its catalog`);for(let r of n.config??[])if(!i.has(r.member))throw Error(`Brain "${e.name}" bundle "${n.id}" config references a plugin outside its catalog`);for(let r of n.permissions??[])if(!i.has(r.member))throw Error(`Brain "${e.name}" bundle "${n.id}" permissions reference a plugin outside its catalog`);for(let r of n.evalDisable??[])if(!i.has(r))throw Error(`Brain "${e.name}" bundle "${n.id}" evalDisable references a plugin outside its catalog`)}for(let n of e.evalDisable??[])if(!i.has(n))throw Error(`Brain "${e.name}" evalDisable references a plugin outside its catalog`);return Object.freeze({...e,plugins:Object.freeze([...e.plugins]),...e.bundles?{bundles:Object.freeze([...e.bundles])}:{},...e.agentInstructions?{agentInstructions:Object.freeze([...e.agentInstructions])}:{},...e.evalDisable?{evalDisable:Object.freeze([...e.evalDisable])}:{}})}export{u as defineBrain,l as defineBundle,d as use};
2
+ import{nf as d,of as t}from"./chunks/index-g9bpep2g.js";import{pl as a}from"./chunks/index-cj5gzzsn.js";import"./chunks/index-431k3883.js";import"./chunks/index-y95tc91a.js";import"./chunks/index-954p4889.js";import"./chunks/index-7mq8b26b.js";import"./chunks/index-1hskk22v.js";import"./chunks/index-3w684dmw.js";function s(e,i){let o=new Set,n=new Set;for(let r of e){if(!t(r))throw Error(`${i} contains a value that was not returned by use()`);if(o.has(r.definition))throw Error(`${i} contains duplicate plugin definition "${r.definition.id}"; include each configured definition only once`);if(n.has(r.definition.id))throw Error(`${i} contains duplicate local plugin id "${r.definition.id}"; give each package definition a unique local id before composing it`);o.add(r.definition),n.add(r.definition.id)}}function l(e){a(e.id,"Bundle id"),s(e.members,`Bundle "${e.id}"`);for(let i of e.config??[])if(!t(i.member))throw Error(`Bundle "${e.id}" config contains a value that was not returned by use()`);for(let i of e.permissions??[])if(!t(i.member))throw Error(`Bundle "${e.id}" permissions contains a value that was not returned by use()`);for(let i of e.evalDisable??[])if(!t(i))throw Error(`Bundle "${e.id}" evalDisable contains a value that was not returned by use()`);return Object.freeze({...e,members:Object.freeze([...e.members]),...e.config?{config:Object.freeze([...e.config])}:{},...e.permissions?{permissions:Object.freeze([...e.permissions])}:{},...e.agentInstructions?{agentInstructions:Object.freeze([...e.agentInstructions])}:{},...e.evalDisable?{evalDisable:Object.freeze([...e.evalDisable])}:{}})}function u(e){if(!e.name.trim())throw Error("Brain name must not be empty");if(e.bundleContract?.trim().length===0)throw Error("Brain bundleContract must not be empty");s(e.plugins,`Brain "${e.name}"`);let i=new Set(e.plugins),o=new Set;for(let n of e.bundles??[]){if(o.has(n.id))throw Error(`Brain "${e.name}" has duplicate bundle "${n.id}"`);o.add(n.id);for(let r of n.members)if(!i.has(r))throw Error(`Brain "${e.name}" bundle "${n.id}" references a plugin outside its catalog`);for(let r of n.config??[])if(!i.has(r.member))throw Error(`Brain "${e.name}" bundle "${n.id}" config references a plugin outside its catalog`);for(let r of n.permissions??[])if(!i.has(r.member))throw Error(`Brain "${e.name}" bundle "${n.id}" permissions reference a plugin outside its catalog`);for(let r of n.evalDisable??[])if(!i.has(r))throw Error(`Brain "${e.name}" bundle "${n.id}" evalDisable references a plugin outside its catalog`)}for(let n of e.evalDisable??[])if(!i.has(n))throw Error(`Brain "${e.name}" evalDisable references a plugin outside its catalog`);return Object.freeze({...e,plugins:Object.freeze([...e.plugins]),...e.bundles?{bundles:Object.freeze([...e.bundles])}:{},...e.agentInstructions?{agentInstructions:Object.freeze([...e.agentInstructions])}:{},...e.evalDisable?{evalDisable:Object.freeze([...e.evalDisable])}:{}})}export{u as defineBrain,l as defineBundle,d as use};
3
3
 
4
4
  //# debugId=5C6B614D178C9B1664756E2164756E21
5
5
  //# sourceMappingURL=index.js.map
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import"./chunks/index-x8e40qwv.js";import{An as x,Bn as a,Cn as b,Dn as c,En as d,Zl as p,zn as t}from"./chunks/index-stpp3r8b.js";import{Rt as m,sr as f}from"./chunks/index-431k3883.js";import"./chunks/index-y95tc91a.js";import"./chunks/index-954p4889.js";import{ID as e}from"./chunks/index-7mq8b26b.js";import"./chunks/index-1hskk22v.js";import"./chunks/index-3w684dmw.js";export{f as SdkError,m as UserPermissionLevelSchema,p as defineAccountSettings,a as defineDaemon,b as defineInterface,c as defineMessageInterface,d as defineMessageInterfacePackage,x as defineRoute,t as protocol,e as z};
2
+ import"./chunks/index-x8e40qwv.js";import{An as x,Bn as a,Cn as b,Dn as c,En as d,Zl as p,zn as t}from"./chunks/index-cj5gzzsn.js";import{Rt as m,sr as f}from"./chunks/index-431k3883.js";import"./chunks/index-y95tc91a.js";import"./chunks/index-954p4889.js";import{ID as e}from"./chunks/index-7mq8b26b.js";import"./chunks/index-1hskk22v.js";import"./chunks/index-3w684dmw.js";export{f as SdkError,m as UserPermissionLevelSchema,p as defineAccountSettings,a as defineDaemon,b as defineInterface,c as defineMessageInterface,d as defineMessageInterfacePackage,x as defineRoute,t as protocol,e as z};
3
3
 
4
4
  //# debugId=AFB5D55409C441E364756E2164756E21
5
5
  //# sourceMappingURL=interfaces.js.map