@rizom/brain 0.2.0-alpha.562 → 0.2.0-alpha.563
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 +102 -102
- package/dist/chunks/{app-a7vxvxy9.js → app-m9vywjmb.js} +2 -2
- package/dist/chunks/{blog-post-adapter-cc701qpv.js → blog-post-adapter-k2s1gtyd.js} +2 -2
- package/dist/chunks/{index-wx77bxhg.js → index-1japmzr5.js} +3 -3
- package/dist/chunks/{index-wx77bxhg.js.map → index-1japmzr5.js.map} +1 -1
- package/dist/chunks/{index-h9xpqxzp.js → index-gz7t3d03.js} +9 -9
- package/dist/chunks/{index-h9xpqxzp.js.map → index-gz7t3d03.js.map} +8 -8
- package/dist/chunks/{index-pp913f7a.js → index-kx66vcbc.js} +2 -2
- package/dist/chunks/{index-yx9vsh2j.js → index-qsvhvhw2.js} +5 -5
- package/dist/chunks/{index-yx9vsh2j.js.map → index-qsvhvhw2.js.map} +3 -3
- package/dist/chunks/{index-mrvc27y1.js → index-vfz52jnm.js} +2 -2
- package/dist/chunks/{index-z7xwqb76.js → index-ycpbraxz.js} +2 -2
- package/dist/chunks/{linkedin-template-rt27nj4a.js → linkedin-template-tz7j2s0x.js} +2 -2
- package/dist/chunks/{rss-datasource-8v1t5gw4.js → rss-datasource-k9bvb8x4.js} +2 -2
- package/dist/entities.js +1 -1
- package/dist/index.js +1 -1
- package/dist/interfaces.js +1 -1
- package/dist/migrations/job-queue/meta/0000_snapshot.json +4 -13
- package/dist/model.d.ts +6 -0
- package/dist/model.js +42 -42
- package/dist/model.js.map +2 -2
- package/dist/plugins.js +1 -1
- package/dist/services.js +1 -1
- package/dist/ui/studio-chunks/main-1ct8r3ev.js.map +3 -3
- package/package.json +1 -1
- /package/dist/chunks/{app-a7vxvxy9.js.map → app-m9vywjmb.js.map} +0 -0
- /package/dist/chunks/{blog-post-adapter-cc701qpv.js.map → blog-post-adapter-k2s1gtyd.js.map} +0 -0
- /package/dist/chunks/{index-pp913f7a.js.map → index-kx66vcbc.js.map} +0 -0
- /package/dist/chunks/{index-mrvc27y1.js.map → index-vfz52jnm.js.map} +0 -0
- /package/dist/chunks/{index-z7xwqb76.js.map → index-ycpbraxz.js.map} +0 -0
- /package/dist/chunks/{linkedin-template-rt27nj4a.js.map → linkedin-template-tz7j2s0x.js.map} +0 -0
- /package/dist/chunks/{rss-datasource-8v1t5gw4.js.map → rss-datasource-k9bvb8x4.js.map} +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{na as dr}from"./index-13wwvf9d.js";import{$a as us,$l as Ho,$p as pi,Aj as Ge,An as Li,Bj as Or,Cj as Mr,Dj as Lr,Ea as Jr,Ff as E,Fj as Ce,Gj as On,Hj as Io,Hm as bs,Im as Ss,Ja as At,Jj as D,Jm as Rs,Jo as Tn,Ka as Le,Kj as rt,Ko as kn,La as Zr,Lj as $t,Lo as Te,Ma as $r,Mj as io,Nj as co,Nn as Ui,Oa as Br,Om as Ye,Pa as os,Pm as qn,Pn as Zi,Ql as Ae,Qm as xr,Qn as B,Rn as vn,Sa as _r,Sj as it,Ta as Gr,Tl as hs,Ul as ys,Um as is,Un as mt,Va as Q,Vl as qe,Vn as $i,Vo as Fi,Wa as K,Wk as ct,Wl as fi,Wp as en,Xa as ss,Xl as hi,Xn as ts,Xo as qi,Xp as di,Ya as as,Yl as yi,Yn as Bi,Za as cs,Zf as k,Zl as vi,Zn as _i,_a as ls,_k as bo,_n as Wi,_p as tn,ab as ds,al as Vi,am as Go,ap as Ji,aq as Qi,bb as ps,bm as Qo,bp as Hi,bq as mi,cb as ms,cl as Xi,cn as Rr,cp as Gi,db as gs,dl as Yn,dm as Oo,dn as Ee,en as yn,ep as ai,fd as T,fl as wo,fn as Xo,fp as ei,gk as hn,gl as ji,gn as kr,gp as ci,hn as Ir,hp as bn,ij as y,il as ie,in as Oi,ip as li,iq as Ki,jk as Vo,jl as Yt,jp as ui,kg as _,kk as dn,kn as un,kq as Rn,lk as Ur,ln as Zt,lq as Qe,ok as Ar,pn,qa as Dt,qo as jn,ra as Fr,rf as q,sa as A,tf as Ei,ua as ee,wa as qr,xk as xi,xl as L,xn as es,yj as N,zn as Mi}from"./index-h9xpqxzp.js";import{Bq as W,oq as qo,tq as Ni,xq as G}from"./index-70fmhq0q.js";import{Fq as x,Gq as z}from"./index-4fa7rc6d.js";import{$r as si,Ct as Ai,Dr as V,Gs as J,Ht as Fn,It as Di,Jt as zi,Kq as s,Ms as Nt,Nq as mo,Ns as ln,Oq as go,Os as Fo,Pq as Qt,Rq as nr,Tq as be,Wr as ii,Yr as ni,Zr as oi,at as xn,dt as Yo,et as Ut,hs as Cr,js as Tr,jt as Ii,rs as F,us as ne,ws as C,xs as fe}from"./index-32at95wx.js";import{Tt as Cl}from"./index-4z4r1ga1.js";function Rt(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 pe(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 a=Rt(e,t).reduce((c,l)=>c+l.count,0);if(a>0)o.push(`${a} 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 hr(e){let{config:t,services:r,bootTime:i,endpoints:n,interactions:o}=e,[a,c,l,u]=await Promise.all([r.entityService.getEntityCounts(Ce("runtime app info reports operator-facing aggregate status")),r.entityService.countEmbeddings(),r.daemonRegistry.getStatuses(),r.jobQueueService.getDiagnostics()]),d=a.reduce((p,g)=>p+g.count,0);return{model:t.name||"brain-app",version:t.version||"1.0.0",uptime:Math.floor((Date.now()-i)/1000),entities:d,entityCounts:a,embeddings:c,backgroundWork:pe(u,r.jobQueueService.getExecutionRegistrations()),ai:{model:t.ai.model,embeddingModel:"text-embedding-3-small"},daemons:l,endpoints:n(),interactions:o()}}import{readdir as yr,readFile as Js}from"fs/promises";var Hs=10;async function Gs(e="/proc"){let t=null;try{t=(await yr(`${e}/self/fd`)).length}catch{}try{let i=(await yr(e,{withFileTypes:!0})).filter((a)=>a.isDirectory()&&/^\d+$/.test(a.name)).map((a)=>a.name),n=0,o=0;return await Promise.all(i.map(async(a)=>{try{let c=await Js(`${e}/${a}/status`,"utf8");if(o++,/^State:\s+Z\b/m.test(c))n++}catch{}})),{fileDescriptors:t,processCount:o,zombieCount:n}}catch{return{fileDescriptors:t,processCount:null,zombieCount:null}}}function vr(e,t,r){return t.status==="fulfilled"?{name:e,status:"healthy",message:r}:{name:e,status:"unhealthy",message:C(t.reason)}}function Qs(e){if(!e)return{name:"job-worker",status:"degraded",message:"Worker session state is unavailable"};let t=e.workerSessions,r=pe(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 Ks(e){if(!e)return{name:"job-queue-progress",status:"degraded",message:"Queue progress state is unavailable"};let t=pe(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 Ys(e,t){if(!e||!t)return{name:"job-execution-inventory",status:"degraded",message:"Job execution inventory is unavailable"};let r=Rt(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 Vs(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 Xs(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 ea(e){let t=e.entityService.getProjectionStore(),[r,i,n]=await Promise.all([t.getActiveWave(),t.getUnresolvedProjectionIncidentDiagnostics(Hs),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 a=(await t.listWaveRules(r.id)).filter((l)=>l.status==="queued"||l.status==="failed"),c=(await Promise.all(a.map(async(l)=>{let u=l.jobId?await e.jobQueueService.getStatus(l.jobId):null;if(l.status!=="failed"&&u&&(u.status==="pending"||u.status==="processing"))return null;return{ruleId:l.ruleId,jobId:l.jobId,jobStatus:u?.status??"missing"}}))).filter((l)=>l!==null);return{waveId:r.id,batches:n,strandedRules:c,incidentCount:i.total,incidents:i.incidents}}function ta(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 ra(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 br(e){let t=e.now?.()??Date.now(),r=(e.memoryUsage??process.memoryUsage)(),[i,n,o,a,c,l,u,d]=await Promise.allSettled([e.entityService.getEntityCounts(Ce("runtime readiness database probe")),e.jobQueueService.getDiagnostics(t),Promise.resolve(e.jobQueueService.getExecutionRegistrations()),e.daemonRegistry.getStatuses(),(e.readProcessSignals??Gs)(),e.projectionRuntimeSupervisor.getDiagnostics(),ea(e),e.operationalHealthRegistry.getChecks()]),p=n.status==="fulfilled"?n.value:null,g=o.status==="fulfilled"?o.value??null:null,f=a.status==="fulfilled"?a.value:[],m=c.status==="fulfilled"?c.value:{fileDescriptors:null,processCount:null,zombieCount:null},h=l.status==="fulfilled"?l.value:{status:"unhealthy",initialized:!1,trackedRoots:0,openCircuits:[]},w=[vr("entity-database",i,"Entity database is accessible"),vr("job-queue-database",n,"Job queue database is accessible"),Qs(p),Ks(p),Ys(p,g),Vs(p),l.status==="fulfilled"?Xs(h):{name:"projection-circuits",status:"degraded",message:C(l.reason)},u.status==="fulfilled"?ta(u.value):{name:"projection-waves",status:"degraded",message:C(u.reason)},a.status==="fulfilled"?ra(f):{name:"daemons",status:"degraded",message:C(a.reason)}],v=d.status==="fulfilled"?d.value:[{name:"plugin-operational-health",status:"degraded",message:"Plugin operational health is unavailable"}],S=[...w,...v];return{status:w.some((b)=>b.status==="unhealthy")?"not_ready":"ready",operationalStatus:S.some((b)=>b.status!=="healthy")?"degraded":"operational",checkedAt:new Date(t).toISOString(),checks:S,resources:{memory:{rssBytes:r.rss,heapUsedBytes:r.heapUsed,heapTotalBytes:r.heapTotal},fileDescriptors:m.fileDescriptors,processes:{total:m.processCount,zombies:m.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 Sr(){return{dataDir:"./data",cacheDir:"./cache",distDir:"./dist"}}function Y(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 It=Sr(),ia=s.looseObject({label:s.string().min(1),pluralName:s.string().optional(),layout:s.string().optional(),paginate:s.boolean().optional(),pageSize:s.number().optional(),navigation:s.object({show:s.boolean().optional(),slot:s.enum(["primary","secondary"]).optional(),priority:s.number().optional()}).optional()});function wt(){return Y(It)}var oe=s.enum(["debug","info","warn","error"]),se=s.enum(["none","low","medium","high","xhigh","max"]),Pt=s.object({name:s.string().default("brain-app"),version:s.string().default("1.0.0"),database:ne,jobQueueDatabase:ne,jobQueue:s.object({workerConcurrency:s.number().int().min(1).max(32).default(4)}).prefault({}),conversationDatabase:ne,runtimeStateDatabase:ne,embeddingDatabase:ne,ai:s.object({apiKey:s.string().default(""),imageApiKey:s.string().optional(),model:s.string(),temperature:s.number().min(0).max(2).default(0.7),maxTokens:s.number().positive().default(1000),webSearch:s.boolean().default(!0),reasoningEffort:se.optional()}),embedding:s.object({enabled:s.boolean().default(!0)}),logging:s.object({level:oe.default("info"),format:s.enum(["text","json"]).default("text"),file:s.string().optional(),context:s.string().default("shell")}).prefault({level:"info",context:"shell"}),features:s.object({}).default({}),plugins:s.array(Te).default([]),dataDir:s.string().default("./brain-data"),gitBrokerSocket:s.string().min(1).optional(),gitBrokerCheckout:s.string().min(1).optional(),spaces:s.array(s.string()).default([]),siteBaseUrl:s.string().optional(),localSiteUrl:s.string().optional(),preferLocalUrls:s.boolean().default(!1),themeCSS:s.string().default(""),entityDisplay:s.record(s.string(),ia).optional(),profileKind:s.string().trim().min(1).optional()});function ke(e={}){let{plugins:t=[],permissions:r={},identity:i,profile:n,agentInstructions:o,evalHandlerRegistry:a,ai:c,logging:l,embedding:u,jobQueue:d,...p}=e,{entityDisplay:g,...f}=Pt.parse({...wt(),...V(p),ai:V({...c}),logging:V({...l}),embedding:V({...u}),jobQueue:V({...d}),plugins:[]});return{...f,plugins:t,permissions:r,...V({entityDisplay:g,identity:i,profile:n,agentInstructions:o,evalHandlerRegistry:a})}}var j={NOTE:"note",BRAIN_CHARACTER:"brain-character",ANCHOR_PROFILE:"anchor-profile"},me={KNOWLEDGE_QUERY:"shell:knowledge-query",BASE_ENTITY_DISPLAY:"shell:base-entity-display",CONTENT_GENERATION:"shell:content-generation"},Ct={ENTITIES:"shell:entities"};var na=Ir.extend({templateName:s.string()}),oa=s.object({slug:s.string()}),sa="The style guide governs voice, tone, wording and form: paragraphing, sentence rhythm, hooks, rhetorical questions and calls to action. The instructions below govern the task, required content, length limits, platform constraints and output format. When they conflict on voice or form, follow the style guide.",aa="Generate the content described in your instructions.";function ca(e){return e instanceof s.ZodType}function la(e){if(!e)return;return e.replace(/^https?:\/\//,"").replace(/\/$/,"")}class xe{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,a){this.aiService=e,this.entityService=t,this.templateRegistry=r,this.getIdentityContent=i,this.getProfileContent=n,this.entityUrls=o,this.siteBaseUrl=la(a)}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=na.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 a=i?await Rr((w,v)=>i.getEntity(w,v),n.templateName,o.basePrompt):await Ee(this.entityService,n.templateName,o.basePrompt);r?.throwIfAborted();let c=[a,n.prompt].filter(Boolean).join(" "),l=c.length>0&&o.useKnowledgeContext===!0,u=this.entityService.getWeightMap(),d=Object.keys(u).length>0,p=l?i?await i.search(c,{limit:5,...d&&{weight:u}}):await this.entityService.search({query:c,options:{limit:5,...d&&{weight:u},...r&&{signal:r}}}):[];r?.throwIfAborted();let g=this.buildPrompt(n,p),f=i?await this.readIdentities(i,n.representedIdentity):void 0,m=this.buildSystemPrompt(a,n,f);if(!ca(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(m,g,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(j.BRAIN_CHARACTER):"",t===void 0||t==="anchor"?r(j.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",sa,"");return i.push("# Instructions",e),i.join(`
|
|
2
|
+
import{na as dr}from"./index-13wwvf9d.js";import{$a as us,$l as Ho,$p as pi,Aj as Ge,An as Li,Bj as Or,Cj as Mr,Dj as Lr,Ea as Jr,Ff as E,Fj as Ce,Gj as On,Hj as Io,Hm as bs,Im as Ss,Ja as At,Jj as D,Jm as Rs,Jo as Tn,Ka as Le,Kj as rt,Ko as kn,La as Zr,Lj as $t,Lo as Te,Ma as $r,Mj as io,Nj as co,Nn as Ui,Oa as Br,Om as Ye,Pa as os,Pm as qn,Pn as Zi,Ql as Ae,Qm as xr,Qn as B,Rn as vn,Sa as _r,Sj as it,Ta as Gr,Tl as hs,Ul as ys,Um as is,Un as mt,Va as Q,Vl as qe,Vn as $i,Vo as Fi,Wa as K,Wk as ct,Wl as fi,Wp as en,Xa as ss,Xl as hi,Xn as ts,Xo as qi,Xp as di,Ya as as,Yl as yi,Yn as Bi,Za as cs,Zf as k,Zl as vi,Zn as _i,_a as ls,_k as bo,_n as Wi,_p as tn,ab as ds,al as Vi,am as Go,ap as Ji,aq as Qi,bb as ps,bm as Qo,bp as Hi,bq as mi,cb as ms,cl as Xi,cn as Rr,cp as Gi,db as gs,dl as Yn,dm as Oo,dn as Ee,en as yn,ep as ai,fd as T,fl as wo,fn as Xo,fp as ei,gk as hn,gl as ji,gn as kr,gp as ci,hn as Ir,hp as bn,ij as y,il as ie,in as Oi,ip as li,iq as Ki,jk as Vo,jl as Yt,jp as ui,kg as _,kk as dn,kn as un,kq as Rn,lk as Ur,ln as Zt,lq as Qe,ok as Ar,pn,qa as Dt,qo as jn,ra as Fr,rf as q,sa as A,tf as Ei,ua as ee,wa as qr,xk as xi,xl as L,xn as es,yj as N,zn as Mi}from"./index-gz7t3d03.js";import{Bq as W,oq as qo,tq as Ni,xq as G}from"./index-70fmhq0q.js";import{Fq as x,Gq as z}from"./index-4fa7rc6d.js";import{$r as si,Ct as Ai,Dr as V,Gs as J,Ht as Fn,It as Di,Jt as zi,Kq as s,Ms as Nt,Nq as mo,Ns as ln,Oq as go,Os as Fo,Pq as Qt,Rq as nr,Tq as be,Wr as ii,Yr as ni,Zr as oi,at as xn,dt as Yo,et as Ut,hs as Cr,js as Tr,jt as Ii,rs as F,us as ne,ws as C,xs as fe}from"./index-32at95wx.js";import{Tt as Cl}from"./index-4z4r1ga1.js";function Rt(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 pe(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 a=Rt(e,t).reduce((c,l)=>c+l.count,0);if(a>0)o.push(`${a} 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 hr(e){let{config:t,services:r,bootTime:i,endpoints:n,interactions:o}=e,[a,c,l,u]=await Promise.all([r.entityService.getEntityCounts(Ce("runtime app info reports operator-facing aggregate status")),r.entityService.countEmbeddings(),r.daemonRegistry.getStatuses(),r.jobQueueService.getDiagnostics()]),d=a.reduce((p,g)=>p+g.count,0);return{model:t.name||"brain-app",version:t.version||"1.0.0",uptime:Math.floor((Date.now()-i)/1000),entities:d,entityCounts:a,embeddings:c,backgroundWork:pe(u,r.jobQueueService.getExecutionRegistrations()),ai:{model:t.ai.model,embeddingModel:"text-embedding-3-small"},daemons:l,endpoints:n(),interactions:o()}}import{readdir as yr,readFile as Js}from"fs/promises";var Hs=10;async function Gs(e="/proc"){let t=null;try{t=(await yr(`${e}/self/fd`)).length}catch{}try{let i=(await yr(e,{withFileTypes:!0})).filter((a)=>a.isDirectory()&&/^\d+$/.test(a.name)).map((a)=>a.name),n=0,o=0;return await Promise.all(i.map(async(a)=>{try{let c=await Js(`${e}/${a}/status`,"utf8");if(o++,/^State:\s+Z\b/m.test(c))n++}catch{}})),{fileDescriptors:t,processCount:o,zombieCount:n}}catch{return{fileDescriptors:t,processCount:null,zombieCount:null}}}function vr(e,t,r){return t.status==="fulfilled"?{name:e,status:"healthy",message:r}:{name:e,status:"unhealthy",message:C(t.reason)}}function Qs(e){if(!e)return{name:"job-worker",status:"degraded",message:"Worker session state is unavailable"};let t=e.workerSessions,r=pe(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 Ks(e){if(!e)return{name:"job-queue-progress",status:"degraded",message:"Queue progress state is unavailable"};let t=pe(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 Ys(e,t){if(!e||!t)return{name:"job-execution-inventory",status:"degraded",message:"Job execution inventory is unavailable"};let r=Rt(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 Vs(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 Xs(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 ea(e){let t=e.entityService.getProjectionStore(),[r,i,n]=await Promise.all([t.getActiveWave(),t.getUnresolvedProjectionIncidentDiagnostics(Hs),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 a=(await t.listWaveRules(r.id)).filter((l)=>l.status==="queued"||l.status==="failed"),c=(await Promise.all(a.map(async(l)=>{let u=l.jobId?await e.jobQueueService.getStatus(l.jobId):null;if(l.status!=="failed"&&u&&(u.status==="pending"||u.status==="processing"))return null;return{ruleId:l.ruleId,jobId:l.jobId,jobStatus:u?.status??"missing"}}))).filter((l)=>l!==null);return{waveId:r.id,batches:n,strandedRules:c,incidentCount:i.total,incidents:i.incidents}}function ta(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 ra(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 br(e){let t=e.now?.()??Date.now(),r=(e.memoryUsage??process.memoryUsage)(),[i,n,o,a,c,l,u,d]=await Promise.allSettled([e.entityService.getEntityCounts(Ce("runtime readiness database probe")),e.jobQueueService.getDiagnostics(t),Promise.resolve(e.jobQueueService.getExecutionRegistrations()),e.daemonRegistry.getStatuses(),(e.readProcessSignals??Gs)(),e.projectionRuntimeSupervisor.getDiagnostics(),ea(e),e.operationalHealthRegistry.getChecks()]),p=n.status==="fulfilled"?n.value:null,g=o.status==="fulfilled"?o.value??null:null,f=a.status==="fulfilled"?a.value:[],m=c.status==="fulfilled"?c.value:{fileDescriptors:null,processCount:null,zombieCount:null},h=l.status==="fulfilled"?l.value:{status:"unhealthy",initialized:!1,trackedRoots:0,openCircuits:[]},w=[vr("entity-database",i,"Entity database is accessible"),vr("job-queue-database",n,"Job queue database is accessible"),Qs(p),Ks(p),Ys(p,g),Vs(p),l.status==="fulfilled"?Xs(h):{name:"projection-circuits",status:"degraded",message:C(l.reason)},u.status==="fulfilled"?ta(u.value):{name:"projection-waves",status:"degraded",message:C(u.reason)},a.status==="fulfilled"?ra(f):{name:"daemons",status:"degraded",message:C(a.reason)}],v=d.status==="fulfilled"?d.value:[{name:"plugin-operational-health",status:"degraded",message:"Plugin operational health is unavailable"}],S=[...w,...v];return{status:w.some((b)=>b.status==="unhealthy")?"not_ready":"ready",operationalStatus:S.some((b)=>b.status!=="healthy")?"degraded":"operational",checkedAt:new Date(t).toISOString(),checks:S,resources:{memory:{rssBytes:r.rss,heapUsedBytes:r.heapUsed,heapTotalBytes:r.heapTotal},fileDescriptors:m.fileDescriptors,processes:{total:m.processCount,zombies:m.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 Sr(){return{dataDir:"./data",cacheDir:"./cache",distDir:"./dist"}}function Y(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 It=Sr(),ia=s.looseObject({label:s.string().min(1),pluralName:s.string().optional(),layout:s.string().optional(),paginate:s.boolean().optional(),pageSize:s.number().optional(),navigation:s.object({show:s.boolean().optional(),slot:s.enum(["primary","secondary"]).optional(),priority:s.number().optional()}).optional()});function wt(){return Y(It)}var oe=s.enum(["debug","info","warn","error"]),se=s.enum(["none","low","medium","high","xhigh","max"]),Pt=s.object({name:s.string().default("brain-app"),version:s.string().default("1.0.0"),database:ne,jobQueueDatabase:ne,jobQueue:s.object({workerConcurrency:s.number().int().min(1).max(32).default(4)}).prefault({}),conversationDatabase:ne,runtimeStateDatabase:ne,embeddingDatabase:ne,ai:s.object({apiKey:s.string().default(""),imageApiKey:s.string().optional(),model:s.string(),temperature:s.number().min(0).max(2).default(0.7),maxTokens:s.number().positive().default(1000),webSearch:s.boolean().default(!0),reasoningEffort:se.optional()}),embedding:s.object({enabled:s.boolean().default(!0)}),logging:s.object({level:oe.default("info"),format:s.enum(["text","json"]).default("text"),file:s.string().optional(),context:s.string().default("shell")}).prefault({level:"info",context:"shell"}),features:s.object({}).default({}),plugins:s.array(Te).default([]),dataDir:s.string().default("./brain-data"),gitBrokerSocket:s.string().min(1).optional(),gitBrokerCheckout:s.string().min(1).optional(),spaces:s.array(s.string()).default([]),siteBaseUrl:s.string().optional(),localSiteUrl:s.string().optional(),preferLocalUrls:s.boolean().default(!1),themeCSS:s.string().default(""),entityDisplay:s.record(s.string(),ia).optional(),profileKind:s.string().trim().min(1).optional()});function ke(e={}){let{plugins:t=[],permissions:r={},identity:i,profile:n,agentInstructions:o,evalHandlerRegistry:a,ai:c,logging:l,embedding:u,jobQueue:d,...p}=e,{entityDisplay:g,...f}=Pt.parse({...wt(),...V(p),ai:V({...c}),logging:V({...l}),embedding:V({...u}),jobQueue:V({...d}),plugins:[]});return{...f,plugins:t,permissions:r,...V({entityDisplay:g,identity:i,profile:n,agentInstructions:o,evalHandlerRegistry:a})}}var j={NOTE:"note",BRAIN_CHARACTER:"brain-character",ANCHOR_PROFILE:"anchor-profile"},me={KNOWLEDGE_QUERY:"shell:knowledge-query",BASE_ENTITY_DISPLAY:"shell:base-entity-display",CONTENT_GENERATION:"shell:content-generation"},Ct={ENTITIES:"shell:entities"};var na=Ir.extend({templateName:s.string()}),oa=s.object({slug:s.string()}),sa="The style guide governs voice, tone, wording and form: paragraphing, sentence rhythm, hooks, rhetorical questions and calls to action. The instructions below govern the task, required content, length limits, platform constraints and output format. When they conflict on voice or form, follow the style guide.",aa="Generate the content described in your instructions.";function ca(e){return e instanceof s.ZodType}function la(e){if(!e)return;return e.replace(/^https?:\/\//,"").replace(/\/$/,"")}class xe{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,a){this.aiService=e,this.entityService=t,this.templateRegistry=r,this.getIdentityContent=i,this.getProfileContent=n,this.entityUrls=o,this.siteBaseUrl=la(a)}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=na.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 a=i?await Rr((w,v)=>i.getEntity(w,v),n.templateName,o.basePrompt):await Ee(this.entityService,n.templateName,o.basePrompt);r?.throwIfAborted();let c=[a,n.prompt].filter(Boolean).join(" "),l=c.length>0&&o.useKnowledgeContext===!0,u=this.entityService.getWeightMap(),d=Object.keys(u).length>0,p=l?i?await i.search(c,{limit:5,...d&&{weight:u}}):await this.entityService.search({query:c,options:{limit:5,...d&&{weight:u},...r&&{signal:r}}}):[];r?.throwIfAborted();let g=this.buildPrompt(n,p),f=i?await this.readIdentities(i,n.representedIdentity):void 0,m=this.buildSystemPrompt(a,n,f);if(!ca(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(m,g,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(j.BRAIN_CHARACTER):"",t===void 0||t==="anchor"?r(j.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",sa,"");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(`
|
|
@@ -10,15 +10,15 @@ ${JSON.stringify(e.data,null,2)}`);if(e.prompt)r.push(`Additional instructions:
|
|
|
10
10
|
`):aa}formatRelevantEntity(e,t){let{entity:r,excerpt:i}=e,n=r.entityType,o=oa.safeParse(r.metadata),a=o.success?o.data.slug:r.id;if(this.siteBaseUrl&&t.hasRoute(n)){let c=t.generateUrl(n,a),l=`https://${this.siteBaseUrl}${c}`;return`[${n}] ${r.id}: ${i} (${l})`}return`[${n}] ${r.id}: ${i}`}}var ua=s.object({entityType:s.string(),query:s.object({id:s.string()})});class je{entityService;id=Ct.ENTITIES;name="Entity DataSource";description="Fetches entity content from the entity service";constructor(e){this.entityService=e}async fetch(e,t,r){let i=ua.safeParse(e);if(!i.success){let c=i.error.issues.map((l)=>`${l.path.join(".")}: ${l.message}`).join(", ");throw Error(`EntityDataSource: Invalid query - ${c}`)}let n=i.data,a=await(r?.entityService??this.entityService).getEntity({entityType:n.entityType,id:n.query.id});if(!a)throw Error(`EntityDataSource: Entity not found (${n.entityType}:${n.query.id})`);return t.parse({markdown:a.content})}}function wr(e,t){e.dataSourceRegistry.register(new xe(e.aiService,e.entityService,e.templateRegistry,()=>e.identityService.getCharacterContent(),()=>e.profileService.getProfileContent(),new Ae(t.entityDisplay),t.siteBaseUrl)),e.dataSourceRegistry.register(new je(e.entityService)),e.logger.debug("Core DataSources registered")}async function Pr(e,t,r){r?.throwIfAborted();let i=e.contentService.getTemplate(t.templateName);if(!i)throw Error(`Template not found: ${t.templateName}`);let n=t.interfacePermissionGrant??"public";if(!e.permissionService.hasPermission(n,i.requiredPermission))throw Error(`Insufficient permissions: ${i.requiredPermission} required, but interface granted ${n} for template: ${t.templateName}`);let o={prompt:t.prompt,...t.conversationHistory&&{conversationHistory:t.conversationHistory},...t.data&&{data:t.data},...t.representedIdentity&&{representedIdentity:t.representedIdentity},...t.styleGuide&&{styleGuide:t.styleGuide}};return e.contentService.generateContent(t.templateName,o,{signal:r})}async function De(e,t,r){let i=await e.send({type:Cr,sender:t,payload:{actor:r}});if("noop"in i)return null;if(!i.success)throw Error("Principal resolution unavailable");return Tr.parse(i.data).principal}function Er(e,t){return new kr(e,(r)=>De(t,"shell:content-service",r))}var Tt=T.Service("@brains/conversation-service/ConversationService");function da(e){if(e.service){let r=e.service;return{service:r,close:()=>r.close()}}let t=xr.createFreshFromConfig(e.logger,e.messageBus,e.dbConfig,e.config);try{return{service:t,close:()=>t.close()}}catch(r){throw t.close(),r}}function jr(e){return N(Tt,()=>da(e))}var kt=T.Service("@brains/entity-service/EntityService");function pa(e){return"close"in e&&typeof e.close==="function"}function Dr(e){return N(kt,()=>{let t=e.service??Ar.createFresh(e);return{service:t,close:()=>{if(pa(t))t.close()}}})}var ge=s.strictObject({dedupeKey:s.string().min(1).max(512),title:s.string().min(1),body:s.string().min(1),html:s.string().min(1).optional(),sensitivity:s.enum(["normal","secret"]).optional(),includeInInbox:s.boolean().optional()}),Et=s.strictObject({alerts:s.array(ge).optional()});var ze="shell:recurring-check",jt=86400000,ma=7*jt,ga=3*jt,fa=s.strictObject({checkId:s.string().min(1)}),ha=s.discriminatedUnion("kind",[s.strictObject({kind:s.literal("last-success"),checkId:s.string(),at:s.string().datetime()}),s.strictObject({kind:s.literal("alert"),checkId:s.string(),dedupeKey:s.string(),status:s.enum(["pending","suppressed","delivered","resolved"]),alert:ge,observedAt:s.string().datetime(),includeInInbox:s.boolean().optional(),deliveredAt:s.string().datetime().optional(),resolvedAt:s.string().datetime().optional()})]);class Me{brainId;scheduler;state;jobQueue;delivery;logger;clock;nowFallback;checks=new Map;pluginChecks=new Map;alertOperations=new Ur;handlerRegistered=!1;started=!1;stopPromise=null;constructor(e){this.brainId=e.brainId,this.scheduler=e.scheduler,this.jobQueue=e.jobQueue,this.delivery=e.delivery,this.logger=e.logger.child("RecurringCheckService"),this.clock=e.clock,this.nowFallback=e.now??(()=>new Date),this.state=e.runtimeState.scoped({namespace:"shell.recurring-checks",schema:ha});let t={validateAndParse:(r)=>{let i=fa.safeParse(r);return i.success?i.data:null},process:async(r)=>{await this.runNow(r.checkId)}};this.jobQueue.registerHandler(ze,t,"shell"),this.handlerRegistered=!0}abandon(){if(this.started)throw Error("Cannot abandon a running recurring check service");if(!this.handlerRegistered)return;this.jobQueue.unregisterHandler(ze),this.handlerRegistered=!1}namespace(e){return{register:(t)=>this.register(e,t)}}register(e,t){zr(e,"plugin ID"),zr(t.id,"check ID");let r=`${e}:${t.id}`;if(this.checks.has(r))throw Error(`Recurring check already registered: ${r}`);let i={pluginId:e,definition:{...t,id:r},catchUpTasks:new Set};this.checks.set(r,i);let n=this.pluginChecks.get(e)??new Set;if(n.add(i),this.pluginChecks.set(e,n),this.started)this.schedule(i),this.trackCatchUp(i).catch((o)=>{this.logger.error(`Failed to enqueue recurring check ${r}`,o)});return()=>{this.releaseRegisteredCheck(i,Error(`Recurring check unregistered: ${r}`)).catch((o)=>{this.logger.error(`Failed to unregister recurring check ${r}`,o)})}}async unregisterPlugin(e){let t=[...this.pluginChecks.get(e)??[]];await this.drainCleanupTasks(t.map((r)=>this.releaseRegisteredCheck(r,Error(`Recurring check plugin unregistered: ${e}`))))}async start(){if(this.started)return;if(this.stopPromise)await this.stopPromise,this.stopPromise=null;this.started=!0;for(let e of this.checks.values())this.schedule(e);await Promise.all([...this.checks.values()].map((e)=>this.trackCatchUp(e)))}stop(){return this.stopPromise??=this.stopChecks(),this.stopPromise}async stopChecks(){this.started=!1;let e=Error("Recurring check service stopped"),t=[...this.pluginChecks.values()].flatMap((r)=>[...r]);await this.drainCleanupTasks(t.map((r)=>r.releasePromise??this.settleRegisteredCheck(r,e)))}async runNow(e,t){t?.throwIfAborted();let r=this.checks.get(e);if(!r)throw Error(`Unknown recurring check: ${e}`);if(r.activeCheck)return this.logger.debug(`Skipping overlapping recurring check: ${e}`),!1;let i=new AbortController,n=t?AbortSignal.any([i.signal,t]):i.signal,o={controller:i,settled:Promise.resolve()};r.activeCheck=o;let a=Promise.resolve().then(()=>this.executeRegisteredCheck(r,n)),c=()=>{if(r.activeCheck===o)delete r.activeCheck};return o.settled=a.then(c,c),a}async executeRegisteredCheck(e,t){let r=e.definition.id,i,n=async(c)=>{let l=AbortSignal.any([t,c]),u=e.definition.deliverAlerts!==!1;if(u)await this.flushPendingAlerts(r);else await this.suppressPendingAlerts(r);l.throwIfAborted();let d=await e.definition.run({signal:l});l.throwIfAborted();let p=Et.parse(d);for(let g of p.alerts??[])l.throwIfAborted(),await this.recordAlert(r,g,{deliver:u,includeInInbox:g.includeInInbox??e.definition.includeInInbox!==!1});l.throwIfAborted(),await this.state.set(this.lastSuccessKey(r),{kind:"last-success",checkId:r,at:this.currentTime().toISOString()})},o=y.tryPromise({try:(c)=>(i=n(c),i),catch:(c)=>c}),a=await y.runPromiseExit(o,{signal:t});if(i)await Promise.allSettled([i]);if(E.isSuccess(a))return!0;if(t.aborted)throw t.reason;throw q.squash(a.cause)}getRegisteredCheckIds(){return[...this.checks.keys()]}trackCatchUp(e){let t=this.enqueueCatchUpIfNeeded(e);e.catchUpTasks.add(t);let r=()=>{e.catchUpTasks.delete(t)};return t.then(r,r),t}releaseRegisteredCheck(e,t){if(e.releasePromise)return e.releasePromise;let r=e.definition.id;if(this.checks.get(r)===e)this.checks.delete(r);let i=this.releaseRegisteredCheckOnce(e,t);return e.releasePromise=i,i}async releaseRegisteredCheckOnce(e,t){try{await this.settleRegisteredCheck(e,t)}finally{let r=this.pluginChecks.get(e.pluginId);if(r?.delete(e),r?.size===0)this.pluginChecks.delete(e.pluginId)}}async settleRegisteredCheck(e,t){let r=[];if(e.scheduledJob){let i=e.scheduledJob;delete e.scheduledJob;try{r.push(i.stop())}catch(n){r.push(Promise.reject(n))}}if(e.activeCheck)e.activeCheck.controller.abort(t),r.push(e.activeCheck.settled);r.push(...e.catchUpTasks),r.push(this.cancelEnqueueRetry(e)),await this.drainCleanupTasks(r)}async drainCleanupTasks(e){let t=await Promise.allSettled(e),r=[];for(let i of t)if(i.status==="rejected")r.push(i.reason);if(r.length===1)throw r[0];if(r.length>1)throw AggregateError(r,"Recurring check cleanup failed")}schedule(e){let t=e.definition,r=Oe(this.brainId,t.id,t.cadence);e.scheduledJob=this.scheduler.scheduleCron(r.expression,async()=>{await this.cancelEnqueueRetry(e);try{await this.enqueue(t.id)}catch(i){this.retryRefusedEnqueue(e,i)}},{timezone:"UTC"})}retryRefusedEnqueue(e,t){let r=e.definition;if(!this.started||this.checks.get(r.id)!==e){this.logger.error(`Failed to enqueue recurring check ${r.id}`,t);return}let i=Oe(this.brainId,r.id,r.cadence),n=xt(this.currentTime(),i).getTime()+i.periodMs,o=new AbortController,a={controller:o,settled:Promise.resolve()};e.enqueueRetry=a,a.settled=Or(()=>this.enqueue(r.id),t,{firstDelayMs:Mr,maxDelayMs:Lr,giveUpAt:n,signal:o.signal,clock:this.clock,onRetry:(c,l)=>{this.logger.warn(`Failed to enqueue recurring check ${r.id}; retrying in ${l}ms`,c)}}).then((c)=>{if(c.kind!=="abandoned")return;this.logger.error(`Failed to enqueue recurring check ${r.id}; the next scheduled run supersedes it`,c.error)},(c)=>{this.logger.error(`Retrying recurring check ${r.id} failed`,c)}).finally(()=>{if(e.enqueueRetry===a)delete e.enqueueRetry})}async cancelEnqueueRetry(e){let t=e.enqueueRetry;if(delete e.enqueueRetry,!t)return;t.controller.abort(),await t.settled}async enqueueCatchUpIfNeeded(e){let t=e.definition,r=this.currentTime(),i=Oe(this.brainId,t.id,t.cadence),n=xt(r,i),o=await this.state.get(this.lastSuccessKey(t.id));if(o?.kind==="last-success"&&new Date(o.at)>=n)return;try{await this.enqueue(t.id)}catch(a){this.retryRefusedEnqueue(e,a)}}enqueue(e){let t={source:"shell",metadata:{operationType:"data_processing",operationTarget:e,silent:!0},maxRetries:3,deduplication:"skip",deduplicationKey:e};return this.jobQueue.enqueue({type:ze,data:{checkId:e},options:t})}async listOpenAlerts(){return(await this.state.list({keyPrefix:"alert:"})).flatMap((t)=>{let r=t.value;if(r.kind!=="alert"||r.status==="resolved")return[];if(!(r.includeInInbox??this.checks.get(r.checkId)?.definition.includeInInbox!==!1))return[];return[{id:t.key,checkId:r.checkId,title:r.alert.title,body:r.alert.body,observedAt:r.observedAt}]}).sort((t,r)=>t.observedAt.localeCompare(r.observedAt)||t.id.localeCompare(r.id))}async resolveOpenAlert(e){await this.alertOperations.run(e,async()=>{let t=await this.state.get(e),r=t?.kind==="alert"&&(t.includeInInbox??this.checks.get(t.checkId)?.definition.includeInInbox!==!1);if(t?.kind!=="alert"||t.status==="resolved"||!r)throw Error("Recurring-check inbox item is not open");await this.state.set(e,{...t,status:"resolved",resolvedAt:this.currentTime().toISOString()})})}async flushPendingAlerts(e){let t=await this.state.list({keyPrefix:this.alertKeyPrefix(e)});for(let r of t)await this.alertOperations.run(r.key,async()=>{let i=await this.state.get(r.key);if(i?.kind==="alert"&&(i.status==="pending"||i.status==="suppressed"))await this.deliverStoredAlert(r.key,i)})}async suppressPendingAlerts(e){let t=await this.state.list({keyPrefix:this.alertKeyPrefix(e)});for(let r of t)await this.alertOperations.run(r.key,async()=>{let i=await this.state.get(r.key);if(i?.kind==="alert"&&i.status==="pending")await this.state.set(r.key,{...i,status:"suppressed"})})}async recordAlert(e,t,r){let i=ge.parse(t),n=this.alertKey(e,i.dedupeKey);await this.alertOperations.run(n,async()=>{let o=await this.state.get(n);if(o?.kind==="alert"){let c=o.includeInInbox===r.includeInInbox?o:{...o,includeInInbox:r.includeInInbox};if(c!==o)await this.state.set(n,c);if(c.status==="delivered"||c.status==="resolved")return;if(r.deliver)await this.deliverStoredAlert(n,c);return}let a={kind:"alert",checkId:e,dedupeKey:i.dedupeKey,status:r.deliver?"pending":"suppressed",alert:i,observedAt:this.currentTime().toISOString(),includeInInbox:r.includeInInbox};if(await this.state.set(n,a),r.deliver)await this.deliverStoredAlert(n,a)})}async deliverStoredAlert(e,t){if(await this.delivery.deliver(t.alert)===!1)return;await this.state.set(e,{...t,status:"delivered",deliveredAt:this.currentTime().toISOString()})}currentTime(){return this.clock?new Date(this.clock.currentTimeMillisUnsafe()):this.nowFallback()}lastSuccessKey(e){return`run:${F(e)}`}alertKeyPrefix(e){return`alert:${F(e)}:`}alertKey(e,t){return`${this.alertKeyPrefix(e)}${F(t)}`}}function Oe(e,t,r){let i=r==="daily"?jt:ma,n=i/60000,o=F(`${e}\x00${t}\x00${r}`),a=Number.parseInt(o.slice(0,12),16)%n,c=a%60,l=Math.floor(a/60),u=l%24;return{expression:r==="daily"?`${c} ${u} * * *`:`${c} ${u} * * ${Math.floor(l/24)}`,offsetMs:a*60000,periodMs:i,anchorMs:r==="daily"?0:ga}}function xt(e,t){let r=e.getTime(),i=r-t.anchorMs,o=t.anchorMs+Math.floor(i/t.periodMs)*t.periodMs+t.offsetMs;if(o>r)o-=t.periodMs;return new Date(o)}function zr(e,t){if(!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/.test(e))throw Error(`Invalid recurring-check ${t}: ${e}. Use 1-64 alphanumeric, _, or - characters.`)}var R=Zr("runtime_state_records",{namespace:Le("namespace").notNull(),key:Le("key").notNull(),value:Le("value",{mode:"json"}).notNull(),createdAt:At("created_at").notNull(),updatedAt:At("updated_at").notNull()},(e)=>({pk:Br({columns:[e.namespace,e.key]}),namespaceUpdatedAtIdx:$r("idx_runtime_state_namespace_updated_at").on(e.namespace,e.updatedAt)}));function Wr(e){return _r({url:e.url,schema:{runtimeStateRecords:R},authToken:e.authToken,authTokenEnv:"RUNTIME_STATE_DATABASE_AUTH_TOKEN"})}var ya=/^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,127}$/,Hr=512;class zt{db;namespace;schema;now;constructor(e,t,r,i=()=>new Date){va(t),this.db=e,this.namespace=t,this.schema=r,this.now=i}async get(e){let t=X(e),i=(await this.db.select().from(R).where(ee(A(R.namespace,this.namespace),A(R.key,t))).limit(1))[0];if(!i)return null;return this.schema.parse(i.value)}async has(e){let t=X(e);return(await this.db.select({key:R.key}).from(R).where(ee(A(R.namespace,this.namespace),A(R.key,t))).limit(1)).length>0}async set(e,t){let r=X(e),i=this.schema.parse(t),n=this.now().getTime();await this.db.insert(R).values({namespace:this.namespace,key:r,value:i,createdAt:n,updatedAt:n}).onConflictDoUpdate({target:[R.namespace,R.key],set:{value:i,updatedAt:n}})}async setIfNotExists(e,t){let r=X(e),i=this.schema.parse(t),n=this.now().getTime(),o=await this.db.insert(R).values({namespace:this.namespace,key:r,value:i,createdAt:n,updatedAt:n}).onConflictDoNothing({target:[R.namespace,R.key]});return Number(o.rowsAffected)>0}async compareAndSet(e,t,r){let i=X(e),n=this.schema.parse(t),o=this.schema.parse(r),a=await this.db.update(R).set({value:o,updatedAt:this.now().getTime()}).where(ee(A(R.namespace,this.namespace),A(R.key,i),A(R.value,n)));return Number(a.rowsAffected)===1}async delete(e){let t=X(e),r=await this.db.delete(R).where(ee(A(R.namespace,this.namespace),A(R.key,t)));return Number(r.rowsAffected)>0}async list(e={}){return(await this.listRows(e)).map((r)=>({key:r.key,value:this.schema.parse(r.value),createdAt:new Date(r.createdAt),updatedAt:new Date(r.updatedAt)}))}async clear(e={}){let t=await this.db.delete(R).where(ee(A(R.namespace,this.namespace),Nr(e.keyPrefix)));return Number(t.rowsAffected)}async listRows(e){let{keyPrefix:t,afterKey:r,limit:i}=e;if(r!==void 0)X(r);if(i!==void 0)s.number().int().min(1).max(1000).parse(i);let n=this.db.select({...Fr(R),key:Dt`CAST(${R.key} AS BLOB)`.mapWith((o)=>new TextDecoder("utf-8",{fatal:!0}).decode(o))}).from(R).where(ee(A(R.namespace,this.namespace),Nr(t),r!==void 0?qr(R.key,r):void 0)).orderBy(Jr(R.key)).$dynamic();return i===void 0?n:n.limit(i)}}function va(e){if(!ya.test(e))throw Error(`Invalid runtime state namespace: ${e}. Use 1-128 alphanumeric, _, ., :, or - characters.`)}function X(e){if(e.length===0||e.length>Hr)throw Error("Runtime state keys must be 1-512 characters long");return e}function Nr(e){if(e===void 0)return;return ba(e),Dt`substr(CAST(${R.key} AS BLOB), 1, length(CAST(${e} AS BLOB))) = CAST(${e} AS BLOB)`}function ba(e){if(e.length>Hr)throw Error("Runtime state key prefixes must be 512 characters or shorter");return e}class Ue{db;client;logger;databaseUrl;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;static createFresh(e,t){return new Ue(e,t??z.getInstance())}constructor(e,t){let{db:r,client:i,url:n}=Wr(e);this.db=r,this.client=i,this.databaseUrl=n,this.logger=t.child("RuntimeStateService")}initialize(){if(this.closeRequested)return Promise.resolve();return this.walInitialization??=this.initializeWALMode(),this.walInitialization}async initializeWALMode(){try{await Gr(this.client,this.databaseUrl)}catch(e){this.logger.warn("Failed to enable runtime state WAL mode (non-fatal)",e)}finally{if(this.walInitializationSettled=!0,this.closeRequested)this.closeClient()}}scoped(e){return new zt(this.db,e.namespace,e.schema)}close(){if(this.closeRequested=!0,!this.walInitialization||this.walInitializationSettled)this.closeClient()}closeClient(){if(this.clientClosed)return;this.clientClosed=!0,this.client.close()}}var Ot=T.Service("@brains/runtime-state/RuntimeStateService");function Qr(e){return N(Ot,()=>{let t=e.service??Ue.createFresh(e.config,e.logger);return{service:t,close:()=>t.close()}})}async function Mt(e,t){if(e.status==="running"){t.warn(`Daemon already running: ${e.name}`);return}e.status="starting",delete e.error;try{await e.daemon.start(),e.status="running",e.startedAt=new Date,t.debug(`Daemon started successfully: ${e.name}`)}catch(r){throw e.status="error",e.error=fe(r),t.warn(`Daemon ${e.name} failed to start: ${C(r)}`),r}}async function Lt(e,t){if(e.status==="stopped"){t.warn(`Daemon already stopped: ${e.name}`);return}e.status="stopping";try{await e.daemon.stop(),e.status="stopped",e.stoppedAt=new Date,t.debug(`Daemon stopped successfully: ${e.name}`)}catch(r){throw e.status="error",e.error=fe(r),t.error(`Failed to stop daemon: ${e.name}`,r),r}}async function Kr(e){if(!e.daemon.healthCheck)return;try{let t=await e.daemon.healthCheck();return e.health=t,t}catch(t){let r={status:"error",message:C(t),lastCheck:new Date};return e.health=r,r}}function Yr(e){return{name:e.name,pluginId:e.pluginId,status:e.status,health:e.health}}class Ze{daemons=new Map;daemonScopes=new Map;daemonTransitions=new Map;logger;static createFresh(e){return new Ze(e)}constructor(e){this.logger=e.child("DaemonRegistry")}register(e,t,r){if(this.daemonScopes.has(e))throw Error(`Cannot overwrite running daemon: ${e}`);if((this.daemonTransitions.get(e)?.pending??0)>0)throw Error(`Cannot overwrite transitioning daemon: ${e}`);if(this.daemons.has(e))this.logger.warn(`Daemon already registered: ${e}, overwriting`);let i={name:e,daemon:t,pluginId:r,status:"stopped"};this.daemons.set(e,i),this.logger.debug(`Registered daemon: ${e} from plugin: ${r}`)}has(e){return this.daemons.has(e)}get(e){return this.daemons.get(e)}start(e){if(!this.daemons.has(e))return Promise.reject(Error(`Daemon not registered: ${e}`));return this.enqueueTransition(e,"start",()=>this.startDaemon(e))}async startDaemon(e){let t=this.requireDaemon(e);if(this.daemonScopes.has(e)){await Mt(t,this.logger);return}let r=y.runSync(k.make()),i=y.acquireRelease(y.promise(()=>Mt(t,this.logger)),()=>y.promise(()=>Lt(t,this.logger)));try{await y.runPromise(k.provide(i,r)),this.daemonScopes.set(e,r)}catch(n){throw await y.runPromise(k.close(r,E.fail(n))),n}}stop(e){if(!this.daemons.has(e))return Promise.reject(Error(`Daemon not registered: ${e}`));return this.enqueueTransition(e,"stop",()=>this.stopDaemon(e))}async stopDaemon(e){let t=this.requireDaemon(e),r=this.daemonScopes.get(e);if(!r){await Lt(t,this.logger);return}this.daemonScopes.delete(e),await y.runPromise(k.close(r,E.void))}async checkHealth(e){let t=this.daemons.get(e);if(!t)throw Error(`Daemon not registered: ${e}`);return Kr(t)}getByPlugin(e){return Array.from(this.daemons.values()).filter((t)=>t.pluginId===e)}getAll(){return Array.from(this.daemons.keys())}getAllInfo(){return Array.from(this.daemons.values())}async getStatuses(){let e=this.getAllInfo();for(let t of e)if(t.daemon.healthCheck)await this.checkHealth(t.name);return e.map(Yr)}unregister(e){if(!this.daemons.has(e))return this.logger.warn(`Daemon not registered: ${e}`),Promise.resolve();return this.enqueueTransition(e,"unregister",async()=>{let t=this.requireDaemon(e);if(this.daemonScopes.has(e)||t.status!=="stopped")await this.stopDaemon(e);this.daemons.delete(e),this.logger.debug(`Unregistered daemon: ${e}`)},!0)}abandon(e){let t=this.daemons.get(e);if(!t)return;if(t.status!=="stopped"||this.daemonScopes.has(e)||(this.daemonTransitions.get(e)?.pending??0)>0)throw Error(`Cannot abandon active daemon: ${e}`);this.daemons.delete(e),this.logger.debug(`Abandoned daemon registration: ${e}`)}async startPlugin(e){let t=this.getByPlugin(e);this.logger.debug(`Starting ${t.length} daemons for plugin: ${e}`);let r,i=[];for(let n of t){let o=this.daemonScopes.has(n.name);try{if(await this.start(n.name),!o)i.push(n.name)}catch(a){if(r??=fe(a),!o)i.push(n.name)}}if(r){for(let n of i.reverse())try{await this.stop(n)}catch(o){this.logger.error(`Failed to roll back daemon: ${n}`,o)}throw r}}async stopPlugin(e){let t=this.getByPlugin(e);this.logger.debug(`Stopping ${t.length} daemons for plugin: ${e}`);for(let r of t)try{await this.stop(r.name)}catch(i){this.logger.error(`Failed to stop daemon: ${r.name}`,i)}}async clear(){this.logger.debug("Clearing all daemons");for(let e of[...this.daemons.keys()])try{await this.unregister(e)}catch(t){this.logger.error(`Failed to unregister daemon during clear: ${e}`,t)}this.logger.debug("All daemons cleared")}requireDaemon(e){let t=this.daemons.get(e);if(!t)throw Error(`Daemon not registered: ${e}`);return t}enqueueTransition(e,t,r,i=!1){let n=this.daemonTransitions.get(e);if(!n)n={tail:Promise.resolve(),lastKind:void 0,lastPromise:void 0,pending:0,terminal:!1},this.daemonTransitions.set(e,n);if(t==="start"&&n.terminal)return Promise.reject(Error(`Daemon is being unregistered: ${e}`));if(n.lastKind===t&&n.lastPromise)return n.lastPromise;if(i)n.terminal=!0;n.pending++;let o=n.tail.then(r),a=()=>{if(n.pending--,n.pending===0)this.daemonTransitions.delete(e)},c=o.then(a,a);return n.tail=c,n.lastKind=t,n.lastPromise=o,o}}var Sa=s.object({projectionId:s.string().min(1),reason:s.string().min(1),openedAt:s.number().int().nonnegative(),expiresAt:s.number().int().nonnegative()}),Ra=8,Ia=32,wa=128,Pa=5,Ca=600000,Ta=600000,ka=1000,Ea="shell.projection-circuits";class $e{operationContext;options;circuitStore;roots=new Map;reservedJobs=new Map;circuits=new Map;projections;static createFresh(e,t={}){return new $e(e,t)}constructor(e,t){this.operationContext=e,this.options={maxDerivationDepth:t.maxDerivationDepth??Ra,maxJobsPerRoot:t.maxJobsPerRoot??Ia,maxMutationsPerRoot:t.maxMutationsPerRoot??wa,repeatedTargetLimit:t.repeatedTargetLimit??Pa,retentionMs:t.retentionMs??Ca,circuitOpenMs:t.circuitOpenMs??Ta,maxTrackedRoots:t.maxTrackedRoots??ka,now:t.now??Date.now};for(let[r,i]of Object.entries(this.options)){if(r==="now")continue;if(typeof i!=="number"||!Number.isInteger(i)||i<=0)throw Error(`${r} must be a positive integer`)}this.circuitStore=t.runtimeState?.scoped({namespace:Ea,schema:Sa})}async initialize(e){if(this.projections)throw Error("Projection runtime supervisor is already initialized");if(this.projections=new Map(e.projections.map((r)=>[r.id,r])),!this.circuitStore)return;let t=this.options.now();for(let r of await this.circuitStore.list()){let i=r.value;if(i.expiresAt<=t||!this.projections.has(i.projectionId)){await this.circuitStore.delete(r.key);continue}this.circuits.set(i.projectionId,i)}}async reserveJobAdmission(e){let t=e.projectionId;if(!t)return this.createNoopJobReservation();let r=this.options.now();if(await this.prune(r),await this.requireProjection(t,r),await this.assertCircuitClosed(t,r),await this.assertDepth(e,r),e.projectionLineage.filter((u)=>u===t).length>1)await this.rejectAndOpen(t,`Projection ${t} repeats in one causal lineage`,r);let n=e.rootJobId,o=this.roots.get(n)?.jobs??0,a=this.reservedJobs.get(n)??0;if(o+a+1>this.options.maxJobsPerRoot)await this.rejectAndOpen(t,`Root ${n} exceeded projection job budget ${this.options.maxJobsPerRoot}`,r);this.reservedJobs.set(n,a+1);let c=!1,l=(u)=>{if(c)return;if(c=!0,this.releaseJobReservation(n),!u)return;let d=this.options.now(),p=this.getRootCounters(n,d);p.jobs++,p.updatedAt=d};return{commit:()=>l(!0),rollback:()=>l(!1)}}async assertMutationAdmission(e){let t=this.operationContext.current()?.provenance,r=t?.projectionId;if(!t||!r)return;let i=this.options.now();await this.prune(i),await this.requireProjection(r,i),await this.assertCircuitClosed(r,i);let n=this.getRootCounters(t.rootJobId,i);if(n.mutations++,n.updatedAt=i,n.mutations>this.options.maxMutationsPerRoot)await this.rejectAndOpen(r,`Root ${t.rootJobId} exceeded projection mutation budget ${this.options.maxMutationsPerRoot}`,i);let o=`${r}\x00${e.entityType}\x00${e.entityId}`,a=(n.targetMutations.get(o)??0)+1;if(n.targetMutations.set(o,a),a>this.options.repeatedTargetLimit)await this.rejectAndOpen(r,`Projection ${r} repeatedly mutated ${e.entityType}:${e.entityId}`,i)}async getDiagnostics(){let e=this.options.now();await this.prune(e);let t=Array.from(this.circuits.values()).sort((r,i)=>r.projectionId.localeCompare(i.projectionId)).map((r)=>({...r}));return{status:t.length>0?"unhealthy":"healthy",initialized:this.projections!==void 0,trackedRoots:this.roots.size,openCircuits:t}}async requireProjection(e,t){if(!this.projections)throw Error("Projection runtime supervisor is not initialized");let r=this.projections.get(e);if(!r)throw await this.rejectAndOpen(e,`Projection ${e} is not declared in the validated graph`,t),Error(`Projection ${e} is not declared`);return r}async assertDepth(e,t){let r=e.projectionId;if(!r)return;if(e.derivationDepth>this.options.maxDerivationDepth)await this.rejectAndOpen(r,`Projection ${r} depth ${e.derivationDepth} exceeds global maximum ${this.options.maxDerivationDepth}`,t)}async assertCircuitClosed(e,t){let r=this.circuits.get(e);if(!r)return;if(r.expiresAt<=t){this.circuits.delete(e),await this.circuitStore?.delete(e);return}throw Error(`Projection circuit ${e} is open: ${r.reason}`)}async rejectAndOpen(e,t,r){let i={projectionId:e,reason:t,openedAt:r,expiresAt:r+this.options.circuitOpenMs};this.circuits.set(e,i);try{await this.circuitStore?.set(e,i)}catch(n){throw Error(`Projection ${e} was rejected but its circuit could not be persisted`,{cause:n})}throw Error(t)}createNoopJobReservation(){return{commit:()=>{},rollback:()=>{}}}releaseJobReservation(e){let t=this.reservedJobs.get(e);if(t===void 0||t<=1){this.reservedJobs.delete(e);return}this.reservedJobs.set(e,t-1)}getRootCounters(e,t){let r=this.roots.get(e);if(r)return r;if(this.roots.size>=this.options.maxTrackedRoots){let n=Array.from(this.roots.entries()).sort(([o,a],[c,l])=>a.updatedAt-l.updatedAt||o.localeCompare(c))[0];if(n)this.roots.delete(n[0])}let i={jobs:0,mutations:0,targetMutations:new Map,updatedAt:t};return this.roots.set(e,i),i}async prune(e){for(let[t,r]of this.roots)if(e-r.updatedAt>=this.options.retentionMs)this.roots.delete(t);for(let[t,r]of this.circuits)if(r.expiresAt<=e)this.circuits.delete(t),await this.circuitStore?.delete(t)}}var xa={web:{serves:!0,executes:!1,handlerRegistrationMode:"validation-only",progressMonitorMode:"durable-reader",projectionActivation:"scheduler"},worker:{serves:!1,executes:!0,handlerRegistrationMode:"execution-only",progressMonitorMode:"durable-writer",projectionActivation:"executor"},combined:{serves:!0,executes:!0,handlerRegistrationMode:"combined",progressMonitorMode:"combined",projectionActivation:"scheduler"}};function Be(e){return xa[e??"combined"]}var Vr=[J.created,J.updated,J.deleted];function Xr(e,t,r){let i=Vr.map((o)=>e.subscribe(o,(a)=>(t.send({type:o,payload:a.payload}),{success:!0}))),n=t.onEvent((o)=>{if(!Vr.includes(o.type))return;e.deliverPeer(o.type,o.payload).catch((a)=>{r.warn(`Failed to deliver peer event ${o.type}`,{error:a})})});return()=>{for(let o of i)o();n()}}var ja=20,Aa=0.5,Da=0.06,za=5;function ti(e){return async({answer:t})=>{let i=(await e.entityService.search({query:t,options:{limit:ja,minScore:Aa,visibilityScope:D("public"),publishedOnly:!0}})).filter((o)=>e.isCitable(o.entity.entityType)),n=Math.max(...i.map((o)=>o.score));return i.filter((o)=>o.score>=n-Da).slice(0,za).map(({entity:o})=>ei(o,e))}}function Oa(e,t,r,i,n){return[J.created,J.updated,J.deleted].map((a)=>e.observe(a,async(c)=>{if(c.payload.entityType===t&&(r===null||c.payload.entityId===r)){await i();let l=a.replace("entity:","");n.debug(`${t} entity ${l}, cache refreshed`)}return{success:!0}}))}function ri(e,t,r,i){return Oa(e,t,t,async()=>{await r(),await e.send({type:B.identityChanged,payload:{entityType:t},sender:"shell",broadcast:!0})},i)}async function Ma(e,t,r){let i=La(e.kind);if(!i)return null;try{let n=t.scoped({namespace:i,refKind:e.kind,routePath:""});return Ua(await n.read(e.id),e)}catch(n){return r.debug("Skipped unavailable prior runtime upload",{uploadKind:e.kind,uploadId:e.id,error:C(n)}),null}}function La(e){return e==="upload"?"upload":null}function Ua(e,t){let{record:r,content:i}=e;if(Za(r.mediaType))return{kind:"text",filename:r.filename,mediaType:r.mediaType,content:new TextDecoder("utf-8").decode(i).replace(/^\uFEFF/,""),sizeBytes:r.sizeBytes,source:t};return{kind:"file",filename:r.filename,mediaType:r.mediaType,data:new Uint8Array(i),sizeBytes:r.sizeBytes,source:t}}function Za(e){let t=e.toLowerCase();return t.startsWith("text/")||t==="application/json"}function gi(e){let{config:t,entityService:r,logger:i,messageBus:n,aiService:o,mcpService:a,conversationService:c,runtimeUploadRegistry:l,disposables:u,executionOnly:d=!1}=e,p=di.createFresh(r,i,t.identity);u.push(...ri(n,j.BRAIN_CHARACTER,()=>p.refreshCache(),i));let g=pi.createFresh(r,i,t.profile),f=mi.createFresh(i,async(b)=>{let I=await De(n,"shell:canonical-identity-service",b).catch(()=>null);if(!I?.canonicalId)return null;return{userId:I.userId,canonicalId:I.canonicalId,displayName:I.displayName}}),m=ui({guestPricing:ai(o.getConfig().model),model:o.getModel(),modelId:o.getConfig().model,webSearch:o.getConfig().webSearch,temperature:o.getConfig().temperature,maxTokens:o.getConfig().maxTokens,reasoningEffort:o.getConfig().reasoningEffort,messageBus:n}),h=ci(t.name),w=new Ae(t.entityDisplay),v={isCitable:(b)=>w.isCitable(b),urlFor:(b,I)=>w.generateUrl(b,I),siteBaseUrl:t.siteBaseUrl},S=li.createFresh(a,c,p,g,i,{agentFactory:m,canonicalIdentityResolver:f,entityLinks:v,...e.embeddingUsage?{embeddingUsage:e.embeddingUsage}:{},...t.embedding.enabled?{indexReadiness:r,guestAnswerSources:ti({entityService:r,...v})}:{},uploadAttachmentResolver:(b)=>Ma(b,l,i),guestAskedBefore:async(b)=>{let I=await n.collect({type:ii,sender:"shell:agent-service",payload:b});return ni(I.flatMap((P)=>("noop"in P)||!P.success?[]:[P.data]))},agentContextProvider:async(b)=>(await n.collect({type:oi,sender:"shell:agent-service",payload:b})).flatMap((P)=>{if("noop"in P||!P.success)return[];return si(P.data)}),...h?{assistantAgentId:h}:{},...t.agentInstructions&&{agentInstructions:t.agentInstructions}});if(u.push(...ri(n,j.ANCHOR_PROFILE,()=>g.refreshCache(),i)),!d)u.push(n.subscribe(B.identityChanged,async()=>(S.invalidateAgent(),{success:!0})));return{identityService:p,profileService:g,canonicalIdentityService:f,agentService:S}}var he=T.Service("@brains/job-queue/JobQueueService"),_e=T.Service("@brains/job-queue/BatchJobManager"),We=T.Service("@brains/job-queue/JobProgressMonitor"),Ne=T.Service("@brains/job-queue/JobQueueWorker");function bi(e){return N(he,()=>{let t=e.service??fi.createFresh(e.config,e.logger,{...e.operationContext&&{operationContext:e.operationContext},...e.projectionAdmission&&{projectionAdmission:e.projectionAdmission},...e.handlerRegistrationMode&&{handlerRegistrationMode:e.handlerRegistrationMode}});return{service:t,close:()=>t.close()}})}function Si(e){let t=!1,r=y.gen(function*(){let i=yield*he,n=e.batchJobManager??yi.createFresh(i,e.logger),o=e.jobProgressMonitor??vi.createFresh(i,e.messageBus,n,e.logger,e.progressMonitorMode),a=e.jobQueueWorker??hi.createFresh(i,o,e.logger,{pollInterval:100,concurrency:e.workerConcurrency,autoStart:!1,...e.onWorkerUnhealthy&&{onUnhealthy:e.onWorkerUnhealthy}},{...e.operationContext&&{operationContext:e.operationContext},...e.projectionBatchScope&&{projectionBatchScope:e.projectionBatchScope}});return T.make(_e,n).pipe(T.add(We,o),T.add(Ne,a))});return{layer:_.effectContext(y.acquireRelease(r,(i)=>t?y.void:$a(i))),abandon:()=>{t=!0}}}function $a(e){let t=T.get(e,Ne),r=T.get(e,We),i=T.get(e,_e);return y.gen(function*(){let n=yield*y.exit(y.tryPromise({try:()=>t.stop(),catch:(l)=>l})),o=yield*y.exit(y.tryPromise({try:()=>r.stop(),catch:(l)=>l})),a=yield*y.exit(y.tryPromise({try:async()=>{await i.stop()},catch:(l)=>l})),c=[n,o,a].find(E.isFailure);if(c)yield*y.die(q.squash(c.cause))})}function Ba(e,t=(r)=>process.exit(r)){return(r)=>{e.error("Job queue worker requires process restart",{reason:r,exitCode:1}),t(1)}}function Fe(e){let t=y.runSyncExit(k.close(e,E.void));if(E.isFailure(t))throw q.squash(t.cause)}function Ri(e){let t=e.operationContext??qe.createFresh(),r=y.runSync(k.make()),i,n;try{let o=y.runSync(_.buildWithScope(bi({config:e.jobQueueConfig,logger:e.logger,operationContext:t,...e.projectionAdmission&&{projectionAdmission:e.projectionAdmission},...e.handlerRegistrationMode&&{handlerRegistrationMode:e.handlerRegistrationMode},...e.dependencies?.jobQueueService&&{service:e.dependencies.jobQueueService}}),r)),a=T.get(o,he),c=y.runSync(k.make());i=c;let l=Si({messageBus:e.messageBus,logger:e.logger,operationContext:t,...e.projectionBatchScope&&{projectionBatchScope:e.projectionBatchScope},onWorkerUnhealthy:Ba(e.logger),workerConcurrency:e.workerConcurrency,...e.progressMonitorMode&&{progressMonitorMode:e.progressMonitorMode},...e.dependencies?.batchJobManager&&{batchJobManager:e.dependencies.batchJobManager},...e.dependencies?.jobProgressMonitor&&{jobProgressMonitor:e.dependencies.jobProgressMonitor},...e.dependencies?.jobQueueWorker&&{jobQueueWorker:e.dependencies.jobQueueWorker}});n=l;let u=y.runSync(_.buildWithScope(l.layer.pipe(_.provide(_.succeed(he,a))),c)),d=T.get(u,_e),p=T.get(u,We),g=T.get(u,Ne),f,m=!1,h=!1;return{batchJobManager:d,jobProgressMonitor:p,jobQueueService:a,jobQueueWorker:g,closeRuntime:()=>(m=!0,f??=y.runPromise(k.close(c,E.void)),f),rollbackRuntime:()=>{if(m)return;m=!0,l.abandon(),Fe(c)},closeDatabase:()=>{if(h)return;h=!0,Fe(r)}}}catch(o){if(i)try{n?.abandon(),Fe(i)}catch(a){e.logger.warn("Failed to release partial job runtime acquisition",a)}try{Fe(r)}catch(a){e.logger.warn("Failed to release partial job database acquisition",a)}throw o}}function wi(e){return{deliver:async(t)=>{if(!e.hasHandlers(Ut))return!1;let r=await e.send({type:Ut,payload:{title:t.title,body:t.body,...t.html?{html:t.html}:{}},sender:"shell.recurring-checks"});if(!("success"in r)||!r.success||!r.data)throw Error("Recurring alert delivery failed");let i=Ii.safeParse(r.data);if(!i.success||i.data.status!=="sent")throw Error("Recurring alert delivery failed");return!0}}}function Ci(e){return{sourceId:"recurring-checks",displayName:"Recurring checks",list:async()=>(await e.listOpenAlerts()).map((t)=>({id:t.id,title:Pi(t.title,160),summary:Pi(t.body,1000),receivedAt:t.observedAt,urgency:"high",actions:[{id:"resolve",label:"Dismiss",confirm:!0}]})),act:async(t,r,i)=>{if(i.permissionLevel!=="admin")throw Error("Admin permission required");if(r!=="resolve")throw Error("Invalid recurring-check inbox action");await e.resolveOpenAlert(t)}}}function Pi(e,t){return e.length<=t?e:e.slice(0,t)}function Ti(e,t){if(t)return t;let r={debug:x.DEBUG,info:x.INFO,warn:x.WARN,error:x.ERROR}[e.logging.level];return z.createFresh({level:r,context:e.logging.context,format:e.logging.format==="json"?"json":"text",...e.logging.file?{logFile:e.logging.file}:{}})}function ki(e){return{apiKey:e.ai.apiKey,model:e.ai.model,temperature:e.ai.temperature,maxTokens:e.ai.maxTokens,webSearch:e.ai.webSearch,...e.ai.reasoningEffort&&{reasoningEffort:e.ai.reasoningEffort},...e.ai.imageApiKey?{imageApiKey:e.ai.imageApiKey}:{}}}function ae(e){return{url:e.url,...e.authToken?{authToken:e.authToken}:{}}}function Yi(e){let{config:t,dependencies:r,initializerLogger:i,lifecycle:n,processRole:o,peerChannel:a}=e;i.debug("Initializing Shell services");let c=Be(o),l=Ti(t,r?.logger),u=r?.operationContext??qe.createFresh(),d=[],p=Gi.createFresh(),g=r?.embeddingService??Hi.createFresh({apiKey:t.ai.apiKey,logger:l,usage:p}),f=r?.aiService??Ji.createFresh(ki(t),l),m=r?.entityRegistry??xi.createFresh(l),h=r?.messageBus??qi.createFresh(l,u);if(a)d.push(Xr(h,a,l));let w=r?.templateRegistry??Ai.createFresh(l),v=r?.dataSourceRegistry??ji.createFresh(l),S=r?.renderService??zi.createFresh(w),b=r?.daemonRegistry??Ze.createFresh(l),I=r?.pluginManager??Ki.createFresh(l,b),P=r?.permissionService??new Di(t.permissions,{spaces:t.spaces,entityActionFloor:(Z)=>m.getEntityTypeConfig(Z).actionPolicy}),U=r?.profileKindRegistry??new Qi(t.profileKind),Ie=r?.channelRegistry??new Li,gt=r?.inboxRegistry??new Ui,js=r?.inboxFollowUpRegistry??new Zi(l),As=r?.operationalHealthRegistry??new Fi,Ds=r?.accountSettingsRegistry??new Mi,zs=r?.attachmentRegistry??$i.createFresh(),mr=r?.runtimeUploadRegistry??Bi.createFresh({dataDir:t.dataDir,logger:l}),Os=n.buildLayer(Qr({config:ae(t.runtimeStateDatabase),logger:l,...r?.runtimeStateService&&{service:r.runtimeStateService}})),ft=T.get(Os,Ot),ht=r?.projectionRuntimeSupervisor??$e.createFresh(u,{runtimeState:ft}),gr=r?.mcpService??Ni.createFresh(h,l),yt={},Ms={runFreshBatchScope:(Z)=>yt.current?yt.current.runFreshBatchScope(Z):Z()},we=Ri({dependencies:r,jobQueueConfig:ae(t.jobQueueDatabase),workerConcurrency:t.jobQueue.workerConcurrency,messageBus:h,operationContext:u,projectionBatchScope:Ms,projectionAdmission:ht,handlerRegistrationMode:c.handlerRegistrationMode,progressMonitorMode:c.progressMonitorMode,logger:l}),{batchJobManager:Ls,jobProgressMonitor:Us,jobQueueService:vt,jobQueueWorker:Zs}=we;n.addSyncFinalizer(()=>we.closeDatabase()),n.addSyncFinalizer(()=>we.rollbackRuntime());let de=r?.recurringCheckService??new Me({brainId:t.siteBaseUrl??t.dataDir,scheduler:new _i,runtimeState:ft,clock:y.runSync(Ei.Clock),jobQueue:vt,logger:l,delivery:wi(h)});n.addSyncFinalizer(()=>de.abandon()),gt.registerSource("shell.recurring-checks",Ci(de)),n.addSyncFinalizer(()=>gt.unregisterPlugin("shell.recurring-checks"));let fr=(Z,St)=>{if(!c.serves)return;b.register(Z,St,"shell"),n.addSyncFinalizer(()=>b.abandon(Z))};fr("shell:recurring-checks",{start:()=>de.start(),stop:()=>de.stop()});let $s=n.buildLayer(Dr({embeddingService:g,embeddingsEnabled:t.embedding.enabled,entityRegistry:m,logger:l,jobQueueService:vt,messageBus:h,mutationAdmission:ht,...r?.projectionRuntime?.now&&{projectionNow:r.projectionRuntime.now},dbConfig:ae(t.database),embeddingDbConfig:ae(t.embeddingDatabase),...r?.entityService&&{service:r.entityService}})),Pe=T.get($s,kt);yt.current=Pe.getProjectionStore();let Bs=n.buildLayer(jr({dbConfig:ae(t.conversationDatabase),logger:l,messageBus:h,...r?.conversationService&&{service:r.conversationService}})),bt=T.get(Bs,Tt);fr("shell:guest-retention",Wi({intervalMs:60000,logger:l,run:async()=>{await bt.deleteExpiredGuestConversations(100)}})),n.addSyncFinalizer(()=>{for(let Z of d.splice(0))try{Z()}catch(St){l.warn("Failed to dispose shell subscription",St)}});let _s=r?.contentService??new Oi({logger:l,entityService:Pe,aiService:f,templateRegistry:w,dataSourceRegistry:v,generationAuthorizer:Er(P,h)}),{identityService:Ws,profileService:Ns,canonicalIdentityService:Fs,agentService:qs}=gi({config:t,entityService:Pe,embeddingService:g,embeddingUsage:p,entityRegistry:m,logger:l,messageBus:h,aiService:f,mcpService:gr,conversationService:bt,runtimeUploadRegistry:mr,disposables:d,executionOnly:!c.serves});return{logger:l,operationContext:u,projectionRuntimeSupervisor:ht,disposables:d,entityRegistry:m,messageBus:h,renderService:S,daemonRegistry:b,pluginManager:I,templateRegistry:w,dataSourceRegistry:v,mcpService:gr,embeddingService:g,entityService:Pe,aiService:f,conversationService:bt,contentService:_s,jobQueueService:vt,jobQueueWorker:Zs,batchJobManager:Ls,jobProgressMonitor:Us,jobServicesLifecycle:we,permissionService:P,identityService:Ws,profileService:Ns,canonicalIdentityService:Fs,profileKindRegistry:U,channelRegistry:Ie,inboxRegistry:gt,inboxFollowUpRegistry:js,operationalHealthRegistry:As,accountSettingsRegistry:Ds,agentService:qs,attachmentRegistry:zs,runtimeUploadRegistry:mr,runtimeStateService:ft,recurringCheckService:de}}function rn(e,t){e.register(Zt.name,Zt),t.debug("Shell system templates registered")}function nn(e,t){e.register(me.BASE_ENTITY_DISPLAY,{name:"base-entity-display",description:"Display template for base entities",schema:$t,formatter:new Vi,requiredPermission:"public"}),t.debug("Base entity display template registered")}function on(e,t){e.registerEntityType(j.NOTE,$t,new Xi,{projectionSourceRole:"primary"}),t.debug("Fallback base entity adapter registered")}function sn(e,t){let r=new en;e.registerEntityType(j.BRAIN_CHARACTER,r.schema,r,{classification:"system",projectionSource:!1,projectionSourceRole:"excluded"}),t.debug("Brain character entity support registered")}function an(e,t){let r=new tn;e.registerEntityType(j.ANCHOR_PROFILE,r.schema,r,{classification:"system",projectionSourceRole:"canonical"}),t.debug("Anchor profile entity support registered")}async function cn(e){let{plugins:t,pluginManager:r,logger:i,initOptions:n}=e,o=n?.registrationContext?.executionOnly,a=o?t.filter((c)=>c.type!=="interface"):t;i.debug(`Found ${a.length} plugins to register`);for(let c of a)i.debug(`Registering plugin: ${c.id}`),r.registerPlugin(c);if(await r.initializePlugins(n?.registrationContext),o)await r.registerInterfaceChannels(t.filter((c)=>c.type==="interface"),n.registrationContext);if(!n?.registerOnly){for(let{id:c,error:l}of r.getFailedPlugins())if(r.getPlugin(c)?.requiresDaemonStartup?.())throw l}i.debug("Plugin initialization complete")}class Je{logger;config;processRole;peerChannel;static createFresh(e,t,r,i){return new Je(e,t,r,i)}constructor(e,t,r,i){this.logger=e.child("ShellInitializer"),this.config=t,this.processRole=r,this.peerChannel=i}registerShellTemplates(e){rn(e,this.logger)}registerBaseEntityDisplayTemplate(e){nn(e,this.logger)}registerFallbackBaseEntity(e){on(e,this.logger)}registerBrainCharacterSupport(e){sn(e,this.logger)}registerAnchorProfileSupport(e){an(e,this.logger)}async initializePlugins(e,t){await cn({plugins:this.config.plugins,pluginManager:e,logger:this.logger,initOptions:t})}initializeServices(e,t){return Yi({config:this.config,dependencies:t,initializerLogger:this.logger,lifecycle:e,...this.processRole&&{processRole:this.processRole},...this.peerChannel&&{peerChannel:this.peerChannel}})}registerJobHandlers(e,t,r){let i=un.createFresh(t,r);e.registerHandler(ln.contentGeneration,i,"shell")}wireShell(e,t){e.pluginManager.setShell(t)}async initializeAll(e,t,r,i){this.logger.debug("Starting Shell initialization");try{if(this.registerShellTemplates(e),this.registerBaseEntityDisplayTemplate(e),this.registerBrainCharacterSupport(t),this.registerAnchorProfileSupport(t),await this.initializePlugins(r,i),!t.hasEntityType(j.NOTE))this.registerFallbackBaseEntity(t);this.logger.debug("Shell registration phase complete")}catch(n){throw this.logger.error("Shell initialization failed",n),n}}}var Bt=s.strictObject({waveId:s.string().trim().min(1),ruleId:s.string().trim().min(1)});class _t{ruleById;store;coordinator;getJobStatus;onDiagnostic;inputContext;executionContext;reconcileTargets;now;constructor(e){let t=new Map;for(let r of e.rules){if(t.has(r.id))throw Error(`Duplicate executable projection rule "${r.id}"`);t.set(r.id,r)}this.ruleById=t,this.store=e.store,this.coordinator=e.coordinator,this.getJobStatus=e.getJobStatus??(async()=>null),this.onDiagnostic=e.onDiagnostic,this.inputContext=e.inputContext,this.executionContext=e.executionContext,this.reconcileTargets=e.reconcileTargets,this.now=e.now}validateAndParse(e){let t=Bt.safeParse(e);return t.success?t.data:null}async onTerminalError(e,t,r){let i=Bt.parse(t);await this.coordinator.failActiveWaveWithIncident({waveId:i.waveId,ruleId:i.ruleId,jobId:r,failureReason:"Projection rule job exhausted retries"})}async process(e,t,r,i){let n=Bt.parse(e),o=this.ruleById.get(n.ruleId);if(!o)throw Error(`Projection rule "${n.ruleId}" is not executable`);let[a,c,l,u]=await Promise.all([this.store.listWaveInputs(n.waveId),this.store.listWaveRules(n.waveId),this.store.getWave(n.waveId),this.getJobStatus(t)]);if(!l)throw Error(`Projection wave "${n.waveId}" does not exist`);if(l.status!=="running"&&l.status!=="superseded")throw Error(`Projection wave "${n.waveId}" is not active`);let d=c.find((P)=>P.ruleId===n.ruleId);if(!d)throw Error(`Projection rule "${n.ruleId}" is not scheduled for wave "${n.waveId}"`);let p={waveId:n.waveId,ruleId:o.id,ruleVersion:o.version,jobId:t,attemptNumber:(u?.retryCount??0)+1,cutoffGeneration:l.cutoffGeneration};if(await this.recordDiagnostic({...p,event:"attempt-started"}),l.status==="superseded"){let P=await this.store.listPendingInputs();return await this.recordDiagnostic({...p,event:"apply-completed",applyOutcome:"superseded",highestPendingGeneration:He(P)}),{waveId:n.waveId,ruleId:o.id,outcome:"superseded",inputFingerprint:null,changedTargets:[]}}if(await this.store.supersedeWaveIfStale(n.waveId,this.now())){let P=await this.store.listPendingInputs();return await this.recordDiagnostic({...p,event:"apply-completed",applyOutcome:"superseded",highestPendingGeneration:He(P)}),await this.coordinator.continueAfterSupersession(n.waveId),{waveId:n.waveId,ruleId:o.id,outcome:"superseded",inputFingerprint:null,changedTargets:[]}}let g=Na(a,c,d.level),f=await o.selectInput({waveId:n.waveId,inputs:g},this.inputContext,i),m=o.fingerprint(f),h={...p,inputFingerprint:m,selectedSourceCount:Wa(f,g)};await this.recordDiagnostic({...h,event:"input-selected"});let w={ruleId:o.id,ruleVersion:o.version,inputFingerprint:m},v=await this.store.getRuleMemo(w);await this.recordDiagnostic({...h,event:"memo-resolved",memoHit:v!==null});let S;if(v)S=v.writeIntents;else{await this.recordDiagnostic({...h,event:"derive-started",memoHit:!1});try{S=await o.derive(f,this.executionContext,i),await this.recordDiagnostic({...h,event:"derive-completed",memoHit:!1})}catch(P){throw await this.recordDiagnostic({...h,event:i.aborted?"derive-cancelled":"derive-failed",memoHit:!1}),P}}let b=await this.store.applyRuleResult({waveId:n.waveId,ruleId:o.id,ruleVersion:o.version,inputFingerprint:m,writeIntents:S,completedAt:this.now()}),I=await this.store.listPendingInputs();if(!b)return await this.recordDiagnostic({...h,event:"apply-completed",memoHit:v!==null,applyOutcome:"superseded",highestPendingGeneration:He(I)}),await this.coordinator.continueAfterSupersession(n.waveId),{waveId:n.waveId,ruleId:o.id,outcome:"superseded",inputFingerprint:m,changedTargets:[]};return await this.recordDiagnostic({...h,event:"apply-completed",memoHit:v!==null,applyOutcome:"applied",highestPendingGeneration:He(I)}),await this.reconcileTargets(b.changedTargets),await this.coordinator.advanceActiveWave(n.waveId),{waveId:n.waveId,ruleId:o.id,outcome:"applied",inputFingerprint:m,changedTargets:b.changedTargets}}async recordDiagnostic(e){if(!this.onDiagnostic)return;try{await this.onDiagnostic(e)}catch(t){this.executionContext.logger.warn("Projection diagnostics callback failed",t)}}}function Wa(e,t){if(typeof e==="object"&&e!==null&&"sources"in e&&Array.isArray(e.sources))return e.sources.length;return t.length}function He(e){if(e.length===0)return null;return e.reduce((t,r)=>Math.max(t,r.generation),e[0]?.generation??0)}function Na(e,t,r){let i=e.map((o)=>({sourceType:o.sourceType,sourceId:o.sourceId,revision:o.revision,operation:o.operation,generation:o.generation})),n=t.filter((o)=>o.status==="completed"&&o.level<r).flatMap((o)=>o.changedTargets.map((a)=>({sourceType:a.entityType,sourceId:a.entityId,revision:a.contentHash??`deleted:${a.entityType}:${a.entityId}`,operation:a.operation})));return[...i,...n]}function Fa(e){switch(e.jobStatus){case"failed":return"Projection rule job exhausted retries";case"completed":return"Projection rule job completed without applying its result";case"missing":return e.rule.jobId?"Projection rule job is missing":"Projection rule has no durable job id";default:return"Projection rule job is in an unexpected terminal state"}}var ce="shell:projection-rule";class Wt{store;queue;graph;ruleById;graphFingerprint;createWaveId;beforeWaveCompletion;scheduleWakeup;onScheduledWakeupError;now;operationQueue=new dn;scheduledWakeup;constructor(e){this.store=e.store,this.queue=e.queue,this.graph=e.graph,this.ruleById=Ha(e.graph,e.rules),this.graphFingerprint=Ga(e.graph,e.rules),this.createWaveId=e.createWaveId,this.beforeWaveCompletion=e.beforeWaveCompletion??(async()=>{}),this.scheduleWakeup=e.scheduleWakeup??qa,this.onScheduledWakeupError=e.onScheduledWakeupError??(()=>{}),this.now=e.now}dispose(){this.cancelScheduledWakeup()}advanceActiveWave(e){return this.runExclusive(async()=>{let t=await this.store.getActiveWave();if(t?.id!==e){let i=await this.store.getWave(e);if(i?.status==="completed")return i;throw Error(`Projection wave "${e}" is not active`)}let r=await this.advanceWave(t);if(r.status==="completed")await this.startNextWaveInternal();return r})}startNextWave(){return this.runExclusive(()=>this.startNextWaveInternal())}continueAfterSupersession(e){return this.runExclusive(async()=>{let t=await this.store.getActiveWave();if(t?.id===e)throw Error(`Projection wave "${e}" was not superseded`);if(t)return this.advanceWave(t);return this.startNextWaveInternal()})}failActiveWave(e){return this.runExclusive(async()=>{if((await this.store.getActiveWave())?.id!==e)throw Error(`Projection wave "${e}" is not active`);return this.store.failWave(e,this.now())})}failActiveWaveWithIncident(e){return this.runExclusive(async()=>{let t=await this.store.getActiveWave();if(t&&t.id!==e.waveId)throw Error(`Projection wave "${e.waveId}" is not active; "${t.id}" is running`);if(!t){let r=await this.store.getWave(e.waveId);if(r?.status==="superseded")return r}return this.store.failWaveWithIncident({...e,failedAt:this.now()})})}async startNextWaveInternal(){let e=await this.store.getActiveWave();if(e){let a=await this.advanceWave(e);if(a.status==="completed")await this.startNextWaveInternal();return a}let t=await this.store.listPendingInputs();if(t.length===0)return this.cancelScheduledWakeup(),null;let r=Ja(this.graph,this.ruleById,t),i=this.now();if(r>i)return this.schedulePendingWakeup(r),null;this.cancelScheduledWakeup();let n=await this.store.claimPendingWave({waveId:this.createWaveId(),graphFingerprint:this.graphFingerprint,startedAt:i});if(!n)return null;let o=await this.advanceWave(n);if(o.status==="completed")await this.startNextWaveInternal();return o}async runExclusive(e){return this.operationQueue.run(e)}schedulePendingWakeup(e){if(this.scheduledWakeup?.readyAt===e)return;this.cancelScheduledWakeup();let t={readyAt:e,cancel:()=>{}};t.cancel=this.scheduleWakeup(Math.max(0,e-this.now()),async()=>{if(this.scheduledWakeup!==t)return;this.scheduledWakeup=void 0;try{await this.startNextWave()}catch(r){this.onScheduledWakeupError(r)}}),this.scheduledWakeup=t}cancelScheduledWakeup(){this.scheduledWakeup?.cancel(),this.scheduledWakeup=void 0}async advanceWave(e){if(e.graphFingerprint!==this.graphFingerprint)throw Error(`Projection wave "${e.id}" graph fingerprint does not match the finalized graph`);let t=await this.store.listWaveRules(e.id);if(t.length===0){let a=await this.store.listWaveInputs(e.id),c=mn(this.graph,this.ruleById,a);if(c.length===0)return this.completeWave(e);await this.store.putWaveRules(e.id,c),t=await this.store.listWaveRules(e.id)}if(t.every((a)=>a.status==="completed"))return this.completeWave(e,t);let r=t.find((a)=>a.status==="failed");if(r)return this.store.failWaveWithIncident({waveId:e.id,ruleId:r.ruleId,jobId:r.jobId,failureReason:"Projection rule is in a terminal failed state",failedAt:this.now()});let i=await this.findStrandedQueuedRule(t);if(i)return this.store.failWaveWithIncident({waveId:e.id,ruleId:i.rule.ruleId,jobId:i.rule.jobId,failureReason:Fa(i),failedAt:this.now()});let n=Math.min(...t.filter((a)=>a.status!=="completed").map((a)=>a.level)),o=t.filter((a)=>a.level===n&&a.status==="pending");return await Promise.all(o.map((a)=>this.enqueueRule(e.id,a))),e}async findStrandedQueuedRule(e){for(let t of e){if(t.status!=="queued")continue;if(!t.jobId)return{rule:t,jobStatus:"missing"};let r=await this.queue.getStatus(t.jobId);if(!r||r.status==="completed"||r.status==="failed")return{rule:t,jobStatus:r?.status??"missing"}}return null}async completeWave(e,t){let[r,i]=await Promise.all([this.store.listWaveInputs(e.id),t?Promise.resolve(t):this.store.listWaveRules(e.id)]);return await this.beforeWaveCompletion({waveId:e.id,sourceTypes:[...new Set(r.map((n)=>n.sourceType))].sort(),changedTargetTypes:[...new Set(i.flatMap((n)=>n.changedTargets.map((o)=>o.entityType)))].sort()}),this.store.completeWave(e.id,this.now())}async enqueueRule(e,t){let r=await this.queue.enqueue({type:ce,data:{waveId:e,ruleId:t.ruleId},options:{source:"projection-scheduler",rootJobId:`projection-wave:${e}`,metadata:{operationType:"data_processing",operationTarget:t.ruleId,silent:!0},deduplication:"coalesce",deduplicationKey:`projection-wave:${e}:${t.ruleId}`,projection:{id:t.ruleId}}});await this.store.queueWaveRule(e,t.ruleId,r)}}function qa(e,t){let r=setTimeout(()=>{t()},e);return()=>clearTimeout(r)}function Ja(e,t,r){let n=mn(e,t,r).reduce((a,c)=>Math.max(a,t.get(c.ruleId)?.sourceChangeBatchDelayMs??0),0);if(n===0)return 0;return r.reduce((a,c)=>Math.max(a,c.markedAt),0)+n}function Ha(e,t){let r=new Map;for(let n of t){if(r.has(n.id))throw Error(`Duplicate executable projection rule "${n.id}"`);r.set(n.id,n)}let i=new Set(e.projections.map((n)=>n.id));for(let n of i)if(!r.has(n))throw Error(`Projection "${n}" has no executable rule`);for(let n of r.keys())if(!i.has(n))throw Error(`Executable projection rule "${n}" is not in the graph`);return r}function Ga(e,t){return pn({projections:e.projections,edges:e.edges,rules:[...t].sort((r,i)=>r.id.localeCompare(i.id)).map((r)=>({id:r.id,version:r.version}))})}function mn(e,t,r){let i=new Map(e.projections.map((l)=>[l.id,l])),n=gn(e,(l)=>[l.from,l.to]),o=new Set(e.projections.filter((l)=>Qa(l,r)).map((l)=>l.id)),a=[...o];while(a.length>0){let l=a.flatMap((u)=>n.get(u)??[]).filter((u)=>i.has(u)&&!o.has(u));for(let u of l)o.add(u);a=[...new Set(l)].sort()}let c=Ka(e,o);return[...o].map((l)=>{let u=i.get(l),d=t.get(l),p=c.get(l);if(!u||!d||p===void 0)throw Error(`Cannot plan projection rule "${l}"`);return{ruleId:l,targetType:u.targetType,level:p}}).sort((l,u)=>l.level-u.level||l.ruleId.localeCompare(u.ruleId))}function Qa(e,t){return e.sources.some((r)=>{let i=new Set(r.excludeTypes??[]);return t.some((n)=>!i.has(n.sourceType)&&(r.types.includes("*")||r.types.includes(n.sourceType)))})}function Ka(e,t){let r=gn(e,(o)=>t.has(o.from)?[o.to,o.from]:void 0),i=new Map,n=new Set(t);while(n.size>0){let o=[...n].filter((a)=>(r.get(a)??[]).every((c)=>i.has(c))).sort();if(o.length===0)throw Error("Reachable projection graph is not acyclic");for(let a of o){let c=(r.get(a)??[]).map((u)=>i.get(u)).filter((u)=>u!==void 0),l=c.length===0?0:Math.max(...c)+1;i.set(a,l),n.delete(a)}}return i}function gn(e,t){let r=new Map;for(let i of e.edges){let n=t(i);if(!n)continue;let[o,a]=n,c=r.get(o);if(c)c.push(a);else r.set(o,[a])}return r}async function fn(e){let t=new Wt({store:e.store,queue:e.queue,graph:e.graph,rules:e.rules,createWaveId:e.createWaveId,beforeWaveCompletion:e.beforeWaveCompletion,onScheduledWakeupError:(a)=>e.logger.error("Scheduled projection wakeup failed",a),...e.scheduleWakeup&&{scheduleWakeup:e.scheduleWakeup},now:e.now}),r=new _t({rules:e.rules,store:e.store,coordinator:t,getJobStatus:(a)=>e.queue.getStatus(a),...e.onDiagnostic&&{onDiagnostic:e.onDiagnostic},inputContext:e.inputContext,executionContext:e.executionContext,reconcileTargets:e.reconcileTargets,now:e.now});e.queue.registerHandler(ce,r,"shell");let i=()=>{},n=()=>{};try{if(e.activationMode!=="executor"){let a=async(d)=>{if(d)await e.reconcileBatches?.();await t.startNextWave()},c,l=(d)=>{if(c)return c;let p=Promise.resolve().then(()=>a(d));c=p;let g=()=>{if(c===p)c=void 0};return p.then(g,g),p},u=async()=>{if(c)return;if(await e.store.hasActiveProjectionBatch())return;await l(!1)};i=e.setWakeup(u),await l(!0),n=(e.scheduleSweep??Ya)(e.sweepIntervalMs??1000,async()=>{try{await l(!0)}catch(d){e.logger.error("Projection coordination sweep failed",d)}})}}catch(a){throw n(),i(),e.queue.unregisterHandler(ce),a}e.logger.debug("Projection runtime activated",{rules:e.rules.length,mode:e.activationMode??"scheduler"});let o=!0;return{scheduler:t,dispose:()=>{if(!o)return;o=!1,n(),i(),t.dispose(),e.queue.unregisterHandler(ce)}}}function Ya(e,t){let r=setInterval(()=>{t()},e);return r.unref(),()=>clearInterval(r)}var Va=250,Xa=s.object({success:s.boolean()}),ec=s.object({projectionBatch:s.object({operationId:s.string().min(1),childKey:s.string().min(1)})});class Ft{config;services;lifecycle;initializer;role;hooks;constructor(e,t,r,i,n,o){this.config=e,this.services=t,this.lifecycle=r,this.initializer=i,this.role=Be(n),this.hooks=o}async boot(e){this.services.logger.debug("Starting Shell boot");let t=this.initializer;await Ge([()=>this.services.entityService.initialize(),()=>this.services.jobQueueService.initialize?.()??Promise.resolve(),()=>this.services.runtimeStateService.initialize(),()=>this.services.conversationService.initialize?.()??Promise.resolve()]);let r={...this.config.entityDisplay!==void 0&&{entityDisplay:this.config.entityDisplay},...!this.role.serves&&{executionOnly:!0}};if(await t.initializeAll(this.services.templateRegistry,this.services.entityRegistry,this.services.pluginManager,{...e?.mode==="register-only"&&{registerOnly:!0},...Object.keys(r).length>0&&{registrationContext:r}}),this.services.profileKindRegistry.finalize(),this.services.channelRegistry.finalize(),this.services.inboxRegistry.finalize(),this.services.inboxFollowUpRegistry.finalize(),await this.services.pluginManager.finalizePluginRegistrations(),this.hooks.finalizeHttpRoutes(),await this.services.projectionRuntimeSupervisor.initialize(this.services.pluginManager.getProjectionGraphSnapshot()),t.registerJobHandlers(this.services.jobQueueService,this.services.contentService,this.services.entityService),e?.mode===void 0){let n=await fn({store:this.services.entityService.getProjectionStore(),queue:this.services.jobQueueService,setWakeup:(o)=>this.services.entityService.setProjectionWakeup(o),graph:this.services.pluginManager.getProjectionGraphSnapshot(),rules:this.services.pluginManager.getProjectionRulesSnapshot(),inputContext:this.hooks.createProjectionInputContext(),executionContext:this.hooks.createProjectionExecutionContext(),reconcileTargets:(o)=>this.services.entityService.reconcileProjectionTargets(o),beforeWaveCompletion:async(o)=>{if(!this.services.messageBus.hasHandlers(Nt.waveReady))return;let a=await this.services.messageBus.collect({type:Nt.waveReady,payload:o,sender:"shell"});if(a.length===0||a.some((c)=>("noop"in c)||!c.success))throw Error(`Projection wave ${o.waveId} completion was not acknowledged`)},logger:this.services.logger,createWaveId:hn,now:this.hooks.projectionRuntime?.now??Date.now,...this.hooks.projectionRuntime?.scheduleWakeup&&{scheduleWakeup:this.hooks.projectionRuntime.scheduleWakeup},...this.hooks.projectionRuntime?.onDiagnostic&&{onDiagnostic:this.hooks.projectionRuntime.onDiagnostic},...this.hooks.projectionRuntime?.scheduleSweep&&{scheduleSweep:this.hooks.projectionRuntime.scheduleSweep},...this.hooks.projectionRuntime?.sweepIntervalMs!==void 0&&{sweepIntervalMs:this.hooks.projectionRuntime.sweepIntervalMs},reconcileBatches:()=>this.services.entityService.recoverProjectionBatches(async(o,a)=>(await this.services.jobQueueService.getJobsByRootJobId(o)).flatMap((l)=>{let u=ec.safeParse(JSON.parse(l.data));if(!u.success||u.data.projectionBatch.operationId!==a)return[];return[{jobId:l.id,childKey:u.data.projectionBatch.childKey,status:l.status,terminalAt:l.completedAt}]})),activationMode:this.role.projectionActivation});this.services.disposables.push(()=>n.dispose())}if(this.services.jobQueueService.finalizeHandlerRegistrations(),this.hooks.registerCoreDataSources(),this.role.serves)this.hooks.registerSystemCapabilities();if(e?.mode==="register-only"){this.services.logger.debug("Shell boot complete (register-only mode)");return}if(await this.loadIdentityServices(),!this.role.serves){this.services.jobProgressMonitor.start(),await this.services.jobQueueWorker.start(),this.services.logger.debug("Shell boot complete (worker process)");return}let i;if(e?.mode!=="startup-check"){await this.startEarlyWebserver();let n=bn();this.services.disposables.push(this.services.messageBus.subscribe(B.initialSyncCompleted,async(c)=>(n.resolve(Xa.safeParse(c.payload).data?.success===!0),{success:!0})));let o=await this.emitPluginsRegistered(),a=await this.services.entityService.backfillMissingEmbeddings();if(this.services.logger.debug("Queued missing embedding backfill jobs",{queued:a.queued,skipped:a.skipped}),await this.services.entityService.reprojectRegisteredGroupings(),o)i=n.promise.then(async(c)=>{if(c)return this.settleStartupContent();this.services.logger.warn("Initial sync failed; ready-state defaults are not created")}).catch((c)=>{this.services.logger.error("Failed to settle startup content",c)});else await this.settleStartupContent()}else await this.prepareReadyState();if(await this.services.pluginManager.readyPlugins(),e?.mode==="startup-check"){this.services.logger.debug("Shell boot complete (startup-check mode)");return}if(await this.startRuntimeServices(),i)i.then(()=>this.startIndexReadinessMonitor()).catch((n)=>{this.services.logger.warn("Semantic index readiness monitor did not start",n)});else await this.startIndexReadinessMonitor();this.services.logger.debug("Shell boot complete")}async startEarlyWebserver(){if(!this.services.daemonRegistry.has("webserver:webserver"))return;await this.services.daemonRegistry.start("webserver:webserver"),this.services.logger.debug("Started webserver before initial sync")}async emitPluginsRegistered(){let e=await this.services.messageBus.collect({type:B.pluginsRegistered,payload:{timestamp:new Date().toISOString(),pluginCount:this.services.pluginManager.getAllPluginIds().length},sender:"shell"});return this.services.logger.debug("Emitted plugins registered event"),e.some((t)=>("data"in t)&&vn.safeParse(t.data).data?.initialSyncPending===!0)}async settleStartupContent(){await this.prepareReadyState(),await this.services.messageBus.send({type:B.startupContentSettled,payload:{timestamp:new Date().toISOString()},sender:"shell",broadcast:!0}),this.services.logger.debug("Emitted startup content settled event")}async loadIdentityServices(){await Ge([()=>this.services.identityService.refreshCache(),()=>this.services.profileService.refreshCache(),()=>this.services.canonicalIdentityService.refreshCache()]),this.services.logger.debug("Identity services loaded")}async initializeIdentityServices(){await Ge([()=>this.services.identityService.initialize(),()=>this.services.profileService.initialize(),()=>this.services.canonicalIdentityService.refreshCache()]),this.services.logger.debug("Identity services initialized")}async prepareReadyState(){await this.initializeIdentityServices();let{logger:e}=this.services,t=await yn(this.services.templateRegistry,this.services.entityService);if(t.created.length>0)e.debug(`Materialized ${t.created.length} prompt entities`);if(t.refreshed.length>0)e.info("Refreshed untouched prompts to their current defaults",{targets:t.refreshed});if(t.staleOverrides.length>0)e.info("Edited prompts are based on an older default",{targets:t.staleOverrides});if(t.unverifiedOverrides.length>0)e.info("Prompts without provenance differ from their default and are kept; delete one to restore its default",{targets:t.unverifiedOverrides});if(t.removedLegacy.length>0)e.info("Removed prompt copies stored under ids generation never read",{ids:t.removedLegacy});for(let{target:r,error:i}of t.failed)e.warn(`Could not sync prompt ${r}: ${i}`)}async startRuntimeServices(){for(let e of["shell:recurring-checks","shell:guest-retention"])if(this.services.daemonRegistry.has(e))await this.services.daemonRegistry.start(e);if(await this.services.pluginManager.startPluginDaemons(),this.role.executes)await this.services.jobQueueWorker.start();this.services.jobProgressMonitor.start(),await this.services.batchJobManager.start()}async startIndexReadinessMonitor(){await this.lifecycle.fork(this.runIndexReadinessMonitor())}runIndexReadinessMonitor(){let{entityService:e,logger:t}=this.services;return y.tryPromise({try:(r)=>e.awaitIndexReady({intervalMs:Va,signal:r}),catch:(r)=>r}).pipe(y.tap((r)=>y.sync(()=>{if(r.degraded)t.warn("Semantic index ready with degraded embeddings",r);else t.debug("Semantic index ready",r)})),y.catch((r)=>y.sync(()=>{t.warn("Semantic index readiness monitor stopped",r)})))}}var tc=s.object({}),Sn=s.string().regex(/^\d{4}-(0[1-9]|1[0-2])$/,"Expected YYYY-MM"),In=s.array(s.string().min(1)).min(1).optional().describe("Only these entity types"),rc=s.object({entityTypes:In,from:Sn.optional().describe("First month, YYYY-MM"),to:Sn.optional().describe("Last month, YYYY-MM")}),ic=s.object({staleDays:s.number().int().min(1).max(3650).default(90).describe("Days without an update before content counts as stale"),entityTypes:In});function wn(e){let t=new Rn;return t.register(Qe({type:"overview",description:"Entity counts by type, recent activity, and draft and published totals.",params:tc,handler:async(r,{entityService:i,visibilityScope:n})=>nc(i,n)})),t.register(Qe({type:"publishing-cadence",description:"Pieces per month, by type: counted in the month they were published, or created when never published.",params:rc,handler:async(r,{entityService:i,visibilityScope:n})=>sc(i,n,r)})),t.register(Qe({type:"content-health",description:"Drafts and content not updated for a long time.",params:ic,handler:async(r,{entityService:i,visibilityScope:n})=>ac(i,n,e,r)})),t}async function nc(e,t){let r=await e.getEntityCounts(t),i={},n=0;for(let{entityType:f,count:m}of r)i[f]=m,n+=m;let o=await qt(e,t),a=Date.now(),c=a-604800000,l=a-2592000000,u=0,d=0;for(let f of o){let m=new Date(f.created).getTime();if(m>=c)u++;if(m>=l)d++}let p=Cn(o),g=o.filter((f)=>f.metadata.status==="published");return{entityCounts:i,totalEntities:n,recentActivity:{last7days:u,last30days:d},contentHealth:{drafts:p.length,published:g.length}}}function oc(e){let t=e.metadata.publishedAt;return new Date(typeof t==="string"&&t?t:e.created)}function Pn(e,t){return t?e.filter((r)=>t.includes(r.entityType)):e}async function sc(e,t,r){let i=Pn(await qt(e,t),r.entityTypes),n=new Map;for(let a of i){let c=oc(a);if(isNaN(c.getTime()))continue;let l=`${c.getUTCFullYear()}-${String(c.getUTCMonth()+1).padStart(2,"0")}`;if(r.from&&l<r.from||r.to&&l>r.to)continue;let u=n.get(l);if(!u)u={},n.set(l,u);u[a.entityType]=(u[a.entityType]??0)+1}return{months:Array.from(n.entries()).sort((a,c)=>c[0].localeCompare(a[0])).map(([a,c])=>{let l=0;for(let u of Object.values(c))l+=u;return{month:a,counts:c,total:l}})}}async function ac(e,t,r,i){let n=Pn(await qt(e,t),i.entityTypes),o=Cn(n).map((u)=>({id:u.id,entityType:u.entityType,title:typeof u.metadata.title==="string"?u.metadata.title:u.id,created:u.created})),a=Date.now(),c=a-i.staleDays*24*60*60*1000,l=n.filter((u)=>{if(r.getEntityTypeConfig(u.entityType).binaryStorage)return!1;let d=new Date(u.updated).getTime();return!isNaN(d)&&d<c}).map((u)=>({id:u.id,entityType:u.entityType,title:typeof u.metadata.title==="string"?u.metadata.title:u.id,updated:u.updated,daysSinceUpdate:Math.floor((a-new Date(u.updated).getTime())/86400000)}));return{drafts:o,stale:l}}function Cn(e){return e.filter((t)=>t.metadata.status==="draft")}async function qt(e,t){let r=e.getEntityTypes(),i=[];for(let n of r){let o=await e.listEntities({entityType:n,options:{limit:1000,filter:{visibilityScope:t}}});i.push(...o)}return i}class ye{parse;idOf;items=new Map;constructor(e,t){this.parse=e,this.idOf=t}register(e){let t=this.parse(e);this.items.set(this.keyFor(t.pluginId,this.idOf(t)),t)}unregister(e,t){if(t!==void 0){this.items.delete(this.keyFor(e,t));return}let r=`${e}:`;for(let i of this.items.keys())if(i.startsWith(r))this.items.delete(i)}list(){return Array.from(this.items.values()).sort((e,t)=>e.priority-t.priority||e.label.localeCompare(t.label))}keyFor(e,t){return`${e}:${t}`}}class Jt extends ye{constructor(){super((e)=>Tn.parse(e),(e)=>e.url)}}class Ht extends ye{constructor(){super((e)=>kn.parse(e),(e)=>e.id)}}function En(e,t){return{enqueueBatch:e.enqueueBatch.bind(e),getActiveBatches:e.getActiveBatches.bind(e),getBatchStatus:e.getBatchStatus.bind(e),getActiveJobs:t.getActiveJobs.bind(t),getRecentJobs:t.getRecentJobs.bind(t),getStatus:t.getStatus.bind(t)}}var cc=["/health","/images"],lc=new Set([xn]),uc=new Set(jn),dc=new Set(["GET","POST","PUT","DELETE"]);function An(e){let t=[];for(let[r,{plugin:i}]of e.getAllPlugins()){let n,o;try{n=i.getWebRoutes?.()??[],o=i.getApiRoutes?.()??[]}catch(a){throw Error(`Failed to collect HTTP route declarations from plugin "${r}"`,{cause:a})}t.push({pluginId:r,webRoutes:n,apiRoutes:o})}return t}function pc(e){return lc.has(e)||cc.some((t)=>e===t||e.startsWith(`${t}/`))}function Gt(e,t,r=!0){let i;try{i=new URL(e,"http://route.invalid").pathname}catch{i=void 0}if(!e.startsWith("/")||e.includes("//")||e.includes("?")||e.includes("#")||e.includes("%")||e.length>1&&e.endsWith("/")||e.trim()!==e||i!==e||r&&pc(e))throw Error(`Invalid HTTP route path "${e}" declared by plugin "${t}"`)}function Dn(e,t,r){if(!e.has(t))throw Error(`Invalid HTTP route method "${t}" declared by plugin "${r}"`)}function mc(e,t){if(e!=="exact"&&e!=="prefix")throw Error(`Invalid HTTP route match "${e}" declared by plugin "${t}"`)}function gc(e,t){Gt(t.path,e.pluginId);let r=t.method??"GET";Dn(uc,r,e.pluginId);let i=t.match??"exact";if(mc(i,e.pluginId),typeof t.handler!=="function")throw Error(`Invalid HTTP route handler for "${t.path}" declared by plugin "${e.pluginId}"`);return Object.freeze({kind:"handler",ownerPluginId:e.pluginId,fullPath:t.path,method:r,match:i,sharedHostAdmission:t.public===!0?"admit":"deny",...t.preview===!0?{preview:!0}:{},handler:t.handler})}function fc(e,t){Gt(t.path,e.pluginId,!1);let r=`/api/${e.pluginId}${t.path}`;if(Gt(r,e.pluginId),Dn(dc,t.method,e.pluginId),typeof t.tool!=="string"||t.tool.trim()==="")throw Error(`Invalid HTTP route tool for "${r}" declared by plugin "${e.pluginId}"`);return Object.freeze({kind:"tool",ownerPluginId:e.pluginId,fullPath:r,method:t.method,match:"exact",sharedHostAdmission:t.public?"admit":"deny",definition:Object.freeze({...t})})}function hc(e){let t=new Map;for(let r of e){let i=`${r.method} ${r.fullPath}`,n=t.get(i);if(n!==void 0)throw Error(`HTTP route conflict for ${i} between plugins "${n}" and "${r.ownerPluginId}"; give one declaration a different method or path`);t.set(i,r.ownerPluginId)}}function yc(e){return Object.freeze(e.map((t)=>Object.freeze({ownerPluginId:t.ownerPluginId,kind:t.kind,method:t.method,fullPath:t.fullPath,match:t.match,sharedHostAdmission:t.sharedHostAdmission})))}class Ke{routes;manifest;apiRoutes;webRoutes;static createFresh(){return new Ke}constructor(){}finalize(e){if(this.routes!==void 0)throw Error("HTTP route registry has already been finalized");let t=[],r=[],i=[];for(let n of e){for(let o of n.webRoutes)t.push(gc(n,o)),r.push(Object.freeze({pluginId:n.pluginId,fullPath:o.path,definition:Object.freeze({...o})}));for(let o of n.apiRoutes){let a=fc(n,o);t.push(a),i.push(Object.freeze({pluginId:n.pluginId,fullPath:a.fullPath,definition:a.definition}))}}return hc(t),this.routes=Object.freeze(t),this.manifest=yc(this.routes),this.webRoutes=Object.freeze(r),this.apiRoutes=Object.freeze(i),this.routes}getSnapshot(){if(this.routes===void 0)throw Error("HTTP route registry has not been finalized");return this.routes}getManifest(){if(this.manifest===void 0)throw Error("HTTP route registry has not been finalized");return this.manifest}getApiRoutes(){if(this.apiRoutes===void 0)throw Error("HTTP route registry has not been finalized");return[...this.apiRoutes]}getWebRoutes(){if(this.webRoutes===void 0)throw Error("HTTP route registry has not been finalized");return[...this.webRoutes]}}function zn(e,t){e.addFinalizer(()=>t.pluginManager.shutdownPlugins()),e.addFinalizer(()=>t.jobServicesLifecycle.closeRuntime()),e.addFinalizer(()=>t.agentService.shutdown?.()),e.addFinalizer(()=>t.daemonRegistry.unregister("shell:guest-retention")),e.addFinalizer(()=>t.daemonRegistry.unregister("shell:recurring-checks"))}var vc=s.discriminatedUnion("kind",[s.object({kind:s.literal("all")}).strict().describe("Search across all entity types"),s.object({kind:s.literal("type"),entityType:s.string().min(1).describe("Entity type to search")}).strict().describe("Search within one entity type")]),Mn=s.object({query:s.string().describe("Search term"),scope:vc.describe("Structured search scope. Use { kind: 'all' } for broad search across all entity types. Use { kind: 'type', entityType } only when the user asks for a specific entity type."),limit:s.number().optional().describe("Maximum number of results"),minScore:s.number().min(0).optional().describe("Minimum relevance score. Default is 0.5; lower it only for exploratory or loose recall when weak candidates are acceptable."),includeUngenerated:s.boolean().optional().describe("Include queued/failed generation stubs in results")}),Ln=s.object({entityType:s.string().describe("Entity type"),id:s.string().describe("Entity ID, slug, or title"),part:s.enum(["full","body"]).optional().describe("full (default) returns the stored Markdown including frontmatter; body returns only the Markdown body, without frontmatter, for requests to show or copy the body verbatim.")}),Un=s.object({entityType:s.string().describe("Entity type to list"),status:s.string().optional().describe("Filter by status. Omit unless the user asks for a known status; do not invent generic statuses. For wish statuses: new, planned, in-progress, done, declined."),limit:s.number().optional().describe("Maximum number of results (default: 20)")}),bc=s.object({kind:s.literal("upload").describe("Upload ref kind"),id:s.string().min(1).describe("Upload ID")}),Zn=s.object({kind:s.literal("user-message").describe("Use verbatim text already supplied by the user. The server reads the stored message; do not copy its body into tool arguments."),messageId:s.string().min(1).optional().describe("Stored user message ID in this conversation; omit for the latest user message."),boundaryMode:s.enum(["literal","lines"]).optional().describe("Use lines for standalone delimiter lines: supply marker text without newline characters. The server excludes the opening line and its line ending, and stops at the start of the closing line, preserving every byte between them, including final newlines. Omit or use literal for inline text boundaries."),startAfter:s.string().min(1).optional().describe("Exact unique opening boundary, excluded from saved text. In lines mode, supply the whole marker line WITHOUT newline characters. In literal mode, supply the exact prefix to exclude. Omit to start at the beginning of the message."),endBefore:s.string().min(1).optional().describe("Exact unique closing boundary, excluded from saved text. In lines mode, supply the whole marker line WITHOUT newline characters; preceding content newlines are preserved. In literal mode, supply the exact suffix to exclude. Omit to end at the end of the message."),contentHash:s.string().min(1).optional().describe("Internal source hash returned with the confirmation; omit on the initial request.")}).strict(),Sc=s.discriminatedUnion("kind",[s.object({kind:s.literal("text").describe("Store exact/direct user-provided content without generation"),content:s.string().min(1).describe("Literal content for a direct save request without a stored user-message source. For pasted text already in this conversation, prefer source.kind user-message with exact boundaries instead of reproducing the body here.")}).strict(),Zn,s.object({kind:s.literal("url").describe("Create URL/domain-backed entities such as links"),url:s.string().min(1).describe("URL or domain to create from; preserve a bare domain as provided instead of adding a scheme.")}).strict(),s.object({kind:s.literal("upload").describe("Use extract-markdown to import upload text into a note, or preserve only when the user explicitly wants to save the uploaded file/document bytes themselves. Do not use for saving a previous assistant summary about an upload; use prior-response for that."),upload:bc.describe("Exact upload candidate object from the current conversation"),transform:s.enum(["extract-markdown","preserve"]).describe("extract-markdown imports upload text into a note-like entity; preserve saves raw uploaded bytes via the registered upload-save handler and derives the durable entity type from media type. Use preserve only for explicit file/document preservation, not for saving an assistant summary response.")}).strict(),s.object({kind:s.literal("prior-response").describe("Save a previous assistant response as durable content, especially an assistant summary or answer about an upload."),messageId:s.string().min(1).optional().describe("Stored assistant message ID; omit for latest savable")}).strict()]),Rc=s.discriminatedUnion("kind",[s.object({kind:s.literal("prompt").describe("Generate a new non-image durable entity from a broad prompt with no durable source entity. Use this for general topical social/newsletter/blog/deck generation. This branch has no source field; use prompt-from-source only after resolving a specific existing content entity."),entityType:s.string().min(1).describe("Entity type to generate from the prompt. Do not use image here; use standalone-image or cover-image."),title:s.string().optional().describe("Title for the generated entity"),prompt:s.string().min(1).describe("Prompt for creating new generated content. Do not use for saving/importing existing uploads or prior responses.")}).strict(),s.object({kind:s.literal("prompt-from-source").describe("Generate a new non-image durable entity from a specific resolved existing content entity. Use when the user asks to generate from/based on a source, including requests like 'create a newsletter based on my latest blog post'. After resolving the source with a tool result, call this operation in the same turn; do not merely say you can generate it."),entityType:s.string().min(1).describe("Entity type to generate from the source and prompt. Do not use image here; use standalone-image or cover-image."),title:s.string().optional().describe("Title for the generated entity"),source:s.object({entityType:s.string().min(1).describe("Resolved content source entity type, such as post for a newsletter from a blog post. Do not use brain-character or anchor-profile."),entityId:s.string().min(1).describe("Resolved source entity ID copied from a prior tool result or typed entity ref; never an upload id, filename, guessed slug, or future placeholder.")}).strict().describe("Existing durable source entity to ground this generation. Use only resolved entity refs, not uploads, filenames, profile/brain-character context, conversation-only context, unknown sources, or guessed sources."),prompt:s.string().min(1).describe("Prompt for creating new generated content from the resolved source. Do not use for saving/importing existing uploads or prior responses.")}).strict(),s.object({kind:s.literal("standalone-image").describe("Generate a standalone image that is not attached to another entity. Do not use this as a cover image substitute; requested covers require cover-image after the target entity exists."),title:s.string().optional().describe("Title for the generated image"),prompt:s.string().min(1).describe("Prompt for creating an unattached image. Not for cover images requested for a generated post/entity.")}).strict(),s.object({kind:s.literal("cover-image").describe("Generate an image and attach it to an existing entity as coverImageId. Use only after the target entity already exists and its real entityId is known; do not use in the same initial turn as generating that target entity."),target:s.object({entityType:s.string().min(1).describe("Existing target entity type. Use the actual type of the entity being covered: social-post for LinkedIn/social posts, post for blog posts, etc."),entityId:s.string().min(1).describe("Existing target entity ID copied from a prior tool result or typed entity ref; never a placeholder or guessed future id")}).strict().describe("Existing entity that should receive the generated coverImageId"),title:s.string().optional().describe("Title for the generated image"),prompt:s.string().min(1).describe("Prompt for creating the cover image")}).strict(),s.object({kind:s.literal("attachment").describe("Generate a deterministic durable artifact from an existing entity attachment provider"),source:s.object({entityType:s.string().min(1).describe("Source entity type"),entityId:s.string().min(1).describe("Canonical source entity ID copied from a prior tool result or typed entity ref; never an upload id, filename, guessed slug, or future placeholder")}).strict().describe("Existing durable entity whose attachment provider should render the artifact. Use only resolved entity refs, not uploads or conversation-only context."),attachmentType:s.string().min(1).describe('Source artifact type such as "carousel", "printable", or "og-image"'),title:s.string().optional().describe("Title for the generated artifact"),replace:s.boolean().optional().describe("Set true for regenerate, replace, refresh, or update requests so a deterministic artifact is regenerated instead of reused")}).strict()]),$n=s.object({entityType:s.string().describe("Entity type to create. Use wish for explicitly saved or tracked unmet requested capabilities or outcomes."),title:s.string().optional().describe("Title for a new entity."),visibility:On.optional().describe("Content visibility. Omit for public. Use shared for team/collaborator content readable by Trusted and Admin callers. Use restricted for private/admin-only content."),source:Sc.describe("Concrete source selector. Use exactly one source branch. For AI generation or source-derived artifacts, use system_generate instead."),replace:s.boolean().optional().describe("Create a new copy intentionally"),confirmed:s.literal(!0).optional().describe("Confirm the creation"),confirmationToken:s.string().optional().describe("Internal confirmation token returned by the confirmation flow")}).strict(),Bn=s.object({operation:Rc.describe("Generation operation selector. Use prompt for broad non-image AI-generated entities with no source, prompt-from-source for generation from a resolved existing entity, standalone-image for unattached images, cover-image for generated covers on existing entities, and attachment for deterministic source-derived artifacts; for regenerate/replace/refresh artifact requests use attachment with replace:true."),confirmed:s.literal(!0).optional().describe("Confirm generation"),confirmationToken:s.string().optional().describe("Internal confirmation token returned by the confirmation flow")}).strict(),Ic=s.object({oldText:s.string().min(1).describe("Exact text occurring once in the original stored Markdown. Include enough context to be unique."),newText:s.string().describe("Literal replacement text; empty string deletes oldText.")}).strict(),wc=s.discriminatedUnion("kind",[s.object({kind:s.literal("fields").describe("Update partial frontmatter or metadata fields"),fields:s.record(s.string(),s.unknown()).describe("Partial frontmatter fields to update. Use this for status, title, coverImageId, ogImageId, and metadata changes such as approving an agent. To set an existing image as an entity cover, set coverImageId to that image id. To remove or clear a cover image, set coverImageId to null, not an empty string. Do not use fields for anchor-profile; anchor-profile updates require the content operation.")}).strict(),s.object({kind:s.literal("content").describe("Replace the stored Markdown"),content:s.string().describe("Full replacement text you wrote yourself, stored literally. Text without frontmatter replaces the body and keeps the stored frontmatter; text with frontmatter replaces the whole document. When the user supplied the replacement text, use the source operation instead of copying it here. For small changes, use the edits operation instead of regenerating the whole document.")}).strict(),s.object({kind:s.literal("edits").describe("Apply exact text replacements to the stored Markdown"),edits:s.array(Ic).min(1).max(50).describe("Preferred for small content edits, especially long notes. Exact, unique, non-overlapping replacements matched against the original Markdown, applied atomically after confirmation. Fetch the entity first. Unchanged text is preserved without regeneration.")}).strict(),s.object({kind:s.literal("source").describe("Replace the stored Markdown with user-supplied text"),source:Zn.describe("Full replacement taken verbatim from a user message, for large rewrites the user supplied. Select the text with exact boundaries instead of copying it into content. Text without frontmatter replaces the body and keeps the stored frontmatter; text with frontmatter replaces the whole document.")}).strict()]),_n=s.object({entityType:s.string().describe("Entity type"),id:s.string().describe("Entity ID, slug, or title"),operation:wc.describe("Exactly one update operation"),confirmed:s.literal(!0).optional().describe("Confirm the update"),confirmationToken:s.string().optional().describe("Internal confirmation token returned by the confirmation flow"),contentHash:s.string().optional().describe("Content hash for optimistic concurrency")}).strict(),Wn=s.object({entityType:s.string().describe("Entity type"),id:s.string().describe("Entity ID"),confirmed:s.literal(!0).optional().describe("Confirm the deletion"),confirmationToken:s.string().optional().describe("Internal confirmation token returned by the confirmation flow")}),om=s.object({entityType:s.string().describe("Entity type to extract"),source:s.string().optional().describe("Source entity ID \u2014 omit for batch"),mode:s.enum(["derive","rebuild"]).optional().describe("Batch mode: project incrementally or rebuild from scratch"),confirmed:s.literal(!0).optional().describe("Confirm destructive rebuild"),confirmationToken:s.string().optional().describe("Internal confirmation token returned by the confirmation flow")}),Nn=s.object({batchId:s.string().optional().describe("Specific batch ID to check"),jobTypes:s.array(s.string()).optional().describe("Filter by job types")}),Pc=s.object({entityType:s.string().optional(),entityId:s.string().optional(),attachmentType:s.string().optional()}),Cc=s.object({mediaType:s.string(),url:s.string(),downloadUrl:s.string().optional(),previewUrl:s.string().optional(),filename:s.string().optional(),sizeBytes:s.number().optional(),source:Pc.optional()}),sm=s.object({entityId:s.string().optional(),status:s.enum(["created","generating"]),jobId:s.string().optional(),attachment:Cc.optional()}),am=s.object({status:s.literal("extracting"),jobId:s.string(),entityType:s.string(),source:s.string().optional(),mode:s.enum(["derive","rebuild"]).optional()});function O(e,t,r,i){try{e.permissionService.assertEntityActionAllowed(t,r,i.userPermissionLevel);return}catch(n){if(n instanceof Fn||n instanceof Error)return{success:!1,error:n.message};throw n}}async function Ve(e,t,r){let i=r.conversationId??r.channelId;if(!i)return{success:!1,error:"Conversation message is not accessible in this conversation or does not exist."};let n=await e.conversationService.getMessages(i,{limit:100}),o=t.kind==="user-message",a=o?n.filter((f)=>{if(f.role!=="user")return!1;let m=r.userPermissionLevel??"public";if(m==="admin")return!0;let h=Ye(f.metadata)?.userPermissionLevel;return(h==="public"||h==="trusted"||h==="admin")&&e.permissionService.hasPermission(m,h)}):n.filter(qn),c=t.messageId?a.find((f)=>f.id===t.messageId):a.at(-1);if(!c)return{success:!1,error:"Conversation message is not accessible in this conversation or does not exist."};if(!o)return{success:!0,messageId:c.id,content:c.content};let l=(f,m,h,w)=>{if(m===void 0)return{offset:h};let v=`${f} ${JSON.stringify(m)}`;if(m==="")return{problem:`${v} is empty`};if(t.boundaryMode==="lines"&&/[\r\n]/.test(m))return{problem:`${v} contains a newline; in lines mode give the marker line's text only`};let S=t.boundaryMode==="lines"?Tc(c.content,m,w):Jn(c.content,m,w),[b]=S;if(S.length===1&&b!==void 0)return{offset:b};return{problem:S.length===0?`${v} does not occur in the message`:`${v} occurs ${S.length} times in the message`}},u=l("startAfter",t.startAfter,0,!0),d=l("endBefore",t.endBefore,c.content.length,!1),p=[u,d].flatMap((f)=>("problem"in f)?[f.problem]:[]);if(p.length===0&&"offset"in u&&"offset"in d&&u.offset>=d.offset)p.push("startAfter must come before endBefore with content between them");if(!("offset"in u)||!("offset"in d)||p.length>0)return{success:!1,error:`User-message boundary ${p.join("; ")}; each boundary must occur exactly once. To select everything after an instruction, use boundaryMode literal with startAfter set to the instruction's exact text and omit endBefore.`};let g=c.content.slice(u.offset,d.offset);if(t.contentHash&&t.contentHash!==F(g))return{success:!1,error:"User-message source changed after the proposal. Request the change again and confirm the new approval."};return{success:!0,messageId:c.id,content:g}}function Xe(e,t){return{...e,messageId:t.messageId,contentHash:F(t.content)}}function Tc(e,t,r){return e.split(/(?<=\n)/).reduce((i,n)=>({offset:i.offset+n.length,matches:n.replace(/\r?\n$/,"")===t?[...i.matches,i.offset+(r?n.length:0)]:i.matches}),{offset:0,matches:[]}).matches}function Jn(e,t,r,i=0){let n=e.indexOf(t,i);if(n<0)return[];return[n+(r?t.length:0),...Jn(e,t,r,n+1)]}var kc="system";function M(e,t,r,i,n={}){let{visibility:o="admin",sideEffects:a}=n;return{name:`${kc}_${e}`,description:t,inputSchema:r.shape,handler:async(c,l)=>{let u=r.safeParse(c);if(!u.success)return{success:!1,error:`Invalid input: ${u.error.issues.map((d)=>`${d.path.join(".")}: ${d.message}`).join(", ")}`};try{return await i(u.data,l)}catch(d){return{success:!1,error:C(d)}}},visibility:o,...a?{sideEffects:a}:{}}}async function et(e,t,r,i){let n={interfaceType:i.interfaceType,actor:i.actor,...i.channelId&&{channelId:i.channelId},...i.channelName&&{channelName:i.channelName}},o=await t(r,n);if(o.kind==="handled")return{kind:"handled",result:o.result};let a=o.input;if(a.visibility!==r.visibility)return{kind:"error",result:{success:!1,error:"Create interceptor changed or dropped the requested entity visibility."}};let c=O(e,a.entityType,"create",i);if(c)return{kind:"error",result:c};return{kind:"continue",createInput:a}}function te(e,t){if(e.entityRegistry.hasEntityType(t))return;let r=e.entityService.getEntityTypes();return{success:!1,error:`Entity type "${t}" is not available in this brain. Available types: ${r.join(", ")}.`}}function le(e){let t={...e.conversationId?{conversationId:e.conversationId}:{},...e.channelId?{channelId:e.channelId}:{},...e.runId?{runId:e.runId}:{},...e.toolCallId?{toolCallId:e.toolCallId}:{}};return Object.keys(t).length>0?t:void 0}function Kt(e,t){if(t.getEntityTypeConfig(e.entityType).binaryStorage)return{...e,content:`[binary ${e.entityType} data \u2014 use metadata for ${e.entityType} info]`};return e}function re(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var Ec={base:"note"};function Hn(e){return Ec[e]??e.replaceAll("-"," ")}function tt(e){return[e.metadata.title,e.metadata.name,e.metadata.subject,e.metadata.slug].find((i)=>typeof i==="string"&&i.trim().length>0)??e.id}function Gn(e){return!!e&&Object.keys(e.shape).length>0}async function Qn(e,t,r){if(!r)return!1;let i=await e.conversationService.getMessages(r,{limit:100});for(let n of i){let a=Ye(n.metadata)?.attachments;if(!Array.isArray(a))continue;for(let c of a){if(!Qt(c))continue;let l=c.source;if(!Qt(l))continue;if(l.kind===t.kind&&l.id===t.id)return!0}}return!1}var xc={namespace:"upload",refKind:"upload",routePath:"/api/chat/uploads"};function jc(e){return{summary:`Save uploaded file${e.title?` as "${e.title}"`:""}?`,preview:[`Filename: ${e.filename}`,`Media type: ${e.mediaType}`,`Entity type: ${e.entityType}`,`Visibility: ${e.visibility??"public"}`,...e.title?[`Title: ${e.title}`]:[]].join(`
|
|
11
11
|
`)}}function Ac(e){let{entityType:t,title:r,visibility:i,prompt:n,content:o,url:a,from:c}=e,l=r?` "${r}"`:` ${t}`,u=`${n?"Generate":"Create"}${l}?`,d=c?.kind==="entity-attachment"?c:void 0,p=[`Entity type: ${t}`,`Visibility: ${i??"public"}`,...r?[`Title: ${r}`]:[],...a?[`URL: ${a}`]:[],...c?.kind==="upload"?["Upload: uploaded file"]:[],...d?[`Source attachment: ${d.sourceEntityType}/${d.sourceEntityId} (${d.attachmentType})`]:[],...n?[`Prompt: ${n}`]:[],...o?[`Content preview: ${o.slice(0,500)}`]:[]];return{summary:u,preview:p.join(`
|
|
12
12
|
`)}}function Dc(e){switch(e.kind){case"text":return{content:e.content};case"url":return{url:e.url};case"upload":return{from:e.upload,uploadRef:e.upload,transform:e.transform};case"prior-response":case"user-message":return{conversationMessageRef:e}}}function zc(e){if(e.source.kind==="user-message"){if(!e.resolvedMessageId||e.content===void 0)throw Error("User-message source was not resolved before confirmation");return Xe(e.source,{messageId:e.resolvedMessageId,content:e.content})}if(e.source.kind==="prior-response"){let t=e.source.messageId??e.resolvedMessageId;return{kind:"prior-response",...t?{messageId:t}:{}}}return e.source}async function Oc(e,t){let r={interfaceType:t.interfaceType,actor:t.actor,...t.channelId&&{channelId:t.channelId},...t.channelName&&{channelName:t.channelName}};return e.handler({upload:e.upload,...e.title&&{title:e.title},...e.visibility!==void 0?{visibility:e.visibility}:{}},r)}async function Mc(e,t,r){let{entityService:i,entityRegistry:n}=e,o=ie(t.title??`${t.entityType}-${Date.now()}`),a=n.getEffectiveFrontmatterSchema(t.entityType);try{let c={deduplicateId:!0,...r?{eventContext:r}:{}};return{success:!0,data:{entityId:(t.content&&Gn(a)?await i.createEntityFromMarkdown({input:{entityType:t.entityType,id:o,markdown:t.content,...t.visibility!==void 0?{visibility:t.visibility}:{}},options:c}):await i.createEntity({entity:{id:o,entityType:t.entityType,content:t.content??"",metadata:{title:t.title??o},...t.visibility!==void 0?{visibility:t.visibility}:{},created:new Date().toISOString(),updated:new Date().toISOString()},options:c})).entityId,status:"created"}}}catch(c){return{success:!1,error:C(c,"Failed to create entity")}}}function H(e){return{kind:"error",result:{success:!1,error:e}}}async function Lc(e,t,r){let{content:i,url:n,from:o,uploadRef:a,conversationMessageRef:c,transform:l}=Dc(t.source),u=c?await Ve(e,c,r):void 0;if(u&&!u.success)return{kind:"error",result:u};let d=u?.success===!0?u.content:i;if(l==="extract-markdown"&&(!a||!e.entityRegistry.getEntityTypeConfig(t.entityType).markdownImport)){let p=e.entityRegistry.getAllEntityTypes().filter((g)=>e.entityRegistry.getEntityTypeConfig(g).markdownImport);return H(`Transform "extract-markdown" requires an upload ref and a type declaring markdownImport. Available: ${p.join(", ")||"none"}. Omit transform for raw file promotion.`)}if(!d&&!n&&!o)return H('Provide `source` with kind "user-message", "text", "url", "prior-response", or "upload". Use system_generate for generated content or artifacts.');return{kind:"ok",value:{content:d,url:n,from:o,uploadRef:a,transform:l,resolvedMessageId:u?.success===!0?u.messageId:void 0}}}async function Uc(e,t,r){if(!await Qn(e,t.uploadRef,r.conversationId??r.channelId))return H("Upload ref is not accessible in this conversation or no longer exists.");if(t.transform!=="preserve")return{kind:"ok",value:{entityType:t.entityType,uploadPreserve:void 0}};let n;try{n=await e.runtimeUploads.scoped(xc).readRecord(t.uploadRef.id)}catch{return H("Upload ref not found")}let o=e.entityRegistry.getUploadSaveHandler(n.mediaType);if(!o)return H(`No installed plugin can save uploads with media type "${n.mediaType}".`);return{kind:"ok",value:{entityType:o.entityType,uploadPreserve:{upload:t.uploadRef,filename:n.filename,mediaType:n.mediaType,handler:o.handler}}}}function Zc(e,t,r){let i=t?it(t):void 0;if(e!==void 0&&i!==void 0&&e!==i)return H(`Conflicting entity visibility: system_create requested "${e}" but the source frontmatter declares "${i}".`);let n=e??i,o=n??"public";if(!rt(r.userPermissionLevel,o))return H(`Cannot create entity with visibility "${o}" \u2014 caller permission "${r.userPermissionLevel??"public"}" is not allowed to write at that level.`);return{kind:"ok",value:n}}async function $c(e,t){if(t.replace)return;let r=t.title?ie(t.title):void 0;if(!r)return;if(!await e.entityService.getEntity({entityType:t.entityType,id:r}))return;return{success:!1,error:`A ${t.entityType} already exists for "${r}". To change its fields or status, use system_update; pass replace:true to create a new copy intentionally.`}}async function Bc(e,t,r){if(!(t.source.kind==="upload"&&t.source.transform==="preserve")){let U=te(e,t.entityType);if(U)return{kind:"error",result:U}}let n=await Lc(e,t,r);if(n.kind==="error")return n;let{content:o,url:a,from:c,uploadRef:l,transform:u,resolvedMessageId:d}=n.value,p=l?await Uc(e,{entityType:t.entityType,uploadRef:l,transform:u},r):void 0;if(p?.kind==="error")return p;let g=p?.value.entityType??t.entityType,f=p?.value.uploadPreserve,m=te(e,g);if(m)return{kind:"error",result:m};let h=Zc(t.visibility,o,r);if(h.kind==="error")return h;let w=re(t.title),v=t.replace===!0,S={entityType:g,...w&&{title:w},...h.value!==void 0?{visibility:h.value}:{},...o&&{content:o},...a&&{url:a},...c&&{from:c},...u&&{transform:u},...v&&{replace:v}},b=O(e,S.entityType,"create",r);if(b)return{kind:"error",result:b};let I=e.entityRegistry.getCreateInterceptor(S.entityType);if(!S.content&&!I&&!f)return H('URL or upload source creation is supported only for entity types that explicitly handle it. Provide source kind "text" for this entity type, or use system_generate for generated content/artifacts.');let P=await $c(e,S);if(P)return{kind:"error",result:P};return{kind:"ok",prepared:{createInput:S,resolvedMessageId:d,interceptor:I,eventContext:le(r),...f&&{uploadPreserve:f}}}}function Kn(e){let t=W({label:"create",requestNoun:"creation"});return M("create","Create a new entity from existing material. Never create a duplicate to save edits: use system_update for entities already created or imported in this conversation, even while an upload import is generating. Requires confirmation; call this tool without confirmed to request that confirmation instead of asking for plain-text approval. Use visibility shared for team/collaborator content, restricted for private/admin-only content, and omit it for public content; keep visibility separate from exact source text. Use source to choose exactly one concrete source: user-message for verbatim content already pasted in this conversation (the server extracts the stored text without model copying), text for literal content without a stored message source, url for URL-first flows, prior-response for saving a previous assistant response, or upload with transform extract-markdown to import text into a note or transform preserve to save raw uploaded bytes as their durable file entity. Entity-specific instructions may direct proactive capture of the user's request itself; in that case the request is concrete text and no separate save verb is required. Use system_generate for AI generation, generated images, cover images, and source-derived artifacts such as carousel/printable PDFs or OG images. If the user includes content in the same direct save request, use source.kind user-message, omitting messageId for the latest user message. For standalone delimiter lines, use boundaryMode lines with startAfter/endBefore set to the exact marker line text WITHOUT newline characters; the server preserves all intervening bytes, including final newlines. For inline content, use literal startAfter/endBefore boundaries to exclude the save instruction. Omit boundaries only when saving the whole message. Never retype, shorten, correct, or include delimiter text in pasted source material, and never ask for a smaller copy just because it is long. For 'Save this as a note: ...', startAfter can be the exact 'Save this as a note: ' prefix. If boundaries are ambiguous, ask for clarification. If the user says save it/that/this after your immediately preceding upload summary/answer, use entityType note with source.kind prior-response unless they explicitly ask to save the uploaded file/document itself; do this even when the prior answer says there was limited readable content, and do not ask whether they meant the summary or the file after you just summarized/answered about the upload. A bare upload receipt like 'I got filename. What would you like me to do?' is not a summary/answer: for a following 'save it', preserve the latest uploaded file itself with upload transform preserve (image uploads as entityType image). Only use source.kind upload when the runtime supplies an actual upload reference/attachment; if the user message merely contains a pasted uploaded-file transcript with readable content, use source.kind user-message with boundaries selecting that visible content. On the initial create request, do not pass confirmed; the tool will return confirmation args after the user confirms.",$n,async(r,i)=>{let n=await Bc(e,r,i);if(n.kind==="error")return n.result;let{createInput:o}=n.prepared,{resolvedMessageId:a,interceptor:c,eventContext:l,uploadPreserve:u}=n.prepared;if(r.confirmed){let d=t.validateConfirmed(r.confirmationToken,r);if(d)return d}else{let d=u?jc({...o.title&&{title:o.title},filename:u.filename,mediaType:u.mediaType,entityType:o.entityType,visibility:o.visibility}):Ac(o),p=zc({source:r.source,...a&&{resolvedMessageId:a},...o.content!==void 0?{content:o.content}:{}}),g=t.buildArgs((f)=>({entityType:o.entityType,...o.title&&{title:o.title},...o.visibility!==void 0?{visibility:o.visibility}:{},source:p,...o.replace&&{replace:o.replace},confirmed:!0,confirmationToken:f}));return{needsConfirmation:!0,toolName:"system_create",summary:d.summary,preview:d.preview,args:g}}if(u)return Oc({upload:u.upload,...o.title&&{title:o.title},...o.visibility!==void 0?{visibility:o.visibility}:{},handler:u.handler},i);if(c){let d=await et(e,c,o,i);if(d.kind==="handled"||d.kind==="error")return d.result;o=d.createInput}if(!o.content)return{success:!1,error:'URL or upload source creation is supported only for entity types that explicitly handle it. Provide source kind "text" for this entity type, or use system_generate for generated content/artifacts.'};return Mc(e,o,l)},{visibility:"trusted",sideEffects:"writes"})}function _c(e){let t=e.title?` "${e.title}"`:` ${e.entityType}`,r=e.from?.kind==="entity-attachment"?e.from:void 0,i=[`Entity type: ${e.entityType}`,...e.title?[`Title: ${e.title}`]:[],...e.prompt?[`Prompt: ${e.prompt}`]:[],...r?[`Source attachment: ${r.sourceEntityType}/${r.sourceEntityId} (${r.attachmentType})`]:[],...e.targetEntityType&&e.targetEntityId?[`Target: ${e.targetEntityType}/${e.targetEntityId}`]:[]];return{summary:`Generate${t}?`,preview:i.join(`
|
|
13
|
-
`)}}async function Wc(e,t,r){if(!t)return{kind:"ok",sourceAttachment:void 0};let i=await L(e.entityService,t.sourceEntityType,t.sourceEntityId,e.logger,void 0,r);if(!i.ok)return{kind:"error",result:{success:!1,error:i.error,code:"source-not-found"}};let n={...t,sourceEntityId:i.entity.id};if(!e.attachments.hasProvider(n.sourceEntityType,n.attachmentType))return{kind:"error",result:{success:!1,error:`No attachment provider found for ${n.sourceEntityType}/${n.attachmentType}.`,code:"no-provider"}};let o=e.attachments.getProviderMetadata(n.sourceEntityType,n.attachmentType);if(!o)return{kind:"error",result:{success:!1,error:`Attachment provider for ${n.sourceEntityType}/${n.attachmentType} is missing output metadata.`,code:"provider-missing-metadata"}};return{kind:"ok",sourceAttachment:n,metadata:o}}async function Nc(e,t,r){if(!t)return{kind:"ok",source:void 0};let i=await L(e.entityService,t.entityType,t.entityId,e.logger,void 0,r);if(!i.ok)return{kind:"error",result:{success:!1,error:i.error,code:"source-not-found"}};return{kind:"ok",source:{...t,entityId:i.entity.id}}}async function Fc(e,t,r){if(!t)return{kind:"ok",target:void 0};let i=await L(e.entityService,t.entityType,t.entityId,e.logger,void 0,r);if(!i.ok)return{kind:"error",result:{success:!1,error:i.error}};return{kind:"ok",target:{...t,entityId:i.entity.id}}}async function qc(e,t,r,i,n){let{entityService:o,jobs:a}=e,c=Yt(ie(t.title??r),100);if(!c)return{success:!1,error:"Could not derive a slug from the provided title/prompt. Provide a 'title' with at least one URL-safe character."};let l=t.title??c,u=Yn(e.entityRegistry,{entityType:t.entityType,id:c,title:l});if(!u)return{success:!1,error:`Entity type '${t.entityType}' does not support queued generation. Provide an exact source to system_create instead.`};let d;try{d=(await o.createEntity({entity:u,options:{deduplicateId:!0,...i?{eventContext:i}:{}}})).entityId}catch(p){return{success:!1,error:C(p,"Failed to persist generation stub")}}try{let p=await a.enqueue({type:`${t.entityType}:generation`,data:{entityId:d,prompt:r,...t.title&&{title:t.title},...t.sourceEntityType&&{sourceEntityType:t.sourceEntityType},...t.sourceEntityId&&{sourceEntityId:t.sourceEntityId},...t.sourceEntityIds&&{sourceEntityIds:t.sourceEntityIds},...t.targetEntityType&&{targetEntityType:t.targetEntityType},...t.targetEntityId&&{targetEntityId:t.targetEntityId}},toolContext:n});return{success:!0,data:{entityId:d,status:"generating",jobId:p}}}catch(p){return{success:!1,error:C(p,"Failed to queue generation job")}}}async function Jc(e,t,r){let i,n,o=t.kind==="attachment"&&t.replace===!0;if(t.kind==="prompt"||t.kind==="prompt-from-source"){if(e.entityRegistry.getEntityTypeConfig(t.entityType).binaryStorage)return{kind:"error",result:{success:!1,error:`Prompt generation does not support binary entity type '${t.entityType}'. Use operation.kind 'attachment' for source-derived artifacts, or 'standalone-image' or 'cover-image' for generated images.`,code:"unsupported-generation"}};let a=t.kind==="prompt-from-source"?await Nc(e,t.source,r):{kind:"ok",source:void 0};if(a.kind==="error")return a;let c=re(t.title);i={entityType:t.entityType,...c?{title:c}:{},prompt:t.prompt,...a.source?.entityType&&{sourceEntityType:a.source.entityType},...a.source?.entityId&&{sourceEntityId:a.source.entityId,sourceEntityIds:[a.source.entityId]}}}else if(t.kind==="standalone-image"){let a=re(t.title);i={entityType:"image",...a?{title:a}:{},prompt:t.prompt}}else if(t.kind==="cover-image"){let a=await Fc(e,t.target,r);if(a.kind==="error"){let l=a.result;return{kind:"error",result:"success"in l&&l.success===!1?{...l,code:"target-not-found"}:l}}let c=re(t.title);i={entityType:"image",...c?{title:c}:{},prompt:t.prompt,...a.target?.entityType&&{targetEntityType:a.target.entityType},...a.target?.entityId&&{targetEntityId:a.target.entityId}}}else{let a=await Wc(e,{sourceEntityType:t.source.entityType,sourceEntityId:t.source.entityId,attachmentType:t.attachmentType},r);if(a.kind==="error")return a;n=a.sourceAttachment;let c=a.metadata;if(!c||!n)return{kind:"error",result:{success:!1,error:"Attachment generation requires provider metadata.",code:"provider-missing-metadata"}};let l=re(t.title);i={entityType:c.outputEntityType,...l?{title:l}:{},from:{kind:"entity-attachment",...n},...o&&{replace:o},...c.targetField&&{targetEntityType:n.sourceEntityType,targetEntityId:n.sourceEntityId}}}return{kind:"ok",createInput:i,sourceAttachment:n}}async function Hc(e,t,r){let i=t.operation,n=D(r.userPermissionLevel),o=await Jc(e,i,n);if(o.kind==="error")return o;let{createInput:a,sourceAttachment:c}=o,l=i.kind==="attachment"&&i.replace===!0,u=te(e,a.entityType);if(u)return{kind:"error",result:u};let d=O(e,a.entityType,"create",r);if(d)return{kind:"error",result:d};let p=e.entityRegistry.getCreateInterceptor(a.entityType);if(!a.prompt&&!a.from)return{kind:"error",result:{success:!1,error:"Provide a generation source."}};if(a.from&&!p)return{kind:"error",result:{success:!1,error:`Entity type '${a.entityType}' does not support attachment-based generation. Use operation.kind prompt-from-source for AI-generated content based on referenced source material, or choose an entity type with an attachment provider.`,code:"unsupported-generation"}};if(!p&&!l){let g=a.prompt?Yt(ie(a.title??a.prompt),100):a.title?ie(a.title):void 0;if(g){if(await e.entityService.getEntity({entityType:a.entityType,id:g}))return{kind:"error",result:{success:!1,error:`A ${a.entityType} already exists for "${g}". To change its fields or status, use system_update; pass replace:true to generate a new copy intentionally.`}}}}return{kind:"ok",prepared:{createInput:a,operation:Gc(i,a,c),sourceAttachment:c,interceptor:p,eventContext:le(r)}}}function Gc(e,t,r){if(e.kind==="attachment"){let i=r??{sourceEntityType:e.source.entityType,sourceEntityId:e.source.entityId,attachmentType:e.attachmentType};return{kind:"attachment",source:{entityType:i.sourceEntityType,entityId:i.sourceEntityId},attachmentType:i.attachmentType,...t.title&&{title:t.title},...t.replace&&{replace:t.replace}}}if(e.kind==="cover-image")return{kind:"cover-image",target:{entityType:t.targetEntityType??e.target.entityType,entityId:t.targetEntityId??e.target.entityId},...t.title&&{title:t.title},prompt:e.prompt};if(e.kind==="standalone-image")return{kind:"standalone-image",...t.title&&{title:t.title},prompt:e.prompt};if(e.kind==="prompt-from-source")return{kind:"prompt-from-source",entityType:t.entityType,...t.title&&{title:t.title},source:{entityType:t.sourceEntityType??e.source.entityType,entityId:t.sourceEntityId??e.source.entityId},prompt:e.prompt};return{kind:"prompt",entityType:t.entityType,...t.title&&{title:t.title},prompt:e.prompt}}function Vn(e){let t=W({label:"generate",requestNoun:"generation"});return M("generate","Generate durable content or artifacts. Critical: for a request to generate a post/social-post/newsletter/etc. with a cover image, call only the prompt generation first; do not call standalone-image or cover-image until the target entity exists after confirmation. Critical: broad or underspecified topical generation uses operation.kind prompt and has no source field; preserve the user's wording as the prompt and do not stop to ask what details to highlight. Never invent source IDs, use brain-character/profile, uploads, filenames, guessed ids, or placeholders as source refs. Critical: when the user asks to generate from a source such as 'my latest blog post', resolve the source, then call operation.kind prompt-from-source in the same turn; for latest blog/published source requests, use system_list metadata to compare publishedAt and do not rely on semantic search order. If dated candidates such as publishedAt are visible, choose the newest candidate by publishedAt (not updated/created order) and do not stop with prose like 'I found it and can generate it' or 'if that is the one you mean.' Requires confirmation. Calling this tool without confirmed is how you request that confirmation; do not respond with separate prose such as 'I can generate it if you want' or 'I need to queue it first.' Use operation.kind prompt for broad non-image AI-generated entities with no source, including in the same turn after an optional search finds no source. Use operation.kind prompt-from-source only when generating from a resolved existing durable source entity, for example a newsletter from a resolved post: { kind: 'prompt-from-source', entityType: 'newsletter', source: { entityType: 'post', entityId: '...' }, prompt: '...' }. Use standalone-image only for unattached generated images, cover-image with operation.target only for generated covers on existing entities, and attachment with operation.source for source-derived artifacts such as carousel/printable PDFs or OG/social preview images. When a cover-image request for an existing entity resolves a clear target via search/get, call this tool in the same turn; do not stop after saying you found the entity. For regenerate/replace/refresh source-derived artifact requests, call attachment with replace:true immediately; do not say you can queue it later. When the user asks to create/write/draft/generate new durable content, call this tool without confirmed to request confirmation instead of asking for separate prose approval. If you first resolve a clear source entity for the requested generation, still call this tool in the same turn using prompt-from-source. Use system_create instead for saving/importing existing text, URLs, uploads, prior assistant responses, or raw uploaded file preservation with upload transform preserve. On the initial generation request, do not pass confirmed; the tool returns confirmation args.",Bn,async(r,i)=>{let n=await Hc(e,r,i);if(n.kind==="error")return n.result;let{createInput:o}=n.prepared,{operation:a,interceptor:c,eventContext:l}=n.prepared;if(r.confirmed){let u=t.validateConfirmed(r.confirmationToken,r);if(u)return u}else{let u=_c(o),d=t.buildArgs((p)=>({operation:a,confirmed:!0,confirmationToken:p}));return{needsConfirmation:!0,toolName:"system_generate",summary:u.summary,preview:u.preview,args:d}}if(c){let u=await et(e,c,o,i);if(u.kind==="handled"||u.kind==="error")return u.result;o=u.createInput}if(!o.prompt)return{success:!1,error:"Attachment generation is supported only for entity types that explicitly handle source-derived artifacts."};return qc(e,o,o.prompt,l,i)},{visibility:"trusted",sideEffects:"writes"})}function Xn(e){let{entityService:t,entityRegistry:r,logger:i}=e,n=W({label:"delete",requestNoun:"deletion"});return M("delete","Request entity deletion by id. Unauthorized callers get a permission error; authorized callers get confirmation first. Do not pass confirmed on the initial request.",Wn,async(o,a)=>{if((a.userPermissionLevel??"public")==="public")return{success:!1,error:"Changing content requires higher permission; current permission is Public."};let c=O(e,o.entityType,"delete",a);if(c)return c;let l=te(e,o.entityType);if(l)return l;if(r.getAdapter(o.entityType).isSingleton===!0)return{success:!1,error:`${o.entityType} is a singleton entity and cannot be deleted through system tools. Update it instead.`};let u=D(a.userPermissionLevel),d=await L(t,o.entityType,o.id,i,void 0,u);if(!d.ok)return{success:!1,error:d.error};let{entity:p}=d;if(o.confirmed){let m=n.validateConfirmed(o.confirmationToken,o);if(m)return m;try{await t.deleteEntity({entityType:o.entityType,id:p.id})}catch(h){return{success:!1,error:C(h,"Failed to delete entity")}}return{success:!0,data:{deleted:p.id}}}let g=tt(p),f=n.buildArgs((m)=>({...o,id:p.id,confirmed:!0,confirmationToken:m}));return{needsConfirmation:!0,toolName:"system_delete",summary:`Delete "${g}"?`,preview:p.content.slice(0,200),args:f}},{visibility:"admin",sideEffects:"writes"})}function eo(e,t){let r=t.map(({oldText:o,newText:a},c)=>{let l=e.indexOf(o);if(!o||l<0)throw Error(`Edit ${c+1}: oldText was not found. Fetch the entity again and provide exact text.`);if(e.indexOf(o,l+1)!==-1)throw Error(`Edit ${c+1}: oldText is ambiguous. Include more surrounding text to match exactly once.`);return{start:l,end:l+o.length,newText:a}}).sort((o,a)=>o.start-a.start),i=0,n=[];for(let o of r){if(o.start<i)throw Error("Edits overlap in the original content. Provide non-overlapping replacements.");n.push(e.slice(i,o.start),o.newText),i=o.end}return n.push(e.slice(i)),n.join("")}import{isDeepStrictEqual as Po}from"util";class nt{diff(e,t,r={}){let i;if(typeof r==="function")i=r,r={};else if("callback"in r)i=r.callback;let n=this.castInput(e,r),o=this.castInput(t,r),a=this.removeEmpty(this.tokenize(n,r)),c=this.removeEmpty(this.tokenize(o,r));return this.diffWithOptionsObj(a,c,r,i)}diffWithOptionsObj(e,t,r,i){var n;let o=(v)=>{if(v=this.postProcess(v,r),i){setTimeout(function(){i(v)},0);return}else return v},a=t.length,c=e.length,l=1,u=a+c;if(r.maxEditLength!=null)u=Math.min(u,r.maxEditLength);let d=(n=r.timeout)!==null&&n!==void 0?n:1/0,p=Date.now()+d,g=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(g[0],t,e,0,r);if(g[0].oldPos+1>=c&&f+1>=a)return o(this.buildValues(g[0].lastComponent,t,e));let m=-1/0,h=1/0,w=()=>{for(let v=Math.max(m,-l);v<=Math.min(h,l);v+=2){let S,b=g[v-1],I=g[v+1];if(b)g[v-1]=void 0;let P=!1;if(I){let Ie=I.oldPos-v;P=I&&0<=Ie&&Ie<a}let U=b&&b.oldPos+1<c;if(!P&&!U){g[v]=void 0;continue}if(!U||P&&b.oldPos<I.oldPos)S=this.addToPath(I,!0,!1,0,r);else S=this.addToPath(b,!1,!0,1,r);if(f=this.extractCommon(S,t,e,v,r),S.oldPos+1>=c&&f+1>=a)return o(this.buildValues(S.lastComponent,t,e))||!0;else{if(g[v]=S,S.oldPos+1>=c)h=Math.min(h,v-1);if(f+1>=a)m=Math.max(m,v+1)}}l++};if(i)(function v(){setTimeout(function(){if(l>u||Date.now()>p)return i(void 0);if(!w())v()},0)})();else while(l<=u&&Date.now()<=p){let v=w();if(v)return v}}addToPath(e,t,r,i,n){let o=e.lastComponent;if(o&&!n.oneChangePerToken&&o.added===t&&o.removed===r)return{oldPos:e.oldPos+i,lastComponent:{count:o.count+1,added:t,removed:r,previousComponent:o.previousComponent}};else return{oldPos:e.oldPos+i,lastComponent:{count:1,added:t,removed:r,previousComponent:o}}}extractCommon(e,t,r,i,n){let o=t.length,a=r.length,c=e.oldPos,l=c-i,u=0;while(l+1<o&&c+1<a&&this.equals(r[c+1],t[l+1],n))if(l++,c++,u++,n.oneChangePerToken)e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1};if(u&&!n.oneChangePerToken)e.lastComponent={count:u,previousComponent:e.lastComponent,added:!1,removed:!1};return e.oldPos=c,l}equals(e,t,r){if(r.comparator)return r.comparator(e,t);else return e===t||!!r.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){let t=[];for(let r=0;r<e.length;r++)if(e[r])t.push(e[r]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join("")}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,r){let i=[],n;while(e)i.push(e),n=e.previousComponent,delete e.previousComponent,e=n;i.reverse();let o=i.length,a=0,c=0,l=0;for(;a<o;a++){let u=i[a];if(!u.removed){if(!u.added&&this.useLongestToken){let d=t.slice(c,c+u.count);d=d.map(function(p,g){let f=r[l+g];return f.length>p.length?f:p}),u.value=this.join(d)}else u.value=this.join(t.slice(c,c+u.count));if(c+=u.count,!u.added)l+=u.count}else u.value=this.join(r.slice(l,l+u.count)),l+=u.count}return i}}class to extends nt{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}}var ro=new to;function Vt(e,t,r){return ro.diff(e,t,r)}var ot=s.enum(["png","jpg","jpeg","webp","gif","svg"]),no=s.enum(["pending","draft","failed"]),oo=s.object({title:s.string().optional(),alt:s.string().optional(),format:ot,width:s.number(),height:s.number(),status:no.optional(),processingJobId:s.string().optional(),processingError:s.string().optional(),sourceUrl:s.url().optional(),sourceEntityType:s.string().optional(),sourceEntityId:s.string().optional(),sourceUploadId:s.string().optional(),sourceFilename:s.string().optional(),sourceMediaType:s.string().optional(),attachmentType:s.string().optional(),dedupKey:s.string().optional()}),ve=io.extend({entityType:s.literal("image"),metadata:oo}),Qc=s.object({url:s.string(),alt:s.string(),title:s.string(),width:s.number(),height:s.number()});function so(e){return/^https?:\/\//i.test(e)}async function ao(e,t){let r=await fetch(e);if(!r.ok)throw Error(`Failed to fetch: ${r.status} ${r.statusText}`);let i=r.headers.get("content-type");if(t&&!i?.startsWith(t))throw Error(`URL does not point to expected content type: ${i}`);let n=await r.arrayBuffer(),o=Buffer.from(n).toString("base64");return`data:${i?.split(";")[0]??"application/octet-stream"};base64,${o}`}function lo(e){let t=e.trim().match(/^data:image\/([a-z+]+);base64,(.+)$/i);if(!t?.[1]||!t[2])return null;return{format:t[1].toLowerCase(),base64:t[2]}}function st(e){let t=lo(e);if(!t)throw Error("Invalid image data URL");return t}function Kc(e,t){return`data:image/${t==="jpg"?"jpeg":t};base64,${e}`}var Yc={png:"iVBORw",jpg:"/9j/",gif:"R0lGOD",webp:"UklGR"};function Xt(e){for(let[t,r]of co(Yc))if(e.startsWith(r))return t;return null}function uo(e){let t=e.toLowerCase(),r=t==="svg+xml"?"svg":t,i=ot.safeParse(r);return i.success?i.data:null}async function Vc(e){return ao(e,"image/")}function at(e){let t=Buffer.from(e,"base64");if(t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71){let r=t.readUInt32BE(16),i=t.readUInt32BE(20);return{width:r,height:i}}if(t[0]===255&&t[1]===216){let r=2;while(r<t.length-8){if(t[r]!==255){r++;continue}let i=t[r+1];if(i===192||i===194){let o=t.readUInt16BE(r+5);return{width:t.readUInt16BE(r+7),height:o}}let n=t.readUInt16BE(r+2);r+=2+n}}if(t[0]===71&&t[1]===73&&t[2]===70){let r=t.readUInt16LE(6),i=t.readUInt16LE(8);return{width:r,height:i}}if(t.length>=30&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70){if(t[12]===86&&t[13]===80&&t[14]===56){if(t[15]===32){let r=t[26]??0,i=t[27]??0,n=t[28]??0,o=t[29]??0,a=(r|i<<8)&16383,c=(n|o<<8)&16383;return{width:a,height:c}}if(t[15]===76&&t.length>=25){let r=t.readUInt32LE(21),i=(r&16383)+1,n=(r>>14&16383)+1;return{width:i,height:n}}}}return null}function po(e){let t=uo(e);if(!t)throw Error(`Unsupported image format: ${e}`);return t}class er{entityType="image";purpose="Image assets such as generated covers, social previews, and uploaded images.";schema=ve;toMarkdown(e){return e.content}fromMarkdown(e){let{format:t,base64:r}=st(e),i=at(r);return{entityType:"image",content:e,metadata:{format:po(t),width:i?.width??0,height:i?.height??0}}}extractMetadata(e){return e.metadata}parseFrontMatter(e,t){return t.parse({})}generateFrontMatter(e){return""}getBodyTemplate(){return""}createImageEntity(e){let{dataUrl:t,title:r,alt:i}=e,{format:n,base64:o}=st(t),a=at(o),l=Xt(o)??po(n);return{entityType:"image",content:t,metadata:{title:r,alt:i??r,format:l,width:a?.width??0,height:a?.height??0,...e.status&&{status:e.status},...e.sourceUrl&&{sourceUrl:e.sourceUrl},...e.sourceEntityType&&{sourceEntityType:e.sourceEntityType},...e.sourceEntityId&&{sourceEntityId:e.sourceEntityId},...e.sourceUploadId&&{sourceUploadId:e.sourceUploadId},...e.sourceFilename&&{sourceFilename:e.sourceFilename},...e.sourceMediaType&&{sourceMediaType:e.sourceMediaType},...e.attachmentType&&{attachmentType:e.attachmentType},...e.dedupKey&&{dedupKey:e.dedupKey}}}}}var Xc=new er;function Qg(e){return go(e,{skipInvalid:!0,noRefs:!0,sortKeys:!0})}function fo(e){return mo(e)}var el=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,tl=s.record(s.string(),s.unknown());async function ho(e,t){let r=await t.getEntity({entityType:"image",id:e},ve);if(!r)return;return{url:r.content,alt:r.metadata.alt??"",title:r.metadata.title??"",width:r.metadata.width,height:r.metadata.height}}function yo(e,t){let r=el.exec(e.content);if(!r?.[1])return;try{let i=tl.safeParse(fo(r[1]));if(i.success){let n=i.data[t];return typeof n==="string"?n:void 0}}catch{return}return}function vo(e){return yo(e,"coverImageId")}function rl(e){return yo(e,"ogImageId")}function tr(e,t){return{...e,content:be(e.content,"coverImageId",t)}}function rr(e,t){return{...e,content:be(e.content,"ogImageId",t)}}async function il(e,t){let r=vo(e);if(!r)return;return ho(r,t)}var ir=bo();function nl(e,t){let r=ir.parse(e),i=new Map;ct(r,"definition",(o)=>{if(!i.has(o.identifier))i.set(o.identifier,o)});let n=new Set;return ct(r,(o,a,c)=>{if(o.type!=="image"&&o.type!=="imageReference")return;let l=o.type==="image"?o:i.get(o.identifier);if(!l)return;let u=t(l.url);if(u===l.url)return;if(n.add(l.url),o.type==="image")o.url=u;else if(c&&a!==void 0)c.children[a]={type:"image",url:u,alt:o.alt,title:l.title}}),n.size>0?ir.stringify(r):e}function ol(e){let t=[],r=ir.parse(e);return ct(r,"image",(i)=>{t.push({url:i.url,alt:i.alt??"",title:i.title??void 0})}),t}var lt=/^---\r?\n(?:[\s\S]*?\r?\n)?---[ \t]*(?:\r?\n|$)/;function So(e){return e.replace(lt,"")}var Ro=400;function ut(e,t,r){if(r===null)return!Object.hasOwn(e,t);return Object.hasOwn(e,t)&&Po(e[t],r)}function or(e,t){return new Set([...t.getFrontmatterExtensions(e).flatMap((r)=>Object.keys(r.shape)),...t.getGroupings().filter((r)=>r.types.includes(e)).map((r)=>r.field)])}function sl(e,t,r){if(r.has(t))return nr(e.content).frontmatter[t];return t==="visibility"?e.visibility:e.metadata[t]}function Co(e,t,r){let{visibility:i,coverImageId:n,ogImageId:o,...a}=t,c=i===void 0?e.visibility:Io.parse(i),l=Object.hasOwn(t,"coverImageId")?tr(e,typeof n==="string"?n:null):e,u=Object.hasOwn(t,"ogImageId")?rr(l,typeof o==="string"?o:null):l,d={...e.metadata};for(let[m,h]of Object.entries(a))if(h===null)delete d[m];else d[m]=h;let p={...u,visibility:c,metadata:d};for(let[m,h]of Object.entries(a))if(h===null)delete p[m];else p[m]=h;let g=or(e.entityType,r),f=!1;for(let[m,h]of Object.entries(t)){if(!g.has(m))continue;p.content=be(p.content,m,h),f=!0}if(f)p.metadata=r.projectMetadata(e.entityType,p.content,d);return p}function al(e,t,r){let i=r.getAdapter(e.entityType),n=i.fromMarkdown(e.content),o=i.fromMarkdown(t),a={...e.metadata};for(let c of new Set([...Object.keys(n.metadata??{}),...Object.keys(o.metadata??{})])){let l=o.metadata?.[c];if(Po(n.metadata?.[c],l))continue;if(l===void 0)delete a[c];else a[c]=l}return{...e,...o,id:e.id,entityType:e.entityType,created:e.created,updated:e.updated,contentHash:e.contentHash,content:t,metadata:a,visibility:it(t)??e.visibility}}var cl=new Set(["visibility","coverImageId","ogImageId"]),ll=s.record(s.string(),s.unknown());function ul(e,t,r,i){if(t.kind!=="fields")return;let n=t.fields,o=r.getEffectiveFrontmatterSchema(e.entityType);if(!o)return;let a=or(e.entityType,r),c=Object.keys(n).filter((m)=>a.has(m)),l;try{if(l=Co(e,n,r),c.length>0){let m=r.validateEntity(e.entityType,l),h=i.serializeEntity(m),w=nr(h).frontmatter,v=i.deserializeEntity(h,e.entityType).metadata??{};for(let S of c){let b=n[S];if(!ut(w,S,b)||!ut(v,S,b))return{success:!1,error:`The requested ${S} value would not survive frontmatter persistence.`}}}}catch(m){return{success:!1,error:C(m,"Invalid field update")}}let u=Object.keys(n).filter((m)=>!a.has(m)&&!cl.has(m)&&(m in o.shape));if(u.length===0)return;let d=r.getAdapter(e.entityType),p;try{l=r.validateEntity(e.entityType,l),p=d.extractMetadata(l)}catch{return}let g=[],f=[];for(let m of u){let h=n[m];if(Object.hasOwn(p,m)){if(!ut(p,m,h))g.push(m)}else if(h!==null||!Object.hasOwn(e.metadata,m))f.push(m)}if(f.length>0){let m;try{m=d.parseFrontMatter(d.toMarkdown(l),ll)}catch{if(g.length===0)return}if(m){for(let h of f)if(!ut(m,h,n[h]))g.push(h)}}if(g.length===0)return;return{success:!1,error:`${e.entityType} does not persist ${g.join(", ")} through 'fields'. The update would report success without changing anything. Provide full markdown with frontmatter via 'content' instead.`}}function To(e,t,r){let i=lt.exec(e.content)?.[0];if(i===void 0||!t.trim()||lt.test(t))return t;if(r.getAdapter(e.entityType).hasBody===!1)return{success:!1,error:`${e.entityType} has no body. Replace its full markdown, including frontmatter.`};return i+t}function dl(e,t,r){if(t.kind!=="content")return;let i=t.content.trim(),n=r.getEffectiveFrontmatterSchema(e);if(!n)return;if(!i)return{success:!1,error:"Full content replacement cannot be empty for this entity type. Use 'fields' for partial updates."};try{r.getAdapter(e).parseFrontMatter(t.content,n)}catch{return{success:!1,error:"Invalid content replacement for this entity type. Provide full markdown with valid frontmatter, or use 'fields' for partial updates."}}return}function pl(e,t,r){if(t.kind!=="fields"||!("coverImageId"in t.fields))return;let i=t.fields.coverImageId;if(i!==null&&i!==void 0&&typeof i!=="string")return{success:!1,error:"coverImageId must be a string or null"};if(i==="__PENDING__"||typeof i==="string"&&i.startsWith("upload-"))return{success:!1,error:"coverImageId must reference an existing image id or be null"};if(r.getAdapter(e).supportsCoverImage)return;return{success:!1,error:`Entity type '${e}' doesn't support cover images`}}function ml(e,t,r){if(t.kind==="fields"&&"status"in t.fields)return t.fields.status;if(t.kind==="content"){let i=r.getEffectiveFrontmatterSchema(e.entityType);if(!i)return e.metadata.status;try{return r.getAdapter(e.entityType).parseFrontMatter(t.content,i).status}catch{return e.metadata.status}}return e.metadata.status}function ko(e,t,r){let i=or(e.entityType,r);if(t.kind==="fields")return Object.entries(t.fields).map(([c,l])=>{let u=sl(e,c,i);if(!i.has(c))return`${c}: ${String(u??"(empty)")} \u2192 ${String(l)}`;let d=r.getEffectiveFrontmatterSchema(e.entityType)?.shape[c],p=d!==void 0&&s.safeParse(d,u).success,g=u===void 0?"(absent)":`${JSON.stringify(u)}${p?"":" (invalid existing value)"}`,f=l===null?"(removed)":JSON.stringify(l);return`${c}: ${g} \u2192 ${f}`}).join(`
|
|
13
|
+
`)}}async function Wc(e,t,r){if(!t)return{kind:"ok",sourceAttachment:void 0};let i=await L(e.entityService,t.sourceEntityType,t.sourceEntityId,e.logger,void 0,r);if(!i.ok)return{kind:"error",result:{success:!1,error:i.error,code:"source-not-found"}};let n={...t,sourceEntityId:i.entity.id};if(!e.attachments.hasProvider(n.sourceEntityType,n.attachmentType))return{kind:"error",result:{success:!1,error:`No attachment provider found for ${n.sourceEntityType}/${n.attachmentType}.`,code:"no-provider"}};let o=e.attachments.getProviderMetadata(n.sourceEntityType,n.attachmentType);if(!o)return{kind:"error",result:{success:!1,error:`Attachment provider for ${n.sourceEntityType}/${n.attachmentType} is missing output metadata.`,code:"provider-missing-metadata"}};return{kind:"ok",sourceAttachment:n,metadata:o}}async function Nc(e,t,r){if(!t)return{kind:"ok",source:void 0};let i=await L(e.entityService,t.entityType,t.entityId,e.logger,void 0,r);if(!i.ok)return{kind:"error",result:{success:!1,error:i.error,code:"source-not-found"}};return{kind:"ok",source:{...t,entityId:i.entity.id}}}async function Fc(e,t,r){if(!t)return{kind:"ok",target:void 0};let i=await L(e.entityService,t.entityType,t.entityId,e.logger,void 0,r);if(!i.ok)return{kind:"error",result:{success:!1,error:i.error}};return{kind:"ok",target:{...t,entityId:i.entity.id}}}async function qc(e,t,r,i,n){let{entityService:o,jobs:a}=e,c=Yt(ie(t.title??r),100);if(!c)return{success:!1,error:"Could not derive a slug from the provided title/prompt. Provide a 'title' with at least one URL-safe character."};let l=t.title??c,u=Yn(e.entityRegistry,{entityType:t.entityType,id:c,title:l});if(!u)return{success:!1,error:`Entity type '${t.entityType}' does not support queued generation. Provide an exact source to system_create instead.`};let d;try{d=(await o.createEntity({entity:u,options:{deduplicateId:!0,...i?{eventContext:i}:{}}})).entityId}catch(p){return{success:!1,error:C(p,"Failed to persist generation stub")}}try{let p=await a.enqueue({type:`${t.entityType}:generation`,data:{entityId:d,prompt:r,...t.title&&{title:t.title},...t.sourceEntityType&&{sourceEntityType:t.sourceEntityType},...t.sourceEntityId&&{sourceEntityId:t.sourceEntityId},...t.sourceEntityIds&&{sourceEntityIds:t.sourceEntityIds},...t.targetEntityType&&{targetEntityType:t.targetEntityType},...t.targetEntityId&&{targetEntityId:t.targetEntityId}},toolContext:n});return{success:!0,data:{entityId:d,status:"generating",jobId:p}}}catch(p){return await o.deleteEntity({entityType:t.entityType,id:d}).catch((g)=>{e.logger.warn("Failed to remove unqueued generation stub",{entityType:t.entityType,entityId:d,error:g})}),{success:!1,error:C(p,"Failed to queue generation job")}}}async function Jc(e,t,r){let i,n,o=t.kind==="attachment"&&t.replace===!0;if(t.kind==="prompt"||t.kind==="prompt-from-source"){if(e.entityRegistry.getEntityTypeConfig(t.entityType).binaryStorage)return{kind:"error",result:{success:!1,error:`Prompt generation does not support binary entity type '${t.entityType}'. Use operation.kind 'attachment' for source-derived artifacts, or 'standalone-image' or 'cover-image' for generated images.`,code:"unsupported-generation"}};let a=t.kind==="prompt-from-source"?await Nc(e,t.source,r):{kind:"ok",source:void 0};if(a.kind==="error")return a;let c=re(t.title);i={entityType:t.entityType,...c?{title:c}:{},prompt:t.prompt,...a.source?.entityType&&{sourceEntityType:a.source.entityType},...a.source?.entityId&&{sourceEntityId:a.source.entityId,sourceEntityIds:[a.source.entityId]}}}else if(t.kind==="standalone-image"){let a=re(t.title);i={entityType:"image",...a?{title:a}:{},prompt:t.prompt}}else if(t.kind==="cover-image"){let a=await Fc(e,t.target,r);if(a.kind==="error"){let l=a.result;return{kind:"error",result:"success"in l&&l.success===!1?{...l,code:"target-not-found"}:l}}let c=re(t.title);i={entityType:"image",...c?{title:c}:{},prompt:t.prompt,...a.target?.entityType&&{targetEntityType:a.target.entityType},...a.target?.entityId&&{targetEntityId:a.target.entityId}}}else{let a=await Wc(e,{sourceEntityType:t.source.entityType,sourceEntityId:t.source.entityId,attachmentType:t.attachmentType},r);if(a.kind==="error")return a;n=a.sourceAttachment;let c=a.metadata;if(!c||!n)return{kind:"error",result:{success:!1,error:"Attachment generation requires provider metadata.",code:"provider-missing-metadata"}};let l=re(t.title);i={entityType:c.outputEntityType,...l?{title:l}:{},from:{kind:"entity-attachment",...n},...o&&{replace:o},...c.targetField&&{targetEntityType:n.sourceEntityType,targetEntityId:n.sourceEntityId}}}return{kind:"ok",createInput:i,sourceAttachment:n}}async function Hc(e,t,r){let i=t.operation,n=D(r.userPermissionLevel),o=await Jc(e,i,n);if(o.kind==="error")return o;let{createInput:a,sourceAttachment:c}=o,l=i.kind==="attachment"&&i.replace===!0,u=te(e,a.entityType);if(u)return{kind:"error",result:u};let d=O(e,a.entityType,"create",r);if(d)return{kind:"error",result:d};let p=e.entityRegistry.getCreateInterceptor(a.entityType);if(!a.prompt&&!a.from)return{kind:"error",result:{success:!1,error:"Provide a generation source."}};if(a.from&&!p)return{kind:"error",result:{success:!1,error:`Entity type '${a.entityType}' does not support attachment-based generation. Use operation.kind prompt-from-source for AI-generated content based on referenced source material, or choose an entity type with an attachment provider.`,code:"unsupported-generation"}};if(!p&&!l){let g=a.prompt?Yt(ie(a.title??a.prompt),100):a.title?ie(a.title):void 0;if(g){if(await e.entityService.getEntity({entityType:a.entityType,id:g}))return{kind:"error",result:{success:!1,error:`A ${a.entityType} already exists for "${g}". To change its fields or status, use system_update; pass replace:true to generate a new copy intentionally.`}}}}return{kind:"ok",prepared:{createInput:a,operation:Gc(i,a,c),sourceAttachment:c,interceptor:p,eventContext:le(r)}}}function Gc(e,t,r){if(e.kind==="attachment"){let i=r??{sourceEntityType:e.source.entityType,sourceEntityId:e.source.entityId,attachmentType:e.attachmentType};return{kind:"attachment",source:{entityType:i.sourceEntityType,entityId:i.sourceEntityId},attachmentType:i.attachmentType,...t.title&&{title:t.title},...t.replace&&{replace:t.replace}}}if(e.kind==="cover-image")return{kind:"cover-image",target:{entityType:t.targetEntityType??e.target.entityType,entityId:t.targetEntityId??e.target.entityId},...t.title&&{title:t.title},prompt:e.prompt};if(e.kind==="standalone-image")return{kind:"standalone-image",...t.title&&{title:t.title},prompt:e.prompt};if(e.kind==="prompt-from-source")return{kind:"prompt-from-source",entityType:t.entityType,...t.title&&{title:t.title},source:{entityType:t.sourceEntityType??e.source.entityType,entityId:t.sourceEntityId??e.source.entityId},prompt:e.prompt};return{kind:"prompt",entityType:t.entityType,...t.title&&{title:t.title},prompt:e.prompt}}function Vn(e){let t=W({label:"generate",requestNoun:"generation"});return M("generate","Generate durable content or artifacts. Critical: for a request to generate a post/social-post/newsletter/etc. with a cover image, call only the prompt generation first; do not call standalone-image or cover-image until the target entity exists after confirmation. Critical: broad or underspecified topical generation uses operation.kind prompt and has no source field; preserve the user's wording as the prompt and do not stop to ask what details to highlight. Never invent source IDs, use brain-character/profile, uploads, filenames, guessed ids, or placeholders as source refs. Critical: when the user asks to generate from a source such as 'my latest blog post', resolve the source, then call operation.kind prompt-from-source in the same turn; for latest blog/published source requests, use system_list metadata to compare publishedAt and do not rely on semantic search order. If dated candidates such as publishedAt are visible, choose the newest candidate by publishedAt (not updated/created order) and do not stop with prose like 'I found it and can generate it' or 'if that is the one you mean.' Requires confirmation. Calling this tool without confirmed is how you request that confirmation; do not respond with separate prose such as 'I can generate it if you want' or 'I need to queue it first.' Use operation.kind prompt for broad non-image AI-generated entities with no source, including in the same turn after an optional search finds no source. Use operation.kind prompt-from-source only when generating from a resolved existing durable source entity, for example a newsletter from a resolved post: { kind: 'prompt-from-source', entityType: 'newsletter', source: { entityType: 'post', entityId: '...' }, prompt: '...' }. Use standalone-image only for unattached generated images, cover-image with operation.target only for generated covers on existing entities, and attachment with operation.source for source-derived artifacts such as carousel/printable PDFs or OG/social preview images. When a cover-image request for an existing entity resolves a clear target via search/get, call this tool in the same turn; do not stop after saying you found the entity. For regenerate/replace/refresh source-derived artifact requests, call attachment with replace:true immediately; do not say you can queue it later. When the user asks to create/write/draft/generate new durable content, call this tool without confirmed to request confirmation instead of asking for separate prose approval. If you first resolve a clear source entity for the requested generation, still call this tool in the same turn using prompt-from-source. Use system_create instead for saving/importing existing text, URLs, uploads, prior assistant responses, or raw uploaded file preservation with upload transform preserve. On the initial generation request, do not pass confirmed; the tool returns confirmation args.",Bn,async(r,i)=>{let n=await Hc(e,r,i);if(n.kind==="error")return n.result;let{createInput:o}=n.prepared,{operation:a,interceptor:c,eventContext:l}=n.prepared;if(r.confirmed){let u=t.validateConfirmed(r.confirmationToken,r);if(u)return u}else{let u=_c(o),d=t.buildArgs((p)=>({operation:a,confirmed:!0,confirmationToken:p}));return{needsConfirmation:!0,toolName:"system_generate",summary:u.summary,preview:u.preview,args:d}}if(c){let u=await et(e,c,o,i);if(u.kind==="handled"||u.kind==="error")return u.result;o=u.createInput}if(!o.prompt)return{success:!1,error:"Attachment generation is supported only for entity types that explicitly handle source-derived artifacts."};return qc(e,o,o.prompt,l,i)},{visibility:"trusted",sideEffects:"writes"})}function Xn(e){let{entityService:t,entityRegistry:r,logger:i}=e,n=W({label:"delete",requestNoun:"deletion"});return M("delete","Request entity deletion by id. Unauthorized callers get a permission error; authorized callers get confirmation first. Do not pass confirmed on the initial request.",Wn,async(o,a)=>{if((a.userPermissionLevel??"public")==="public")return{success:!1,error:"Changing content requires higher permission; current permission is Public."};let c=O(e,o.entityType,"delete",a);if(c)return c;let l=te(e,o.entityType);if(l)return l;if(r.getAdapter(o.entityType).isSingleton===!0)return{success:!1,error:`${o.entityType} is a singleton entity and cannot be deleted through system tools. Update it instead.`};let u=D(a.userPermissionLevel),d=await L(t,o.entityType,o.id,i,void 0,u);if(!d.ok)return{success:!1,error:d.error};let{entity:p}=d;if(o.confirmed){let m=n.validateConfirmed(o.confirmationToken,o);if(m)return m;try{await t.deleteEntity({entityType:o.entityType,id:p.id})}catch(h){return{success:!1,error:C(h,"Failed to delete entity")}}return{success:!0,data:{deleted:p.id}}}let g=tt(p),f=n.buildArgs((m)=>({...o,id:p.id,confirmed:!0,confirmationToken:m}));return{needsConfirmation:!0,toolName:"system_delete",summary:`Delete "${g}"?`,preview:p.content.slice(0,200),args:f}},{visibility:"admin",sideEffects:"writes"})}function eo(e,t){let r=t.map(({oldText:o,newText:a},c)=>{let l=e.indexOf(o);if(!o||l<0)throw Error(`Edit ${c+1}: oldText was not found. Fetch the entity again and provide exact text.`);if(e.indexOf(o,l+1)!==-1)throw Error(`Edit ${c+1}: oldText is ambiguous. Include more surrounding text to match exactly once.`);return{start:l,end:l+o.length,newText:a}}).sort((o,a)=>o.start-a.start),i=0,n=[];for(let o of r){if(o.start<i)throw Error("Edits overlap in the original content. Provide non-overlapping replacements.");n.push(e.slice(i,o.start),o.newText),i=o.end}return n.push(e.slice(i)),n.join("")}import{isDeepStrictEqual as Po}from"util";class nt{diff(e,t,r={}){let i;if(typeof r==="function")i=r,r={};else if("callback"in r)i=r.callback;let n=this.castInput(e,r),o=this.castInput(t,r),a=this.removeEmpty(this.tokenize(n,r)),c=this.removeEmpty(this.tokenize(o,r));return this.diffWithOptionsObj(a,c,r,i)}diffWithOptionsObj(e,t,r,i){var n;let o=(v)=>{if(v=this.postProcess(v,r),i){setTimeout(function(){i(v)},0);return}else return v},a=t.length,c=e.length,l=1,u=a+c;if(r.maxEditLength!=null)u=Math.min(u,r.maxEditLength);let d=(n=r.timeout)!==null&&n!==void 0?n:1/0,p=Date.now()+d,g=[{oldPos:-1,lastComponent:void 0}],f=this.extractCommon(g[0],t,e,0,r);if(g[0].oldPos+1>=c&&f+1>=a)return o(this.buildValues(g[0].lastComponent,t,e));let m=-1/0,h=1/0,w=()=>{for(let v=Math.max(m,-l);v<=Math.min(h,l);v+=2){let S,b=g[v-1],I=g[v+1];if(b)g[v-1]=void 0;let P=!1;if(I){let Ie=I.oldPos-v;P=I&&0<=Ie&&Ie<a}let U=b&&b.oldPos+1<c;if(!P&&!U){g[v]=void 0;continue}if(!U||P&&b.oldPos<I.oldPos)S=this.addToPath(I,!0,!1,0,r);else S=this.addToPath(b,!1,!0,1,r);if(f=this.extractCommon(S,t,e,v,r),S.oldPos+1>=c&&f+1>=a)return o(this.buildValues(S.lastComponent,t,e))||!0;else{if(g[v]=S,S.oldPos+1>=c)h=Math.min(h,v-1);if(f+1>=a)m=Math.max(m,v+1)}}l++};if(i)(function v(){setTimeout(function(){if(l>u||Date.now()>p)return i(void 0);if(!w())v()},0)})();else while(l<=u&&Date.now()<=p){let v=w();if(v)return v}}addToPath(e,t,r,i,n){let o=e.lastComponent;if(o&&!n.oneChangePerToken&&o.added===t&&o.removed===r)return{oldPos:e.oldPos+i,lastComponent:{count:o.count+1,added:t,removed:r,previousComponent:o.previousComponent}};else return{oldPos:e.oldPos+i,lastComponent:{count:1,added:t,removed:r,previousComponent:o}}}extractCommon(e,t,r,i,n){let o=t.length,a=r.length,c=e.oldPos,l=c-i,u=0;while(l+1<o&&c+1<a&&this.equals(r[c+1],t[l+1],n))if(l++,c++,u++,n.oneChangePerToken)e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1};if(u&&!n.oneChangePerToken)e.lastComponent={count:u,previousComponent:e.lastComponent,added:!1,removed:!1};return e.oldPos=c,l}equals(e,t,r){if(r.comparator)return r.comparator(e,t);else return e===t||!!r.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){let t=[];for(let r=0;r<e.length;r++)if(e[r])t.push(e[r]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join("")}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,r){let i=[],n;while(e)i.push(e),n=e.previousComponent,delete e.previousComponent,e=n;i.reverse();let o=i.length,a=0,c=0,l=0;for(;a<o;a++){let u=i[a];if(!u.removed){if(!u.added&&this.useLongestToken){let d=t.slice(c,c+u.count);d=d.map(function(p,g){let f=r[l+g];return f.length>p.length?f:p}),u.value=this.join(d)}else u.value=this.join(t.slice(c,c+u.count));if(c+=u.count,!u.added)l+=u.count}else u.value=this.join(r.slice(l,l+u.count)),l+=u.count}return i}}class to extends nt{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}}var ro=new to;function Vt(e,t,r){return ro.diff(e,t,r)}var ot=s.enum(["png","jpg","jpeg","webp","gif","svg"]),no=s.enum(["pending","draft","failed"]),oo=s.object({title:s.string().optional(),alt:s.string().optional(),format:ot,width:s.number(),height:s.number(),status:no.optional(),processingJobId:s.string().optional(),processingError:s.string().optional(),sourceUrl:s.url().optional(),sourceEntityType:s.string().optional(),sourceEntityId:s.string().optional(),sourceUploadId:s.string().optional(),sourceFilename:s.string().optional(),sourceMediaType:s.string().optional(),attachmentType:s.string().optional(),dedupKey:s.string().optional()}),ve=io.extend({entityType:s.literal("image"),metadata:oo}),Qc=s.object({url:s.string(),alt:s.string(),title:s.string(),width:s.number(),height:s.number()});function so(e){return/^https?:\/\//i.test(e)}async function ao(e,t){let r=await fetch(e);if(!r.ok)throw Error(`Failed to fetch: ${r.status} ${r.statusText}`);let i=r.headers.get("content-type");if(t&&!i?.startsWith(t))throw Error(`URL does not point to expected content type: ${i}`);let n=await r.arrayBuffer(),o=Buffer.from(n).toString("base64");return`data:${i?.split(";")[0]??"application/octet-stream"};base64,${o}`}function lo(e){let t=e.trim().match(/^data:image\/([a-z+]+);base64,(.+)$/i);if(!t?.[1]||!t[2])return null;return{format:t[1].toLowerCase(),base64:t[2]}}function st(e){let t=lo(e);if(!t)throw Error("Invalid image data URL");return t}function Kc(e,t){return`data:image/${t==="jpg"?"jpeg":t};base64,${e}`}var Yc={png:"iVBORw",jpg:"/9j/",gif:"R0lGOD",webp:"UklGR"};function Xt(e){for(let[t,r]of co(Yc))if(e.startsWith(r))return t;return null}function uo(e){let t=e.toLowerCase(),r=t==="svg+xml"?"svg":t,i=ot.safeParse(r);return i.success?i.data:null}async function Vc(e){return ao(e,"image/")}function at(e){let t=Buffer.from(e,"base64");if(t[0]===137&&t[1]===80&&t[2]===78&&t[3]===71){let r=t.readUInt32BE(16),i=t.readUInt32BE(20);return{width:r,height:i}}if(t[0]===255&&t[1]===216){let r=2;while(r<t.length-8){if(t[r]!==255){r++;continue}let i=t[r+1];if(i===192||i===194){let o=t.readUInt16BE(r+5);return{width:t.readUInt16BE(r+7),height:o}}let n=t.readUInt16BE(r+2);r+=2+n}}if(t[0]===71&&t[1]===73&&t[2]===70){let r=t.readUInt16LE(6),i=t.readUInt16LE(8);return{width:r,height:i}}if(t.length>=30&&t[0]===82&&t[1]===73&&t[2]===70&&t[3]===70){if(t[12]===86&&t[13]===80&&t[14]===56){if(t[15]===32){let r=t[26]??0,i=t[27]??0,n=t[28]??0,o=t[29]??0,a=(r|i<<8)&16383,c=(n|o<<8)&16383;return{width:a,height:c}}if(t[15]===76&&t.length>=25){let r=t.readUInt32LE(21),i=(r&16383)+1,n=(r>>14&16383)+1;return{width:i,height:n}}}}return null}function po(e){let t=uo(e);if(!t)throw Error(`Unsupported image format: ${e}`);return t}class er{entityType="image";purpose="Image assets such as generated covers, social previews, and uploaded images.";schema=ve;toMarkdown(e){return e.content}fromMarkdown(e){let{format:t,base64:r}=st(e),i=at(r);return{entityType:"image",content:e,metadata:{format:po(t),width:i?.width??0,height:i?.height??0}}}extractMetadata(e){return e.metadata}parseFrontMatter(e,t){return t.parse({})}generateFrontMatter(e){return""}getBodyTemplate(){return""}createImageEntity(e){let{dataUrl:t,title:r,alt:i}=e,{format:n,base64:o}=st(t),a=at(o),l=Xt(o)??po(n);return{entityType:"image",content:t,metadata:{title:r,alt:i??r,format:l,width:a?.width??0,height:a?.height??0,...e.status&&{status:e.status},...e.sourceUrl&&{sourceUrl:e.sourceUrl},...e.sourceEntityType&&{sourceEntityType:e.sourceEntityType},...e.sourceEntityId&&{sourceEntityId:e.sourceEntityId},...e.sourceUploadId&&{sourceUploadId:e.sourceUploadId},...e.sourceFilename&&{sourceFilename:e.sourceFilename},...e.sourceMediaType&&{sourceMediaType:e.sourceMediaType},...e.attachmentType&&{attachmentType:e.attachmentType},...e.dedupKey&&{dedupKey:e.dedupKey}}}}}var Xc=new er;function Qg(e){return go(e,{skipInvalid:!0,noRefs:!0,sortKeys:!0})}function fo(e){return mo(e)}var el=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,tl=s.record(s.string(),s.unknown());async function ho(e,t){let r=await t.getEntity({entityType:"image",id:e},ve);if(!r)return;return{url:r.content,alt:r.metadata.alt??"",title:r.metadata.title??"",width:r.metadata.width,height:r.metadata.height}}function yo(e,t){let r=el.exec(e.content);if(!r?.[1])return;try{let i=tl.safeParse(fo(r[1]));if(i.success){let n=i.data[t];return typeof n==="string"?n:void 0}}catch{return}return}function vo(e){return yo(e,"coverImageId")}function rl(e){return yo(e,"ogImageId")}function tr(e,t){return{...e,content:be(e.content,"coverImageId",t)}}function rr(e,t){return{...e,content:be(e.content,"ogImageId",t)}}async function il(e,t){let r=vo(e);if(!r)return;return ho(r,t)}var ir=bo();function nl(e,t){let r=ir.parse(e),i=new Map;ct(r,"definition",(o)=>{if(!i.has(o.identifier))i.set(o.identifier,o)});let n=new Set;return ct(r,(o,a,c)=>{if(o.type!=="image"&&o.type!=="imageReference")return;let l=o.type==="image"?o:i.get(o.identifier);if(!l)return;let u=t(l.url);if(u===l.url)return;if(n.add(l.url),o.type==="image")o.url=u;else if(c&&a!==void 0)c.children[a]={type:"image",url:u,alt:o.alt,title:l.title}}),n.size>0?ir.stringify(r):e}function ol(e){let t=[],r=ir.parse(e);return ct(r,"image",(i)=>{t.push({url:i.url,alt:i.alt??"",title:i.title??void 0})}),t}var lt=/^---\r?\n(?:[\s\S]*?\r?\n)?---[ \t]*(?:\r?\n|$)/;function So(e){return e.replace(lt,"")}var Ro=400;function ut(e,t,r){if(r===null)return!Object.hasOwn(e,t);return Object.hasOwn(e,t)&&Po(e[t],r)}function or(e,t){return new Set([...t.getFrontmatterExtensions(e).flatMap((r)=>Object.keys(r.shape)),...t.getGroupings().filter((r)=>r.types.includes(e)).map((r)=>r.field)])}function sl(e,t,r){if(r.has(t))return nr(e.content).frontmatter[t];return t==="visibility"?e.visibility:e.metadata[t]}function Co(e,t,r){let{visibility:i,coverImageId:n,ogImageId:o,...a}=t,c=i===void 0?e.visibility:Io.parse(i),l=Object.hasOwn(t,"coverImageId")?tr(e,typeof n==="string"?n:null):e,u=Object.hasOwn(t,"ogImageId")?rr(l,typeof o==="string"?o:null):l,d={...e.metadata};for(let[m,h]of Object.entries(a))if(h===null)delete d[m];else d[m]=h;let p={...u,visibility:c,metadata:d};for(let[m,h]of Object.entries(a))if(h===null)delete p[m];else p[m]=h;let g=or(e.entityType,r),f=!1;for(let[m,h]of Object.entries(t)){if(!g.has(m))continue;p.content=be(p.content,m,h),f=!0}if(f)p.metadata=r.projectMetadata(e.entityType,p.content,d);return p}function al(e,t,r){let i=r.getAdapter(e.entityType),n=i.fromMarkdown(e.content),o=i.fromMarkdown(t),a={...e.metadata};for(let c of new Set([...Object.keys(n.metadata??{}),...Object.keys(o.metadata??{})])){let l=o.metadata?.[c];if(Po(n.metadata?.[c],l))continue;if(l===void 0)delete a[c];else a[c]=l}return{...e,...o,id:e.id,entityType:e.entityType,created:e.created,updated:e.updated,contentHash:e.contentHash,content:t,metadata:a,visibility:it(t)??e.visibility}}var cl=new Set(["visibility","coverImageId","ogImageId"]),ll=s.record(s.string(),s.unknown());function ul(e,t,r,i){if(t.kind!=="fields")return;let n=t.fields,o=r.getEffectiveFrontmatterSchema(e.entityType);if(!o)return;let a=or(e.entityType,r),c=Object.keys(n).filter((m)=>a.has(m)),l;try{if(l=Co(e,n,r),c.length>0){let m=r.validateEntity(e.entityType,l),h=i.serializeEntity(m),w=nr(h).frontmatter,v=i.deserializeEntity(h,e.entityType).metadata??{};for(let S of c){let b=n[S];if(!ut(w,S,b)||!ut(v,S,b))return{success:!1,error:`The requested ${S} value would not survive frontmatter persistence.`}}}}catch(m){return{success:!1,error:C(m,"Invalid field update")}}let u=Object.keys(n).filter((m)=>!a.has(m)&&!cl.has(m)&&(m in o.shape));if(u.length===0)return;let d=r.getAdapter(e.entityType),p;try{l=r.validateEntity(e.entityType,l),p=d.extractMetadata(l)}catch{return}let g=[],f=[];for(let m of u){let h=n[m];if(Object.hasOwn(p,m)){if(!ut(p,m,h))g.push(m)}else if(h!==null||!Object.hasOwn(e.metadata,m))f.push(m)}if(f.length>0){let m;try{m=d.parseFrontMatter(d.toMarkdown(l),ll)}catch{if(g.length===0)return}if(m){for(let h of f)if(!ut(m,h,n[h]))g.push(h)}}if(g.length===0)return;return{success:!1,error:`${e.entityType} does not persist ${g.join(", ")} through 'fields'. The update would report success without changing anything. Provide full markdown with frontmatter via 'content' instead.`}}function To(e,t,r){let i=lt.exec(e.content)?.[0];if(i===void 0||!t.trim()||lt.test(t))return t;if(r.getAdapter(e.entityType).hasBody===!1)return{success:!1,error:`${e.entityType} has no body. Replace its full markdown, including frontmatter.`};return i+t}function dl(e,t,r){if(t.kind!=="content")return;let i=t.content.trim(),n=r.getEffectiveFrontmatterSchema(e);if(!n)return;if(!i)return{success:!1,error:"Full content replacement cannot be empty for this entity type. Use 'fields' for partial updates."};try{r.getAdapter(e).parseFrontMatter(t.content,n)}catch{return{success:!1,error:"Invalid content replacement for this entity type. Provide full markdown with valid frontmatter, or use 'fields' for partial updates."}}return}function pl(e,t,r){if(t.kind!=="fields"||!("coverImageId"in t.fields))return;let i=t.fields.coverImageId;if(i!==null&&i!==void 0&&typeof i!=="string")return{success:!1,error:"coverImageId must be a string or null"};if(i==="__PENDING__"||typeof i==="string"&&i.startsWith("upload-"))return{success:!1,error:"coverImageId must reference an existing image id or be null"};if(r.getAdapter(e).supportsCoverImage)return;return{success:!1,error:`Entity type '${e}' doesn't support cover images`}}function ml(e,t,r){if(t.kind==="fields"&&"status"in t.fields)return t.fields.status;if(t.kind==="content"){let i=r.getEffectiveFrontmatterSchema(e.entityType);if(!i)return e.metadata.status;try{return r.getAdapter(e.entityType).parseFrontMatter(t.content,i).status}catch{return e.metadata.status}}return e.metadata.status}function ko(e,t,r){let i=or(e.entityType,r);if(t.kind==="fields")return Object.entries(t.fields).map(([c,l])=>{let u=sl(e,c,i);if(!i.has(c))return`${c}: ${String(u??"(empty)")} \u2192 ${String(l)}`;let d=r.getEffectiveFrontmatterSchema(e.entityType)?.shape[c],p=d!==void 0&&s.safeParse(d,u).success,g=u===void 0?"(absent)":`${JSON.stringify(u)}${p?"":" (invalid existing value)"}`,f=l===null?"(removed)":JSON.stringify(l);return`${c}: ${g} \u2192 ${f}`}).join(`
|
|
14
14
|
`);let n=e.content.split(`
|
|
15
15
|
`),o=t.content.split(`
|
|
16
16
|
`),a=Vt(n,o,{maxEditLength:Ro});if(!a)return`Full content replacement (line diff omitted: more than ${Ro} changed lines).`;return a.filter((c)=>c.added||c.removed).flatMap((c)=>c.value.map((l)=>`${c.added?"+":"-"} ${l}`)).join(`
|
|
17
17
|
`)}function Eo(e,t,r,i){return ul(e,t,r,i)??dl(e.entityType,t,r)??pl(e.entityType,t,r)}function xo(e,t,r){return wo(e.entityType,e.metadata.status,ml(e,t,r),r)==="non-publish"?"update":"publish"}function jo(e,t,r){return t.kind==="content"?al(e,t.content,r):Co(e,t.fields,r)}function Se(e){return{success:!1,error:e}}async function gl(e,t,r,i){if(t.confirmed&&t.contentHash&&r.contentHash!==t.contentHash)return Se("Entity was modified since you reviewed the changes. Please try again.");let n=t.operation;switch(n.kind){case"fields":return{operation:n};case"edits":return{operation:{kind:"content",content:eo(r.content,n.edits)}};case"content":return Ao(e,r,n.content);case"source":{let o=await Ve(e,n.source,i);if(!o.success)return o;return Ao(e,r,o.content,Xe(n.source,o))}}}function Ao(e,t,r,i){let n=To(t,r,e.entityRegistry);if(typeof n!=="string")return n;return{operation:{kind:"content",content:n},...i?{source:i}:{}}}function Do(e){let{entityService:t,logger:r,entityRegistry:i}=e,n=W({label:"update",requestNoun:"the update"}),o=async(c,l,u,d)=>{let p=n.validateConfirmed(c.confirmationToken,c);if(p)return p;let g=jo(l,u,i);if(g.visibility!==l.visibility&&!rt(d.userPermissionLevel,g.visibility))return Se(`Cannot set entity visibility to "${g.visibility}" \u2014 caller permission "${d.userPermissionLevel??"public"}" is not allowed to write at that level.`);try{let f=le(d);if((await t.updateEntity({entity:g,options:{expectedContentHash:l.contentHash,...f?{eventContext:f}:{}}})).skipReason==="content-conflict")return Se("Entity was modified before the update could be saved. Please request and confirm the update again.")}catch(f){return Se(C(f,"Failed to update entity"))}return{success:!0,data:{updated:l.id}}},a=(c,l,{operation:u,source:d})=>({needsConfirmation:!0,toolName:"system_update",summary:`Update "${tt(l)}"?`,completionSummary:`Updated ${Hn(l.entityType)}.`,preview:ko(l,u,i),args:n.buildArgs((p)=>({...c,...d?{operation:{kind:"source",source:d}}:{},id:l.id,confirmed:!0,confirmationToken:p,contentHash:l.contentHash}))});return M("update","Update an entity with exactly one typed operation: fields for partial frontmatter/metadata changes, content for full replacement text you wrote, edits for exact text patches, or source for replacement text the user supplied. For small content changes, fetch the entity and use the edits operation with exact oldText/newText pairs instead of regenerating the whole document. For a large rewrite whose text the user supplied, use the source operation with exact user-message boundaries instead of copying it into content. 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 the fields operation setting coverImageId to the image ID; do not stop after lookup.",_n,async(c,l)=>{let u=await L(t,c.entityType,c.id,r,void 0,D(l.userPermissionLevel));if(!u.ok)return Se(u.error);let{entity:d}=u,p=await gl(e,c,d,l);if("success"in p)return p;let{operation:g}=p,f=Eo(d,g,i,t);if(f)return f;let m=O(e,c.entityType,xo(d,g,i),l);if(m)return m;return c.confirmed?o(c,d,g,l):a(c,d,p)},{visibility:"trusted",sideEffects:"writes"})}function zo(e){return[Kn(e),Vn(e),Xn(e),Do(e)]}function dt(e){if(e.interfaceType!==Oo)return;if(e.userPermissionLevel!=="public"||e.isAnchor)throw Error("Guest execution denied")}var fl=0.5,sr=(e)=>e==="public"?{publishedOnly:!0}:{};function hl(e,t){if(e.length===0)return;let r=Math.round(Math.max(...e.map((i)=>i.score))*100)/100;return{minScore:t,weakerMatches:e.length,bestScore:r,hint:`No result reached minScore ${t}, but ${e.length} weaker match${e.length===1?"":"es"} exist (best score ${r}). Broad or abstract questions match content weakly: search again with a lower minScore, such as 0.3, before concluding that nothing relevant exists.`}}function Mo(e){let{entityService:t,logger:r}=e;return[G("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.",Mn,async(i,n)=>{dt(n);let o=D(n.userPermissionLevel),a=i.minScore??fl,c=await t.search({query:i.query,options:{limit:i.limit??e.searchLimit,...i.scope.kind==="type"&&{types:[i.scope.entityType]},...i.includeUngenerated!==void 0&&{includeUngenerated:i.includeUngenerated},visibilityScope:o,...sr(o)}}),l=c.filter((d)=>d.score>=a),u=l.length===0?hl(c,a):void 0;return{success:!0,data:{results:l.map((d)=>{let p=Kt(d.entity,e.entityRegistry);return{...d,entity:p,...p!==d.entity?{excerpt:p.content}:{}}}),...u&&{belowThreshold:u}}}},{visibility:"public",sideEffects:"none",cli:{name:"search"}}),G("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.",Ln,async(i,n)=>{if(dt(n),!t.getEntityTypes().includes(i.entityType))return{success:!1,error:`Unknown entity type: ${i.entityType}. Available: ${t.getEntityTypes().join(", ")}`};let o=D(n.userPermissionLevel),a=await L(t,i.entityType,i.id,r,void 0,o,sr(o));if(!a.ok)return{success:!1,error:a.error};let c=Kt(a.entity,e.entityRegistry);return{success:!0,data:{entity:i.part==="body"?{...c,content:So(c.content)}:c}}},{visibility:"public",sideEffects:"none",cli:{name:"get"}}),G("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.",Un,async(i,n)=>{if(dt(n),!t.getEntityTypes().includes(i.entityType))return{success:!1,error:`Unknown entity type: ${i.entityType}. Available: ${t.getEntityTypes().join(", ")}`};let o=D(n.userPermissionLevel),a={visibilityScope:o};if(i.status&&i.status!=="any")a.metadata={status:i.status};let{defaultSort:c}=e.entityRegistry.getEntityTypeConfig(i.entityType),u=(await t.listEntities({entityType:i.entityType,options:{limit:i.limit??20,filter:a,...sr(o),...c?{sortFields:c}:{}}})).map(({content:d,contentHash:p,...g})=>g);return{success:!0,data:{entities:u,count:u.length}}},{visibility:"public",sideEffects:"none",cli:{name:"list"}})]}function yl(e){let t=Object.fromEntries(Object.entries(e.params.shape).map(([r,i])=>{let n=i instanceof s.ZodDefault?i.unwrap():i,o=i.description?n.describe(i.description):n;return[r,o.optional()]}));return s.looseObject(t).describe(`Params for ${e.type}: ${e.description}`)}function vl(e){let[t,...r]=e.map((o)=>o.type);if(t===void 0)throw Error("No analytics reports registered");let i=e.filter((o)=>Object.keys(o.params.shape).length>0).map(yl),n=s.union([...i,s.looseObject({})]);return s.object({type:s.enum([t,...r]).describe("The report to run"),params:n.optional().describe("The report's params; each report lists its own")})}function Lo(e){let{entityService:t,analytics:r}=e,i=r.getDefinitions(),n=i.map((o)=>`${o.type} (${o.description})`).join("; ");return[G("system","analytics",`Aggregate metrics and reports over the brain, not its content: for actual content use system_list, system_get or system_search. Reports: ${n}.`,vl(i),async(o,a)=>({success:!0,data:await r.run({type:o.type,params:o.params,entityService:t,permission:a.userPermissionLevel??"public"})}),{visibility:"public",sideEffects:"none"})]}function Uo(e){let{jobs:t}=e;return[M("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.",Nn,async(r)=>{if(r.batchId){let o=await t.getBatchStatus(r.batchId);if(!o)return{success:!1,error:`No batch found with ID: ${r.batchId}`};let a=o.totalOperations>0?Math.round(o.completedOperations/o.totalOperations*100):0;return{success:!0,data:{batchId:r.batchId,status:o.status,progress:{total:o.totalOperations,completed:o.completedOperations,failed:o.failedOperations,percentComplete:a},currentOperation:o.currentOperation,errors:o.errors}}}let i=await t.getActiveJobs(r.jobTypes),n=await t.getActiveBatches();return{success:!0,data:{summary:{activeJobs:i.length,activeBatches:n.length},jobs:i.map((o)=>({id:o.id,type:o.type,status:o.status,priority:o.priority,retryCount:o.retryCount,createdAt:new Date(o.createdAt).toISOString(),startedAt:o.startedAt?new Date(o.startedAt).toISOString():null})),batches:n.map((o)=>({batchId:o.batchId,status:o.status.status,totalOperations:o.status.totalOperations,completedOperations:o.status.completedOperations,failedOperations:o.status.failedOperations,currentOperation:o.status.currentOperation,pluginId:o.metadata.metadata.pluginId,errors:o.status.errors}))}}},{visibility:"public",sideEffects:"none"})]}function bl(e,t){let{entityCounts:r,daemons:i,endpoints:n,interactions:o,...a}=e;return{...a,endpoints:n.filter((c)=>t(c.visibility)).sort((c,l)=>c.priority-l.priority).map(({label:c,url:l})=>({label:c,url:l}))}}function Zo(e){return[G("system","status","Get system status including model, version, background work, and the web surfaces (such as the dashboard and Studio) the caller can open, with their paths",s.object({}),async(t,r)=>({success:!0,data:bl(await e.getAppInfo(),(i)=>e.permissionService.hasPermission(r.userPermissionLevel??"public",i))}),{visibility:"public",sideEffects:"none",cli:{name:"status"}})]}function $o(e){return[...Mo(e),...Uo(e),...Zo(e),...zo(e),...Lo(e)]}function Bo(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(`
|
|
18
18
|
`)}]})},{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 _o(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((i)=>({uri:`entity://${i}`,name:`${i} entities`})),complete:{type:async()=>t.getEntityTypes()},handler:async({type:r})=>{let i=t.getEntityTypes();if(!i.includes(r))throw Error(`Unknown entity type: ${r}. Available: ${i.join(", ")}`);let o=(await t.listEntities({entityType:r})).map((a)=>({id:a.id,entityType:a.entityType,...a.metadata,updated:a.updated}));return{contents:[{uri:`entity://${r}`,mimeType:"application/json",text:JSON.stringify(o,null,2)}]}}},{name:"entity-detail",uriTemplate:"entity://{type}/{id}",description:"Read a single entity by type and ID",mimeType:"text/markdown",complete:{type:async(r)=>{let i=t.getEntityTypes();return r?i.filter((n)=>n.startsWith(r)):i},id:async()=>[]},handler:async({type:r,id:i})=>{let n=await t.getEntity({entityType:r,id:i});if(!n)throw Error(`Entity not found: ${r}/${i}`);return{contents:[{uri:`entity://${r}/${i}`,mimeType:"text/markdown",text:n.content}]}}}]}function Wo(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:r,type:i})=>({messages:[{role:"user",content:{type:"text",text:r?`Create a new ${i} about: ${r}`:`Create a new ${i}. 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:r,topic:i})=>({messages:[{role:"user",content:{type:"text",text:`Generate a ${r} about: ${i}`}}]})},{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:r,id:i})=>({messages:[{role:"user",content:{type:"text",text:`Review my ${r} "${i}". 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:r,id:i})=>({messages:[{role:"user",content:{type:"text",text:`I want to publish my ${r} "${i}". 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:r})=>({messages:[{role:"user",content:{type:"text",text:`Let's brainstorm about: ${r}. Use my existing content and expertise as context. Give me fresh angles and concrete ideas.`}}]})}]}function No(e){let t=e.entityService.getEntityTypes(),r=t.map((i)=>`- ${i}: ${e.entityRegistry.getAdapter(i).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. Required `operation` union: `{ kind: "fields", fields }`, `{ kind: "content", content }`, `{ kind: "edits", edits }`, or `{ kind: "source", source }`. Use `operation.kind: "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. Never replace unchanged content with placeholders or ellipses. For a whole-document rewrite, when the user supplies the replacement text, use `operation: { kind: "source", 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 a content operation or long edits. Use the content operation 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 `operation.kind: "fields"` for title, status, coverImageId, ogImageId, and other frontmatter/metadata changes. To remove or clear a cover image, set `operation.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:",...r].join(`
|
|
19
|
-
`)}var ue="system",Sl=s.object({toolName:s.string(),args:s.unknown(),...qo.partial().shape});function pt(e,t,r,i,n){for(let o of e)try{t(o)}catch{n.debug(`System ${i} ${r(o)} already registered, skipping`)}}function Jo(e,t,r,i){let n=$o(e);pt(n,(d)=>t.registerTool(ue,d),(d)=>d.name,"tool",i);let o=r.subscribe(Fo.toolExecute(ue),async(d)=>{let p=Sl.safeParse(d.payload);if(!p.success)return{success:!1,error:"Invalid system tool execute payload"};let{toolName:g,args:f,interfaceType:m,actor:h,conversationId:w,channelId:v,userPermissionLevel:S}=p.data,b=n.find((U)=>U.name===g);if(!b)return{success:!1,error:`System tool not found: ${g}`};let I={interfaceType:m??"system",actor:h??{kind:"service",serviceId:"system"}};if(w)I.conversationId=w;if(v)I.channelId=v;if(S)I.userPermissionLevel=S;return{success:!0,data:await b.handler(f,I)}});i.debug(`Registered ${n.length} system tools`);let a=Bo(e);pt(a,(d)=>t.registerResource(ue,d),(d)=>d.uri,"resource",i),i.debug(`Registered ${a.length} system resources`);let c=_o(e);pt(c,(d)=>t.registerResourceTemplate(ue,d),(d)=>d.uriTemplate,"resource template",i),i.debug(`Registered ${c.length} system resource templates`);let l=Wo(e);pt(l,(d)=>t.registerPrompt(ue,d),(d)=>d.name,"prompt",i),i.debug(`Registered ${l.length} system prompts`);let u=No(e);try{t.registerInstructions(ue,u)}catch{i.debug("System instructions already registered, skipping")}return i.debug("Registered system instructions"),o}function Ko(e){let{services:t,jobs:r,analytics:i,query:n,getAppInfo:o}=e,a=t.jobQueueService,c=t.logger.child("system"),l=Jo({entityService:t.entityService,entityRegistry:t.entityRegistry,jobs:{...r,enqueue:Ho(a,"system",!1),enqueueBatch:Go(r,"system"),registerHandler:Qo(a,"system")},conversationService:t.conversationService,runtimeUploads:t.runtimeUploadRegistry,attachments:mt(t.attachmentRegistry),logger:c,query:n,getIdentity:()=>t.identityService.getCharacter(),getProfile:()=>t.profileService.getProfile(),getAppInfo:o,searchLimit:10,analytics:i,permissionService:t.permissionService},t.mcpService,t.messageBus,c);t.disposables.push(l)}class ar{scope;closePromise=null;closed=!1;constructor(){this.scope=y.runSync(k.make())}buildLayer(e){this.assertOpen();let t=y.runSyncExit(_.buildWithScope(e,this.scope));if(E.isFailure(t))throw q.squash(t.cause);return t.value}addFinalizer(e){this.assertOpen(),y.runSync(k.addFinalizer(this.scope,y.promise(async()=>{await e()})))}addSyncFinalizer(e){this.assertOpen(),y.runSync(k.addFinalizer(this.scope,y.sync(()=>{e()})))}async fork(e){if(this.closed)throw Error("Cannot start background work after shell shutdown");await y.runPromise(y.forkIn(e,this.scope))}close(e=E.void){if(this.closePromise)return this.closePromise;if(this.closed)return Promise.resolve();return this.closed=!0,this.closePromise=y.runPromise(k.close(this.scope,e)),this.closePromise}closeSync(e){if(this.closed)return;this.closed=!0,y.runSync(k.close(this.scope,e))}assertOpen(){if(this.closed)throw Error("Cannot register cleanup after shell shutdown")}}class Re{config;services;lifecycle;bootloader;initialized=!1;lifecycleState="constructed";bootMode;bootPromise=null;shutdownPromise=null;analyticsRegistry;bootTime=Date.now();endpointRegistry=new Jt;interactionRegistry=new Ht;httpRouteRegistry=Ke.createFresh();jobs;static createFresh(e,t,r){return new Re(ke(e),t,r)}constructor(e,t,r){this.config=e,this.lifecycle=new ar,es(this,()=>this.httpRouteRegistry.getSnapshot());let i=t?.logger??z.getInstance(),n=Je.createFresh(i,this.config,r?.processRole,r?.peerChannel);try{this.services=n.initializeServices(this.lifecycle,t),this.jobs=En(this.services.batchJobManager,this.services.jobQueueService),this.analyticsRegistry=wn(this.services.entityRegistry),this.bootloader=new Ft(this.config,this.services,this.lifecycle,n,r?.processRole,{registerCoreDataSources:()=>wr(this.services,this.config),finalizeHttpRoutes:()=>{this.httpRouteRegistry.finalize(An(this.services.pluginManager))},registerSystemCapabilities:()=>Ko({services:this.services,jobs:this.jobs,analytics:this.analyticsRegistry,query:(o,a)=>this.query(o,a),getAppInfo:()=>this.getAppInfo()}),createProjectionInputContext:()=>({entities:this.services.entityService,resolvePrompt:(o,a)=>Ee(this.services.entityService,o,a),appInfo:()=>this.getAppInfo(),identityInput:()=>{let o=this.getIdentity(),a=this.getProfile();return Vo.parse({brainName:o.name,role:o.role,purpose:o.purpose,values:o.values,profileName:a.name,...a.description!==void 0?{profileDescription:a.description}:{},...a.organization!==void 0?{profileOrganization:a.organization}:{}})}}),createProjectionExecutionContext:()=>({ai:Xo(this),logger:this.services.logger.child("ProjectionRuntime")}),...t?.projectionRuntime&&{projectionRuntime:t.projectionRuntime}}),n.wireShell(this.services,this),zn(this.lifecycle,this.services)}catch(o){try{this.lifecycle.closeSync(E.fail(o))}catch(a){i.error("Failed to roll back Shell service construction",a)}throw o}}getAnalyticsRegistry(){return this.analyticsRegistry}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:B.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(E.fail(t))}catch(r){this.services.logger.error("Failed to clean up Shell after initialization failure",r)}throw t}}registerTemplates(e,t){this.services.logger.debug("Registering templates",{pluginId:t,count:Object.keys(e).length});for(let[r,i]of Object.entries(e))this.registerTemplate(r,i,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,t){return this.requireInitialized("Shell content generation"),Pr(this.services,e,t)}async query(e,t){this.requireInitialized("Shell query");let r=await this.getAppInfo(),i={...t,appInfo:r,timestamp:new Date().toISOString()},{conversationHistory:n,...o}=i;return Yo.parse(await this.generateContent({prompt:e,templateName:me.KNOWLEDGE_QUERY,...n&&{conversationHistory:n},data:o,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,r){this.requireInitialized("Shell generateObject");let{object:i}=await this.services.aiService.generateObject("You are a helpful assistant. Respond with the requested structured data.",e,t,r);return{object:i}}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 mt(this.services.attachmentRegistry)}getRuntimeUploadRegistry(){return ts(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:r})=>({name:r.name,description:r.description,pluginId:t}))}getPermissionService(){return this.services.permissionService}getAgentService(){return this.services.agentService}registerTools(e,t){for(let r of t)this.services.mcpService.registerTool(e,r)}registerResources(e,t){for(let r of t)this.services.mcpService.registerResource(e,r)}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 r of this.services.templateRegistry.getNames())if(r.startsWith(`${e}:`))this.services.templateRegistry.unregister(r);let t=this.config.evalHandlerRegistry;if(t){for(let r of t.list())if(r.pluginId===e)t.unregister(e,r.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,r){this.services.daemonRegistry.register(e,t,r)}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,r){let i=r?`${r}:${e}`:`shell:${e}`;this.services.templateRegistry.register(i,t),this.services.logger.debug(`Registered template: ${i}`)}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,r){this.config.evalHandlerRegistry?.register(e,t,r)}async getAppInfo(){return hr({config:this.config,services:this.services,bootTime:this.bootTime,endpoints:()=>this.listEndpoints(),interactions:()=>this.listInteractions()})}getRuntimeReadiness(){return br(this.services)}}var rs={kind:"service",serviceId:"brain-cli"},cr=`${rs.kind}:${rs.serviceId}`;var Rl=s.object({provider:s.enum(["hetzner","docker"]).default("hetzner"),serverSize:s.string().default("cx33"),location:s.string().default("fsn1"),domain:s.string().optional(),docker:s.object({enabled:s.boolean().default(!0),image:s.string().optional()}).prefault({}),ports:s.object({default:s.number().default(3333),preview:s.number().default(4321),production:s.number().default(8080)}).prefault({}),cdn:s.object({enabled:s.boolean().default(!1),provider:s.enum(["bunny","none"]).default("none")}).prefault({}),dns:s.object({enabled:s.boolean().default(!1),provider:s.enum(["bunny","none"]).default("none")}).prefault({}),paths:s.object({install:s.string().optional(),data:s.string().optional()}).prefault({})}),ns=s.object({name:s.string().default("brain-app"),version:s.string().default("1.0.0"),database:s.string().optional(),aiApiKey:s.string().optional(),aiImageKey:s.string().optional(),aiModel:s.string().optional(),aiReasoningEffort:se.optional(),logLevel:oe.optional(),logFile:s.string().optional(),profileKind:s.string().trim().min(1).optional(),plugins:s.array(Te).default([]),spaces:s.array(s.string()).default([]),identity:is.optional(),agentInstructions:s.array(s.string()).optional(),deployment:Rl.prefault({})});async function fs(e,t){await Q({label:"entity",config:e,schema:{assets:ss,entities:os,entityMutationReceipts:as,projectionDirtyInputs:cs,projectionWaves:ls,projectionIncidents:us,projectionWaveInputs:ds,projectionWaveRules:ps,projectionRuleMemos:ms},migrationsFolder:K(import.meta.url,"entity-service"),authTokenEnv:"DATABASE_AUTH_TOKEN",logger:t,afterMigrate:gs})}async function vs(e,t){await Q({label:"job-queue",config:e,schema:{jobQueue:hs,jobWorkerSessions:ys},migrationsFolder:K(import.meta.url,"job-queue"),authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",logger:t})}async function Is(e,t){await Q({label:"conversation",config:e,schema:{conversations:bs,messages:Ss,summaryTracking:Rs},migrationsFolder:K(import.meta.url,"conversation-service"),authTokenEnv:"CONVERSATION_DATABASE_AUTH_TOKEN",logger:t})}async function ws(e,t){await Q({label:"runtime-state",config:e,schema:{runtimeStateRecords:R},migrationsFolder:K(import.meta.url,"runtime-state"),authTokenEnv:"RUNTIME_STATE_DATABASE_AUTH_TOKEN",logger:t})}import{mkdir as lr}from"fs/promises";import{isAbsolute as Il}from"path";function Ps(e=process.env){return{dataDir:e.XDG_DATA_HOME??"./data",cacheDir:e.XDG_CACHE_HOME??"./cache",distDir:"./dist"}}function Cs(e=process.env){let t=e.BRAIN_GIT_BROKER_CHECKOUT;if(!t)return;if(!Il(t))throw Error(`Git broker checkout path must be absolute: ${t}`);return t}function Ts(e=process.env){let t=e.BRAIN_GIT_BROKER_SOCKET;if(!t)return;let r=107;if(Buffer.byteLength(t)>r)throw Error(`Git broker socket path is too long for a unix socket (${Buffer.byteLength(t)} > ${r} bytes): ${t}`);return t}function ks(e=process.env){return Y(Ps(e))}async function Es(e=process.env){let t=Ps(e);try{await lr(t.dataDir,{recursive:!0}),await lr(t.cacheDir,{recursive:!0}),await lr(t.distDir,{recursive:!0})}catch(r){let i=r instanceof Error&&r.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: ${C(r)}`;throw Error(i,{cause:r})}return Y(t)}class ur{logger;migrations;constructor(e,t){this.logger=e,this.migrations=t??{getStandardConfigWithDirectories:()=>Es(),migrateEntities:fs,migrateJobQueue:vs,migrateConversations:Is,migrateRuntimeState:ws}}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 wl="NODE_ENV";function Pl(){return process.env[wl]}function xs(){return Pl()!=="production"}var Tl="startup-check";function kl(e){let r={...ns.parse(e??{}),plugins:e?.plugins??[]};if(e?.permissions)r.permissions=e.permissions;if(e?.spaces)r.spaces=e.spaces;if(e?.cliConfig)r.cliConfig=e.cliConfig;if(e?.shellConfig)r.shellConfig=e.shellConfig;return r}function El(e,t){let r={plugins:e.plugins??[],...e.shellConfig};return xl(r),jl(e,r),Al(e,r,t),Dl(e,r),zl(e,r),Ol(e,r),Ml(e,r),Ll(e,r),Ul(e,r),r}function xl(e){let t=ks();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??=Ts(),e.gitBrokerCheckout??=Cs()}function jl(e,t){if(e.database)t.database={url:e.database};if(e.profileKind)t.profileKind=e.profileKind;t.features={}}function Al(e,t,r){let i=r?.mode==="startup-check";if(!e.aiApiKey&&!e.aiImageKey&&!e.aiModel&&!e.aiReasoningEffort&&!i)return;t.ai={...t.ai,...i&&!t.ai?.apiKey&&{apiKey:Tl},...e.aiApiKey&&{apiKey:e.aiApiKey},...e.aiImageKey&&{imageApiKey:e.aiImageKey},...e.aiModel&&{model:e.aiModel},...e.aiReasoningEffort&&{reasoningEffort:e.aiReasoningEffort}}}function Dl(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 zl(e,t){let r=e.permissions?.rules??[];t.permissions={...e.permissions,rules:r.some((i)=>i.pattern===cr)?r:[{pattern:cr,level:"admin"},...r]}}function Ol(e,t){if(e.spaces)t.spaces=e.spaces}function Ml(e,t){if(e.identity)t.identity=e.identity}function Ll(e,t){if(e.agentInstructions)t.agentInstructions=e.agentInstructions}function Ul(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=xs()}class pr{shell=null;config;signalScope=null;signalShutdownFiber=null;stopPromise=null;hasCLI=!1;static create(e,t){return new pr(kl(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=z.getInstance();await new ur(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=Re.createFresh(El(this.config,e),void 0,{...t?.processRole&&{processRole:t.processRole},...t?.peerChannel&&{peerChannel:t.peerChannel}})}async registerCLIInterface(){if(!this.hasCLI)return;let e=this.getShell().getPluginManager(),{CLIInterface:t}=await import("./index-wx77bxhg.js"),r=new t(this.config.cliConfig);e.registerPlugin(r)}async initialize(e,t){if(!this.shell){if(!t?.migrationsCompleted)await this.migrate();this.createShell(e,t)}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 r={debug:x.DEBUG,info:x.INFO,warn:x.WARN,error:x.ERROR}[this.config.logLevel??"info"]??x.INFO,i=z.createFresh({level:r,context:this.config.name,useStderr:this.hasCLI});if(this.hasCLI)z.getInstance().setUseStderr(!0);try{await this.initialize(void 0,e),await this.start(),e?.onRuntimeReady?.(),i.info(`\u2705 ${this.config.name} v${this.config.version} ready`),process.stdin.resume()}catch(n){i.error(`\u274C Failed to start ${this.config.name}:`,n),process.exit(1)}}static async run(e,t,r){await pr.create(e,t).run(r)}setupSignalHandlers(){if(this.signalScope)return;let e=y.runSync(k.make()),t=()=>{this.requestGracefulShutdown("SIGINT")},r=()=>{this.requestGracefulShutdown("SIGTERM")},i=dr(["SIGINT"],t),n=dr(["SIGTERM"],r);y.runSync(k.addFinalizer(e,y.sync(()=>{n(),i()}))),this.signalScope=e}requestGracefulShutdown(e){if(this.signalShutdownFiber)return;let t=z.getInstance();t.info(`
|
|
19
|
+
`)}var ue="system",Sl=s.object({toolName:s.string(),args:s.unknown(),...qo.partial().shape});function pt(e,t,r,i,n){for(let o of e)try{t(o)}catch{n.debug(`System ${i} ${r(o)} already registered, skipping`)}}function Jo(e,t,r,i){let n=$o(e);pt(n,(d)=>t.registerTool(ue,d),(d)=>d.name,"tool",i);let o=r.subscribe(Fo.toolExecute(ue),async(d)=>{let p=Sl.safeParse(d.payload);if(!p.success)return{success:!1,error:"Invalid system tool execute payload"};let{toolName:g,args:f,interfaceType:m,actor:h,conversationId:w,channelId:v,userPermissionLevel:S}=p.data,b=n.find((U)=>U.name===g);if(!b)return{success:!1,error:`System tool not found: ${g}`};let I={interfaceType:m??"system",actor:h??{kind:"service",serviceId:"system"}};if(w)I.conversationId=w;if(v)I.channelId=v;if(S)I.userPermissionLevel=S;return{success:!0,data:await b.handler(f,I)}});i.debug(`Registered ${n.length} system tools`);let a=Bo(e);pt(a,(d)=>t.registerResource(ue,d),(d)=>d.uri,"resource",i),i.debug(`Registered ${a.length} system resources`);let c=_o(e);pt(c,(d)=>t.registerResourceTemplate(ue,d),(d)=>d.uriTemplate,"resource template",i),i.debug(`Registered ${c.length} system resource templates`);let l=Wo(e);pt(l,(d)=>t.registerPrompt(ue,d),(d)=>d.name,"prompt",i),i.debug(`Registered ${l.length} system prompts`);let u=No(e);try{t.registerInstructions(ue,u)}catch{i.debug("System instructions already registered, skipping")}return i.debug("Registered system instructions"),o}function Ko(e){let{services:t,jobs:r,analytics:i,query:n,getAppInfo:o}=e,a=t.jobQueueService,c=t.logger.child("system"),l=Jo({entityService:t.entityService,entityRegistry:t.entityRegistry,jobs:{...r,enqueue:Ho(a,"system",!1),enqueueBatch:Go(r,"system"),registerHandler:Qo(a,"system")},conversationService:t.conversationService,runtimeUploads:t.runtimeUploadRegistry,attachments:mt(t.attachmentRegistry),logger:c,query:n,getIdentity:()=>t.identityService.getCharacter(),getProfile:()=>t.profileService.getProfile(),getAppInfo:o,searchLimit:10,analytics:i,permissionService:t.permissionService},t.mcpService,t.messageBus,c);t.disposables.push(l)}class ar{scope;closePromise=null;closed=!1;constructor(){this.scope=y.runSync(k.make())}buildLayer(e){this.assertOpen();let t=y.runSyncExit(_.buildWithScope(e,this.scope));if(E.isFailure(t))throw q.squash(t.cause);return t.value}addFinalizer(e){this.assertOpen(),y.runSync(k.addFinalizer(this.scope,y.promise(async()=>{await e()})))}addSyncFinalizer(e){this.assertOpen(),y.runSync(k.addFinalizer(this.scope,y.sync(()=>{e()})))}async fork(e){if(this.closed)throw Error("Cannot start background work after shell shutdown");await y.runPromise(y.forkIn(e,this.scope))}close(e=E.void){if(this.closePromise)return this.closePromise;if(this.closed)return Promise.resolve();return this.closed=!0,this.closePromise=y.runPromise(k.close(this.scope,e)),this.closePromise}closeSync(e){if(this.closed)return;this.closed=!0,y.runSync(k.close(this.scope,e))}assertOpen(){if(this.closed)throw Error("Cannot register cleanup after shell shutdown")}}class Re{config;services;lifecycle;bootloader;initialized=!1;lifecycleState="constructed";bootMode;bootPromise=null;shutdownPromise=null;analyticsRegistry;bootTime=Date.now();endpointRegistry=new Jt;interactionRegistry=new Ht;httpRouteRegistry=Ke.createFresh();jobs;static createFresh(e,t,r){return new Re(ke(e),t,r)}constructor(e,t,r){this.config=e,this.lifecycle=new ar,es(this,()=>this.httpRouteRegistry.getSnapshot());let i=t?.logger??z.getInstance(),n=Je.createFresh(i,this.config,r?.processRole,r?.peerChannel);try{this.services=n.initializeServices(this.lifecycle,t),this.jobs=En(this.services.batchJobManager,this.services.jobQueueService),this.analyticsRegistry=wn(this.services.entityRegistry),this.bootloader=new Ft(this.config,this.services,this.lifecycle,n,r?.processRole,{registerCoreDataSources:()=>wr(this.services,this.config),finalizeHttpRoutes:()=>{this.httpRouteRegistry.finalize(An(this.services.pluginManager))},registerSystemCapabilities:()=>Ko({services:this.services,jobs:this.jobs,analytics:this.analyticsRegistry,query:(o,a)=>this.query(o,a),getAppInfo:()=>this.getAppInfo()}),createProjectionInputContext:()=>({entities:this.services.entityService,resolvePrompt:(o,a)=>Ee(this.services.entityService,o,a),appInfo:()=>this.getAppInfo(),identityInput:()=>{let o=this.getIdentity(),a=this.getProfile();return Vo.parse({brainName:o.name,role:o.role,purpose:o.purpose,values:o.values,profileName:a.name,...a.description!==void 0?{profileDescription:a.description}:{},...a.organization!==void 0?{profileOrganization:a.organization}:{}})}}),createProjectionExecutionContext:()=>({ai:Xo(this),logger:this.services.logger.child("ProjectionRuntime")}),...t?.projectionRuntime&&{projectionRuntime:t.projectionRuntime}}),n.wireShell(this.services,this),zn(this.lifecycle,this.services)}catch(o){try{this.lifecycle.closeSync(E.fail(o))}catch(a){i.error("Failed to roll back Shell service construction",a)}throw o}}getAnalyticsRegistry(){return this.analyticsRegistry}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:B.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(E.fail(t))}catch(r){this.services.logger.error("Failed to clean up Shell after initialization failure",r)}throw t}}registerTemplates(e,t){this.services.logger.debug("Registering templates",{pluginId:t,count:Object.keys(e).length});for(let[r,i]of Object.entries(e))this.registerTemplate(r,i,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,t){return this.requireInitialized("Shell content generation"),Pr(this.services,e,t)}async query(e,t){this.requireInitialized("Shell query");let r=await this.getAppInfo(),i={...t,appInfo:r,timestamp:new Date().toISOString()},{conversationHistory:n,...o}=i;return Yo.parse(await this.generateContent({prompt:e,templateName:me.KNOWLEDGE_QUERY,...n&&{conversationHistory:n},data:o,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,r){this.requireInitialized("Shell generateObject");let{object:i}=await this.services.aiService.generateObject("You are a helpful assistant. Respond with the requested structured data.",e,t,r);return{object:i}}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 mt(this.services.attachmentRegistry)}getRuntimeUploadRegistry(){return ts(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:r})=>({name:r.name,description:r.description,pluginId:t}))}getPermissionService(){return this.services.permissionService}getAgentService(){return this.services.agentService}registerTools(e,t){for(let r of t)this.services.mcpService.registerTool(e,r)}registerResources(e,t){for(let r of t)this.services.mcpService.registerResource(e,r)}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 r of this.services.templateRegistry.getNames())if(r.startsWith(`${e}:`))this.services.templateRegistry.unregister(r);let t=this.config.evalHandlerRegistry;if(t){for(let r of t.list())if(r.pluginId===e)t.unregister(e,r.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,r){this.services.daemonRegistry.register(e,t,r)}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,r){let i=r?`${r}:${e}`:`shell:${e}`;this.services.templateRegistry.register(i,t),this.services.logger.debug(`Registered template: ${i}`)}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,r){this.config.evalHandlerRegistry?.register(e,t,r)}async getAppInfo(){return hr({config:this.config,services:this.services,bootTime:this.bootTime,endpoints:()=>this.listEndpoints(),interactions:()=>this.listInteractions()})}getRuntimeReadiness(){return br(this.services)}}var rs={kind:"service",serviceId:"brain-cli"},cr=`${rs.kind}:${rs.serviceId}`;var Rl=s.object({provider:s.enum(["hetzner","docker"]).default("hetzner"),serverSize:s.string().default("cx33"),location:s.string().default("fsn1"),domain:s.string().optional(),docker:s.object({enabled:s.boolean().default(!0),image:s.string().optional()}).prefault({}),ports:s.object({default:s.number().default(3333),preview:s.number().default(4321),production:s.number().default(8080)}).prefault({}),cdn:s.object({enabled:s.boolean().default(!1),provider:s.enum(["bunny","none"]).default("none")}).prefault({}),dns:s.object({enabled:s.boolean().default(!1),provider:s.enum(["bunny","none"]).default("none")}).prefault({}),paths:s.object({install:s.string().optional(),data:s.string().optional()}).prefault({})}),ns=s.object({name:s.string().default("brain-app"),version:s.string().default("1.0.0"),database:s.string().optional(),aiApiKey:s.string().optional(),aiImageKey:s.string().optional(),aiModel:s.string().optional(),aiReasoningEffort:se.optional(),logLevel:oe.optional(),logFile:s.string().optional(),profileKind:s.string().trim().min(1).optional(),plugins:s.array(Te).default([]),spaces:s.array(s.string()).default([]),identity:is.optional(),agentInstructions:s.array(s.string()).optional(),deployment:Rl.prefault({})});async function fs(e,t){await Q({label:"entity",config:e,schema:{assets:ss,entities:os,entityMutationReceipts:as,projectionDirtyInputs:cs,projectionWaves:ls,projectionIncidents:us,projectionWaveInputs:ds,projectionWaveRules:ps,projectionRuleMemos:ms},migrationsFolder:K(import.meta.url,"entity-service"),authTokenEnv:"DATABASE_AUTH_TOKEN",logger:t,afterMigrate:gs})}async function vs(e,t){await Q({label:"job-queue",config:e,schema:{jobQueue:hs,jobWorkerSessions:ys},migrationsFolder:K(import.meta.url,"job-queue"),authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",logger:t})}async function Is(e,t){await Q({label:"conversation",config:e,schema:{conversations:bs,messages:Ss,summaryTracking:Rs},migrationsFolder:K(import.meta.url,"conversation-service"),authTokenEnv:"CONVERSATION_DATABASE_AUTH_TOKEN",logger:t})}async function ws(e,t){await Q({label:"runtime-state",config:e,schema:{runtimeStateRecords:R},migrationsFolder:K(import.meta.url,"runtime-state"),authTokenEnv:"RUNTIME_STATE_DATABASE_AUTH_TOKEN",logger:t})}import{mkdir as lr}from"fs/promises";import{isAbsolute as Il}from"path";function Ps(e=process.env){return{dataDir:e.XDG_DATA_HOME??"./data",cacheDir:e.XDG_CACHE_HOME??"./cache",distDir:"./dist"}}function Cs(e=process.env){let t=e.BRAIN_GIT_BROKER_CHECKOUT;if(!t)return;if(!Il(t))throw Error(`Git broker checkout path must be absolute: ${t}`);return t}function Ts(e=process.env){let t=e.BRAIN_GIT_BROKER_SOCKET;if(!t)return;let r=107;if(Buffer.byteLength(t)>r)throw Error(`Git broker socket path is too long for a unix socket (${Buffer.byteLength(t)} > ${r} bytes): ${t}`);return t}function ks(e=process.env){return Y(Ps(e))}async function Es(e=process.env){let t=Ps(e);try{await lr(t.dataDir,{recursive:!0}),await lr(t.cacheDir,{recursive:!0}),await lr(t.distDir,{recursive:!0})}catch(r){let i=r instanceof Error&&r.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: ${C(r)}`;throw Error(i,{cause:r})}return Y(t)}class ur{logger;migrations;constructor(e,t){this.logger=e,this.migrations=t??{getStandardConfigWithDirectories:()=>Es(),migrateEntities:fs,migrateJobQueue:vs,migrateConversations:Is,migrateRuntimeState:ws}}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 wl="NODE_ENV";function Pl(){return process.env[wl]}function xs(){return Pl()!=="production"}var Tl="startup-check";function kl(e){let r={...ns.parse(e??{}),plugins:e?.plugins??[]};if(e?.permissions)r.permissions=e.permissions;if(e?.spaces)r.spaces=e.spaces;if(e?.cliConfig)r.cliConfig=e.cliConfig;if(e?.shellConfig)r.shellConfig=e.shellConfig;return r}function El(e,t){let r={plugins:e.plugins??[],...e.shellConfig};return xl(r),jl(e,r),Al(e,r,t),Dl(e,r),zl(e,r),Ol(e,r),Ml(e,r),Ll(e,r),Ul(e,r),r}function xl(e){let t=ks();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??=Ts(),e.gitBrokerCheckout??=Cs()}function jl(e,t){if(e.database)t.database={url:e.database};if(e.profileKind)t.profileKind=e.profileKind;t.features={}}function Al(e,t,r){let i=r?.mode==="startup-check";if(!e.aiApiKey&&!e.aiImageKey&&!e.aiModel&&!e.aiReasoningEffort&&!i)return;t.ai={...t.ai,...i&&!t.ai?.apiKey&&{apiKey:Tl},...e.aiApiKey&&{apiKey:e.aiApiKey},...e.aiImageKey&&{imageApiKey:e.aiImageKey},...e.aiModel&&{model:e.aiModel},...e.aiReasoningEffort&&{reasoningEffort:e.aiReasoningEffort}}}function Dl(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 zl(e,t){let r=e.permissions?.rules??[];t.permissions={...e.permissions,rules:r.some((i)=>i.pattern===cr)?r:[{pattern:cr,level:"admin"},...r]}}function Ol(e,t){if(e.spaces)t.spaces=e.spaces}function Ml(e,t){if(e.identity)t.identity=e.identity}function Ll(e,t){if(e.agentInstructions)t.agentInstructions=e.agentInstructions}function Ul(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=xs()}class pr{shell=null;config;signalScope=null;signalShutdownFiber=null;stopPromise=null;hasCLI=!1;static create(e,t){return new pr(kl(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=z.getInstance();await new ur(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=Re.createFresh(El(this.config,e),void 0,{...t?.processRole&&{processRole:t.processRole},...t?.peerChannel&&{peerChannel:t.peerChannel}})}async registerCLIInterface(){if(!this.hasCLI)return;let e=this.getShell().getPluginManager(),{CLIInterface:t}=await import("./index-1japmzr5.js"),r=new t(this.config.cliConfig);e.registerPlugin(r)}async initialize(e,t){if(!this.shell){if(!t?.migrationsCompleted)await this.migrate();this.createShell(e,t)}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 r={debug:x.DEBUG,info:x.INFO,warn:x.WARN,error:x.ERROR}[this.config.logLevel??"info"]??x.INFO,i=z.createFresh({level:r,context:this.config.name,useStderr:this.hasCLI});if(this.hasCLI)z.getInstance().setUseStderr(!0);try{await this.initialize(void 0,e),await this.start(),e?.onRuntimeReady?.(),i.info(`\u2705 ${this.config.name} v${this.config.version} ready`),process.stdin.resume()}catch(n){i.error(`\u274C Failed to start ${this.config.name}:`,n),process.exit(1)}}static async run(e,t,r){await pr.create(e,t).run(r)}setupSignalHandlers(){if(this.signalScope)return;let e=y.runSync(k.make()),t=()=>{this.requestGracefulShutdown("SIGINT")},r=()=>{this.requestGracefulShutdown("SIGTERM")},i=dr(["SIGINT"],t),n=dr(["SIGTERM"],r);y.runSync(k.addFinalizer(e,y.sync(()=>{n(),i()}))),this.signalScope=e}requestGracefulShutdown(e){if(this.signalShutdownFiber)return;let t=z.getInstance();t.info(`
|
|
20
20
|
Received ${e}, shutting down gracefully...`);let r=y.tryPromise({try:()=>this.stop(),catch:(i)=>i}).pipe(y.match({onFailure:(i)=>{t.error("Error during shutdown:",i),process.exit(1)},onSuccess:()=>{process.exit(0)}}));this.signalShutdownFiber=y.runFork(r)}async closeSignalScope(){let e=this.signalScope;if(this.signalScope=null,e)await y.runPromise(k.close(e,E.void))}getShell(){if(!this.shell)throw Error("Shell not initialized. Call initialize() first.");return this.shell}}
|
|
21
21
|
export{oe as S,se as T,ve as U,so as V,lo as W,st as X,Kc as Y,Xt as Z,Vc as _,at as $,Xc as aa,Qg as ba,vo as ca,rl as da,tr as ea,rr as fa,il as ga,nl as ha,ol as ia,Tl as ja,kl as ka,El as la,pr as ma};
|
|
22
22
|
|
|
23
|
-
//# debugId=
|
|
24
|
-
//# sourceMappingURL=index-
|
|
23
|
+
//# debugId=548280CB462351A964756E2164756E21
|
|
24
|
+
//# sourceMappingURL=index-qsvhvhw2.js.map
|