@rizom/brain 0.2.0-alpha.707 → 0.2.0-alpha.709

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{$h as Uo,Ab as yd,Ae as Rd,Aj as Ho,Bb as vd,Be as wd,Bg as ad,Cb as bd,Ce as qo,Cg as bs,Db as ro,De as Jo,Eb as io,Ee as Go,Fb as no,Ge as Qo,Gi as nc,Hb as Ut,He as Vl,Hh as Fe,Hi as oc,Hj as Os,Ib as os,Ic as ss,Ie as Yl,Ih as rn,Ii as gt,Ij as ld,Jb as wt,Je as Xl,Kb as Ge,Ke as ed,Kh as hn,Ki as cd,Kj as Es,Lb as je,Le as nd,Lf as Rn,Lh as ve,Li as Is,Lj as Xa,Mb as pc,Me as jl,Mf as ht,Mh as yn,Mj as tr,Nb as vl,Nf as Ja,Nh as vn,Oa as pt,Od as B,Of as od,Oh as Mr,Pa as Re,Pb as A,Ph as Rs,Qa as go,Qb as hr,Qd as ac,Qf as Hs,Qh as bn,Ra as z,Rb as ii,Rd as Ua,Sb as el,Sd as Ti,Ta as ue,Tb as zo,Ub as Oo,Va as fo,Vb as Mo,Vf as Zc,Wf as Fc,Xb as St,Xf as Nc,Xh as ws,Yb as _r,Yf as ms,Yh as Ps,Zf as gs,Zh as Pc,_f as fs,_h as Cs,ai as xs,bb as ho,bc as yr,cc as Bc,ci as Eo,di as $o,ei as Bo,fd as Pr,fi as _o,gb as Gr,gi as Zo,hb as Tt,ib as ao,jb as co,jd as ml,lb as lo,ld as As,lg as hs,mb as dd,me as Za,ne as bt,ng as ys,od as js,of as Cd,og as Qe,pb as uo,pd as Gc,pf as xd,pg as Ga,qb as vo,qf as Id,qg as Qa,rd as bl,re as Kn,sb as fe,sc as id,sd as as,se as us,sg as Ka,tb as he,tc as Ns,te as Sn,tg as sd,tj as Ds,ub as ud,uc as oo,ud as te,ue as ps,ug as Lo,uj as Fo,vb as pd,vd as Wi,vf as sr,wb as md,we as Fs,wf as Ac,xb as gd,xc as _c,xe as ri,xf as Yn,xg as kr,xj as zs,yb as fd,yf as Od,yg as vs,yj as No,zb as hd,zc as eo,zg as Ae,zj as Ts}from"./index-spb5t14d.js";import{An as ls,Bn as ds,Dn as Ql,Gl as le,In as Ss,Jl as Ie,Jm as rd,Jn as za,Ll as C,Ml as Je,Mn as ge,Nm as Xo,Qn as ee,Sk as $a,Tk as Q,Tl as Qn,Uj as ll,Vj as dl,Wj as ae,Yj as xr,Zj as fr,_j as nt,dm as be,dn as Ma,fm as Dt,fn as La,km as Zs,lm as Xt,ln as se,mn as X,pl as jo,pm as Wa,ql as Do,sm as Vt,tl as Gn,tn as cs,zn as kc}from"./index-g3vf515j.js";import{Rn as Ve,Tn as Ee}from"./index-15n3etjh.js";import{Fv as Ro,Hs as V,Mv as We,Ov as ce,Pv as wo,Qv as er,Rv as qa,Up as T,Uv as Va,Yr as de,_r as ns,ks as k,yv as b,zs as E}from"./index-1zv6k097.js";import{kx as l}from"./index-5b1nmh3r.js";function Or(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 _e(e,t){let r=e.workerSessions,i=r.active===0?"missing":r.stale>0?"stale":"active",n=e.duePending>0&&(e.oldestDuePendingAgeMs??0)>=120000&&e.totals.processing===0&&(e.latestClaimAgeMs===null||e.latestClaimAgeMs>=120000),o=[];if(i==="missing")o.push("No live worker session");else if(i==="stale")o.push(`${r.stale} stale worker session(s)`);if(n)o.push(`${e.duePending} due job(s) have remained unclaimed for at least 120000ms`);if(t){let s=Or(e,t).reduce((a,c)=>a+c.count,0);if(s>0)o.push(`${s} active job(s) have no declared executor`)}return{status:o.length===0?"operational":"degraded",reasons:o,worker:{state:i,activeSessions:r.active,staleSessions:r.stale,latestHeartbeatAgeMs:r.latestHeartbeatAgeMs},queue:{duePending:e.duePending,processing:e.totals.processing,oldestDuePendingAgeMs:e.oldestDuePendingAgeMs,latestClaimAgeMs:e.latestClaimAgeMs,stalled:n}}}async function un(e){let{config:t,services:r,bootTime:i,endpoints:n,interactions:o}=e,[s,a,c,d]=await Promise.all([r.entityService.getEntityCounts(pt("runtime app info reports operator-facing aggregate status")),r.entityService.countEmbeddings(),r.daemonRegistry.getStatuses(),r.jobQueueService.getDiagnostics()]),u=s.reduce((p,m)=>p+m.count,0);return{model:t.name||"brain-app",version:t.version||"1.0.0",uptime:Math.floor((Date.now()-i)/1000),entities:u,entityCounts:s,embeddings:a,backgroundWork:_e(d,r.jobQueueService.getExecutionRegistrations()),ai:{model:t.ai.model,embeddingModel:r.embeddingService.identity.model},daemons:c,endpoints:n(),interactions:o()}}import{readdir as pn,readFile as Gd}from"fs/promises";var Qd=10;async function Kd(e="/proc"){let t=null;try{t=(await pn(`${e}/self/fd`)).length}catch{}try{let i=(await pn(e,{withFileTypes:!0})).filter((s)=>s.isDirectory()&&/^\d+$/.test(s.name)).map((s)=>s.name),n=0,o=0;return await Promise.all(i.map(async(s)=>{try{let a=await Gd(`${e}/${s}/status`,"utf8");if(o++,/^State:\s+Z\b/m.test(a))n++}catch{}})),{fileDescriptors:t,processCount:o,zombieCount:n}}catch{return{fileDescriptors:t,processCount:null,zombieCount:null}}}function mn(e,t,r){return t.status==="fulfilled"?{name:e,status:"healthy",message:r}:{name:e,status:"unhealthy",message:C(t.reason)}}function Vd(e){if(!e)return{name:"job-worker",status:"degraded",message:"Worker session state is unavailable"};let t=e.workerSessions,r=_e(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 Yd(e){if(!e)return{name:"job-queue-progress",status:"degraded",message:"Queue progress state is unavailable"};let t=_e(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 Xd(e,t){if(!e||!t)return{name:"job-execution-inventory",status:"degraded",message:"Job execution inventory is unavailable"};let r=Or(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 eu(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 tu(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 ru(e){let t=e.entityService.getProjectionStore(),[r,i,n]=await Promise.all([t.getActiveWave(),t.getUnresolvedProjectionIncidentDiagnostics(Qd),t.getProjectionBatchDiagnostics?.()??Promise.resolve({preparing:0,open:0,abandoned:0,expiredCallbackLeases:0,oldestActiveAgeMs:null,oldestProgressAgeMs:null})]);if(!r)return{waveId:null,batches:n,strandedRules:[],incidentCount:i.total,incidents:i.incidents};let s=(await t.listWaveRules(r.id)).filter((c)=>c.status==="queued"||c.status==="failed"),a=(await Promise.all(s.map(async(c)=>{let d=c.jobId?await e.jobQueueService.getStatus(c.jobId):null;if(c.status!=="failed"&&d&&(d.status==="pending"||d.status==="processing"))return null;return{ruleId:c.ruleId,jobId:c.jobId,jobStatus:d?.status??"missing"}}))).filter((c)=>c!==null);return{waveId:r.id,batches:n,strandedRules:a,incidentCount:i.total,incidents:i.incidents}}function iu(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 nu(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 gn(e){let t=e.now?.()??Date.now(),r=(e.memoryUsage??process.memoryUsage)(),[i,n,o,s,a,c,d,u]=await Promise.allSettled([e.entityService.getEntityCounts(pt("runtime readiness database probe")),e.jobQueueService.getDiagnostics(t),Promise.resolve(e.jobQueueService.getExecutionRegistrations()),e.daemonRegistry.getStatuses(),(e.readProcessSignals??Kd)(),e.projectionRuntimeSupervisor.getDiagnostics(),ru(e),e.operationalHealthRegistry.getChecks()]),p=n.status==="fulfilled"?n.value:null,m=o.status==="fulfilled"?o.value??null:null,g=s.status==="fulfilled"?s.value:[],f=a.status==="fulfilled"?a.value:{fileDescriptors:null,processCount:null,zombieCount:null},h=c.status==="fulfilled"?c.value:{status:"unhealthy",initialized:!1,trackedRoots:0,openCircuits:[]},v=[mn("entity-database",i,"Entity database is accessible"),mn("job-queue-database",n,"Job queue database is accessible"),Vd(p),Yd(p),Xd(p,m),eu(p),c.status==="fulfilled"?tu(h):{name:"projection-circuits",status:"degraded",message:C(c.reason)},d.status==="fulfilled"?iu(d.value):{name:"projection-waves",status:"degraded",message:C(d.reason)},s.status==="fulfilled"?nu(g):{name:"daemons",status:"degraded",message:C(s.reason)}],y=u.status==="fulfilled"?u.value:[{name:"plugin-operational-health",status:"degraded",message:"Plugin operational health is unavailable"}],S=[...v,...y];return{status:v.some((R)=>R.status==="unhealthy")?"not_ready":"ready",operationalStatus:S.some((R)=>R.status!=="healthy")?"degraded":"operational",checkedAt:new Date(t).toISOString(),checks:S,resources:{memory:{rssBytes:r.rss,heapUsedBytes:r.heapUsed,heapTotalBytes:r.heapTotal},fileDescriptors:f.fileDescriptors,processes:{total:f.processCount,zombies:f.zombieCount},queue:p,projection:{initialized:h.initialized,trackedRoots:h.trackedRoots,openCircuits:h.openCircuits},worker:p?.workerSessions??{total:0,active:0,stale:0,latestHeartbeatAgeMs:null}}}}function fn(){return{dataDir:"./data",cacheDir:"./cache",distDir:"./dist"}}function ye(e){return{database:{url:`file:${e.dataDir}/brain.db`},jobQueueDatabase:{url:`file:${e.dataDir}/brain-jobs.db`},conversationDatabase:{url:`file:${e.dataDir}/conversations.db`},runtimeStateDatabase:{url:`file:${e.dataDir}/runtime-state.db`},embeddingDatabase:{url:`file:${e.dataDir}/embeddings.db`},embedding:{enabled:!0}}}var Ze=l.strictObject({enabled:l.boolean().optional().describe("Serve HTTP; defaults to whether the selected bundles host the web surface"),preview:l.boolean().optional().describe("Serve the preview site; defaults to whether a site builder runs"),hostname:l.string().trim().min(1).optional().describe("Bind address; use 127.0.0.1 for isolated local tests"),productionDistDir:l.string().min(1).optional().describe("Directory of the production site, when no site builder writes it"),previewDistDir:l.string().min(1).optional().describe("Directory of the preview site, when no site builder writes it"),sharedImagesDir:l.string().min(1).optional().describe("Directory of shared optimized images")}),mt=Ze.extend({enabled:l.boolean().default(!1),preview:l.boolean().default(!0),port:l.number().default(8080).describe("Port of the production listener")});var Lr=fn(),ou=l.looseObject({label:l.string().min(1),pluralName:l.string().optional(),layout:l.string().optional(),paginate:l.boolean().optional(),pageSize:l.number().optional(),navigation:l.object({show:l.boolean().optional(),slot:l.enum(["primary","secondary"]).optional(),priority:l.number().optional()}).optional()});function Ur(){return ye(Lr)}var Te=l.enum(["debug","info","warn","error"]);var $r=l.object({name:l.string().default("brain-app"),version:l.string().default("1.0.0"),database:Ie,jobQueueDatabase:Ie,jobQueue:l.object({workerConcurrency:l.number().int().min(1).max(32).default(4)}).prefault({}),conversationDatabase:Ie,runtimeStateDatabase:Ie,embeddingDatabase:Ie,ai:l.object({providerKeys:Fe.default({}),model:l.string().refine(hn,{error:(e)=>`Unsupported model "${String(e.input)}"`}),embeddingModel:l.string().refine((e)=>Mr(e)!==void 0,{error:(e)=>bn(String(e.input))}).default(vn),modelRuntimeUrl:l.string().url().optional(),answerModel:l.string().optional(),visionModel:l.string().optional(),imageModel:l.string().optional(),temperature:l.number().min(0).max(2).default(0.7),webSearch:l.boolean().default(!0),reasoningEffort:se.optional()}).superRefine((e,t)=>{if(e.answerModel&&ve(e.answerModel)!=="local")t.addIssue({code:"custom",path:["answerModel"],message:`answerModel must be a local: model, not ${e.answerModel}`});if(e.visionModel&&ve(e.visionModel)!=="local")t.addIssue({code:"custom",path:["visionModel"],message:`visionModel must be a local: model, not ${e.visionModel}`});if(e.modelRuntimeUrl)return;let r=[...ve(e.model)==="local"?[e.model]:[],...[e.answerModel,e.visionModel].filter((i)=>i!==void 0&&ve(i)==="local"),...e.imageModel&&yn(e.imageModel).provider==="local"?[e.imageModel]:[],...Mr(e.embeddingModel)?.provider==="local"?[e.embeddingModel]:[]];for(let i of r)t.addIssue({code:"custom",path:["modelRuntimeUrl"],message:`${i} needs modelRuntime.url`})}),embedding:l.object({enabled:l.boolean().default(!0)}),logging:l.object({level:Te.default("info"),format:l.enum(["text","json"]).default("text"),file:l.string().optional(),context:l.string().default("shell")}).prefault({level:"info",context:"shell"}),features:l.object({}).default({}),plugins:l.array(gt).default([]),dataDir:l.string().default("./brain-data"),gitBrokerSocket:l.string().min(1).optional(),gitBrokerCheckout:l.string().min(1).optional(),spaces:l.array(l.string()).default([]),siteBaseUrl:l.string().optional(),localSiteUrl:l.string().optional(),preferLocalUrls:l.boolean().default(!1),production:l.boolean().default(!1),themeCSS:l.string().default(""),entityDisplay:l.record(l.string(),ou).optional(),profileKind:l.string().trim().min(1).optional(),http:mt.prefault({})});function ft(e={}){let{plugins:t=[],permissions:r={},identity:i,profile:n,agentInstructions:o,evalHandlerRegistry:s,ai:a,logging:c,embedding:d,jobQueue:u,...p}=e,{entityDisplay:m,...g}=$r.parse({...Ur(),...Q(p),ai:Q({...a}),logging:Q({...c}),embedding:Q({...d}),jobQueue:Q({...u}),plugins:[]});return{...g,plugins:t,permissions:r,...Q({entityDisplay:m,identity:i,profile:n,agentInstructions:o,evalHandlerRegistry:s})}}var L={NOTE:"note",BRAIN_CHARACTER:"brain-character",ANCHOR_PROFILE:"anchor-profile"},Ne={KNOWLEDGE_QUERY:"shell:knowledge-query",BASE_ENTITY_DISPLAY:"shell:base-entity-display",CONTENT_GENERATION:"shell:content-generation"},Br={ENTITIES:"shell:entities"};var su=Sn.extend({templateName:l.string()}),au=l.object({slug:l.string()}),cu="The style guide governs voice, tone, wording and form: paragraphing, sentence rhythm, hooks, rhetorical questions and calls to action. The instructions below and any additional instructions in the request govern the task, required content, length limits, platform constraints and output format. When either conflicts with the style guide on voice or form, follow the style guide.",lu="Generate the content described in your instructions.";function du(e){return e instanceof l.ZodType}function uu(e){if(!e)return;return e.replace(/^https?:\/\//,"").replace(/\/$/,"")}class yt{aiService;entityService;templateRegistry;getIdentityContent;getProfileContent;entityUrls;id="ai-content";name="AI Content Generator";description="Generates content using AI based on templates and prompts";constructor(e,t,r,i,n,o,s){this.aiService=e,this.entityService=t,this.templateRegistry=r,this.getIdentityContent=i,this.getProfileContent=n,this.entityUrls=o,this.siteBaseUrl=uu(s)}siteBaseUrl;async generate(e,t,r){return this.generateWithContext(e,t,r)}async generateScoped(e,t,r){return this.generateWithContext(e,t,r.signal,r)}async generateWithContext(e,t,r,i){r?.throwIfAborted();let n=su.parse(e),o=this.templateRegistry.get(n.templateName);if(!o)throw Error(`Template not found: ${n.templateName}`);if(!o.basePrompt)throw Error(`Template ${n.templateName} must have basePrompt for content generation`);let s=i?await Rn((v,y)=>i.getEntity(v,y),n.templateName,o.basePrompt):await ht(this.entityService,n.templateName,o.basePrompt);r?.throwIfAborted();let a=[s,n.prompt].filter(Boolean).join(" "),c=a.length>0&&o.useKnowledgeContext===!0,d=this.entityService.getWeightMap(),u=Object.keys(d).length>0,p=c?i?await i.search(a,{limit:5,...u&&{weight:d}}):await this.entityService.search({query:a,options:{limit:5,...u&&{weight:d},...r&&{signal:r}}}):[];r?.throwIfAborted();let m=this.buildPrompt(n,p),g=i?await this.readIdentities(i,n.representedIdentity):void 0,f=this.buildSystemPrompt(s,n,g);if(!du(o.schema))throw Error(`Template ${o.name} cannot be used for AI generation: schema is not an AI generation schema`);r?.throwIfAborted();let h=await this.aiService.generateObject(f,m,o.schema,r);return r?.throwIfAborted(),t.parse(h.object)}async readIdentities(e,t){let r=async(o)=>(await e.getEntity(o,o))?.content??"",[i,n]=await Promise.all([t!=="none"?r(L.BRAIN_CHARACTER):"",t===void 0||t==="anchor"?r(L.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",cu,"");return i.push("# Instructions",e),i.join(`
2
+ import{$h as $o,Ab as yd,Ae as Rd,Aj as Wo,Bb as vd,Be as wd,Bg as ad,Cb as bd,Ce as Jo,Cg as Ss,Db as io,De as Go,Eb as no,Ee as Qo,Fb as oo,Ge as Ko,Gi as oc,Hb as Ut,He as Vl,Hh as Fe,Hi as sc,Hj as Ms,Ib as ss,Ic as as,Ie as Yl,Ih as nn,Ii as gt,Ij as ld,Jb as wt,Je as Xl,Kb as Ge,Ke as ed,Kh as yn,Ki as cd,Kj as ks,Lb as je,Le as nd,Lf as wn,Lh as ve,Li as Ts,Lj as ec,Mb as mc,Me as jl,Mf as ht,Mh as vn,Mj as tr,Nb as vl,Nf as Ga,Nh as bn,Oa as pt,Od as B,Of as od,Oh as Mr,Pa as Re,Pb as A,Ph as ws,Qa as fo,Qb as hr,Qd as cc,Qf as Ws,Qh as Sn,Ra as z,Rb as ii,Rd as $a,Sb as el,Sd as Ti,Ta as ue,Tb as Oo,Ub as Mo,Va as ho,Vb as Lo,Vf as Wi,Wf as Fc,Xb as St,Xf as Nc,Xh as Ps,Yb as _r,Yf as gs,Yh as Cs,Zf as fs,Zh as Cc,_f as hs,_h as xs,ai as Is,bb as yo,bc as yr,cc as _c,ci as ko,di as Bo,ei as _o,fd as Pr,fi as Zo,gb as Gr,gi as Fo,hb as Tt,ib as co,jb as lo,jd as ml,lb as uo,ld as js,lg as ys,mb as dd,me as Fa,ne as bt,ng as vs,od as Ds,of as Cd,og as Qe,pb as po,pd as Gc,pf as xd,pg as Qa,qb as bo,qf as Id,qg as Ka,rd as bl,re as Vn,sb as fe,sc as id,sd as cs,se as ps,sg as Va,tb as he,tc as Hs,te as Rn,tg as sd,tj as zs,ub as ud,uc as so,ud as te,ue as ms,ug as Uo,uj as No,vb as pd,vd as qi,vf as sr,wb as md,we as Ns,wf as jc,xb as gd,xc as Zc,xe as ri,xf as Xn,xg as kr,xj as Os,yb as fd,yf as Od,yg as bs,yj as Ho,zb as hd,zc as to,zg as Ae,zj as Es}from"./index-spb5t14d.js";import{An as ds,Bn as us,Dn as Ql,Gl as le,In as Rs,Jl as Ie,Jm as rd,Jn as Oa,Ll as C,Ml as Je,Mn as ge,Nm as es,Qn as ee,Sk as Ba,Tk as Q,Tl as Kn,Uj as ll,Vj as dl,Wj as ae,Yj as xr,Zj as fr,_j as nt,dm as be,dn as La,fm as Dt,fn as Ua,km as Fs,lm as Xt,ln as se,mn as X,pl as Do,pm as qa,ql as zo,sm as Vt,tl as Qn,tn as ls,zn as Ac}from"./index-g3vf515j.js";import{Rn as Ve,Tn as Ee}from"./index-15n3etjh.js";import{Fv as wo,Hs as V,Mv as We,Ov as ce,Pv as Po,Qv as er,Rv as Ja,Up as T,Uv as Ya,Yr as de,_r as os,ks as k,yv as b,zs as E}from"./index-1zv6k097.js";import{kx as l}from"./index-5b1nmh3r.js";function Or(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 _e(e,t){let r=e.workerSessions,i=r.active===0?"missing":r.stale>0?"stale":"active",n=e.duePending>0&&(e.oldestDuePendingAgeMs??0)>=120000&&e.totals.processing===0&&(e.latestClaimAgeMs===null||e.latestClaimAgeMs>=120000),o=[];if(i==="missing")o.push("No live worker session");else if(i==="stale")o.push(`${r.stale} stale worker session(s)`);if(n)o.push(`${e.duePending} due job(s) have remained unclaimed for at least 120000ms`);if(t){let s=Or(e,t).reduce((a,c)=>a+c.count,0);if(s>0)o.push(`${s} active job(s) have no declared executor`)}return{status:o.length===0?"operational":"degraded",reasons:o,worker:{state:i,activeSessions:r.active,staleSessions:r.stale,latestHeartbeatAgeMs:r.latestHeartbeatAgeMs},queue:{duePending:e.duePending,processing:e.totals.processing,oldestDuePendingAgeMs:e.oldestDuePendingAgeMs,latestClaimAgeMs:e.latestClaimAgeMs,stalled:n}}}async function pn(e){let{config:t,services:r,bootTime:i,endpoints:n,interactions:o}=e,[s,a,c,d]=await Promise.all([r.entityService.getEntityCounts(pt("runtime app info reports operator-facing aggregate status")),r.entityService.countEmbeddings(),r.daemonRegistry.getStatuses(),r.jobQueueService.getDiagnostics()]),u=s.reduce((p,m)=>p+m.count,0);return{model:t.name||"brain-app",version:t.version||"1.0.0",uptime:Math.floor((Date.now()-i)/1000),entities:u,entityCounts:s,embeddings:a,backgroundWork:_e(d,r.jobQueueService.getExecutionRegistrations()),ai:{model:t.ai.model,embeddingModel:r.embeddingService.identity.model},daemons:c,endpoints:n(),interactions:o()}}import{readdir as mn,readFile as Gd}from"fs/promises";var Qd=10;async function Kd(e="/proc"){let t=null;try{t=(await mn(`${e}/self/fd`)).length}catch{}try{let i=(await mn(e,{withFileTypes:!0})).filter((s)=>s.isDirectory()&&/^\d+$/.test(s.name)).map((s)=>s.name),n=0,o=0;return await Promise.all(i.map(async(s)=>{try{let a=await Gd(`${e}/${s}/status`,"utf8");if(o++,/^State:\s+Z\b/m.test(a))n++}catch{}})),{fileDescriptors:t,processCount:o,zombieCount:n}}catch{return{fileDescriptors:t,processCount:null,zombieCount:null}}}function gn(e,t,r){return t.status==="fulfilled"?{name:e,status:"healthy",message:r}:{name:e,status:"unhealthy",message:C(t.reason)}}function Vd(e){if(!e)return{name:"job-worker",status:"degraded",message:"Worker session state is unavailable"};let t=e.workerSessions,r=_e(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 Yd(e){if(!e)return{name:"job-queue-progress",status:"degraded",message:"Queue progress state is unavailable"};let t=_e(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 Xd(e,t){if(!e||!t)return{name:"job-execution-inventory",status:"degraded",message:"Job execution inventory is unavailable"};let r=Or(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 eu(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 tu(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 ru(e){let t=e.entityService.getProjectionStore(),[r,i,n]=await Promise.all([t.getActiveWave(),t.getUnresolvedProjectionIncidentDiagnostics(Qd),t.getProjectionBatchDiagnostics?.()??Promise.resolve({preparing:0,open:0,abandoned:0,expiredCallbackLeases:0,oldestActiveAgeMs:null,oldestProgressAgeMs:null})]);if(!r)return{waveId:null,batches:n,strandedRules:[],incidentCount:i.total,incidents:i.incidents};let s=(await t.listWaveRules(r.id)).filter((c)=>c.status==="queued"||c.status==="failed"),a=(await Promise.all(s.map(async(c)=>{let d=c.jobId?await e.jobQueueService.getStatus(c.jobId):null;if(c.status!=="failed"&&d&&(d.status==="pending"||d.status==="processing"))return null;return{ruleId:c.ruleId,jobId:c.jobId,jobStatus:d?.status??"missing"}}))).filter((c)=>c!==null);return{waveId:r.id,batches:n,strandedRules:a,incidentCount:i.total,incidents:i.incidents}}function iu(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 nu(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 fn(e){let t=e.now?.()??Date.now(),r=(e.memoryUsage??process.memoryUsage)(),[i,n,o,s,a,c,d,u]=await Promise.allSettled([e.entityService.getEntityCounts(pt("runtime readiness database probe")),e.jobQueueService.getDiagnostics(t),Promise.resolve(e.jobQueueService.getExecutionRegistrations()),e.daemonRegistry.getStatuses(),(e.readProcessSignals??Kd)(),e.projectionRuntimeSupervisor.getDiagnostics(),ru(e),e.operationalHealthRegistry.getChecks()]),p=n.status==="fulfilled"?n.value:null,m=o.status==="fulfilled"?o.value??null:null,g=s.status==="fulfilled"?s.value:[],f=a.status==="fulfilled"?a.value:{fileDescriptors:null,processCount:null,zombieCount:null},h=c.status==="fulfilled"?c.value:{status:"unhealthy",initialized:!1,trackedRoots:0,openCircuits:[]},v=[gn("entity-database",i,"Entity database is accessible"),gn("job-queue-database",n,"Job queue database is accessible"),Vd(p),Yd(p),Xd(p,m),eu(p),c.status==="fulfilled"?tu(h):{name:"projection-circuits",status:"degraded",message:C(c.reason)},d.status==="fulfilled"?iu(d.value):{name:"projection-waves",status:"degraded",message:C(d.reason)},s.status==="fulfilled"?nu(g):{name:"daemons",status:"degraded",message:C(s.reason)}],y=u.status==="fulfilled"?u.value:[{name:"plugin-operational-health",status:"degraded",message:"Plugin operational health is unavailable"}],S=[...v,...y];return{status:v.some((R)=>R.status==="unhealthy")?"not_ready":"ready",operationalStatus:S.some((R)=>R.status!=="healthy")?"degraded":"operational",checkedAt:new Date(t).toISOString(),checks:S,resources:{memory:{rssBytes:r.rss,heapUsedBytes:r.heapUsed,heapTotalBytes:r.heapTotal},fileDescriptors:f.fileDescriptors,processes:{total:f.processCount,zombies:f.zombieCount},queue:p,projection:{initialized:h.initialized,trackedRoots:h.trackedRoots,openCircuits:h.openCircuits},worker:p?.workerSessions??{total:0,active:0,stale:0,latestHeartbeatAgeMs:null}}}}function hn(){return{dataDir:"./data",cacheDir:"./cache",distDir:"./dist"}}function ye(e){return{database:{url:`file:${e.dataDir}/brain.db`},jobQueueDatabase:{url:`file:${e.dataDir}/brain-jobs.db`},conversationDatabase:{url:`file:${e.dataDir}/conversations.db`},runtimeStateDatabase:{url:`file:${e.dataDir}/runtime-state.db`},embeddingDatabase:{url:`file:${e.dataDir}/embeddings.db`},embedding:{enabled:!0}}}var Ze=l.strictObject({enabled:l.boolean().optional().describe("Serve HTTP; defaults to whether the selected bundles host the web surface"),preview:l.boolean().optional().describe("Serve the preview site; defaults to whether a site builder runs"),hostname:l.string().trim().min(1).optional().describe("Bind address; use 127.0.0.1 for isolated local tests"),productionDistDir:l.string().min(1).optional().describe("Directory of the production site, when no site builder writes it"),previewDistDir:l.string().min(1).optional().describe("Directory of the preview site, when no site builder writes it"),sharedImagesDir:l.string().min(1).optional().describe("Directory of shared optimized images")}),mt=Ze.extend({enabled:l.boolean().default(!1),preview:l.boolean().default(!0),port:l.number().default(8080).describe("Port of the production listener")});var Lr=hn(),ou=l.looseObject({label:l.string().min(1),pluralName:l.string().optional(),layout:l.string().optional(),paginate:l.boolean().optional(),pageSize:l.number().optional(),navigation:l.object({show:l.boolean().optional(),slot:l.enum(["primary","secondary"]).optional(),priority:l.number().optional()}).optional()});function Ur(){return ye(Lr)}var Te=l.enum(["debug","info","warn","error"]);var $r=l.object({name:l.string().default("brain-app"),version:l.string().default("1.0.0"),database:Ie,jobQueueDatabase:Ie,jobQueue:l.object({workerConcurrency:l.number().int().min(1).max(32).default(4)}).prefault({}),conversationDatabase:Ie,runtimeStateDatabase:Ie,embeddingDatabase:Ie,ai:l.object({providerKeys:Fe.default({}),model:l.string().refine(yn,{error:(e)=>`Unsupported model "${String(e.input)}"`}),embeddingModel:l.string().refine((e)=>Mr(e)!==void 0,{error:(e)=>Sn(String(e.input))}).default(bn),modelRuntimeUrl:l.string().url().optional(),answerModel:l.string().optional(),visionModel:l.string().optional(),imageModel:l.string().optional(),temperature:l.number().min(0).max(2).default(0.7),webSearch:l.boolean().default(!0),reasoningEffort:se.optional()}).superRefine((e,t)=>{if(e.answerModel&&ve(e.answerModel)!=="local")t.addIssue({code:"custom",path:["answerModel"],message:`answerModel must be a local: model, not ${e.answerModel}`});if(e.visionModel&&ve(e.visionModel)!=="local")t.addIssue({code:"custom",path:["visionModel"],message:`visionModel must be a local: model, not ${e.visionModel}`});if(e.modelRuntimeUrl)return;let r=[...ve(e.model)==="local"?[e.model]:[],...[e.answerModel,e.visionModel].filter((i)=>i!==void 0&&ve(i)==="local"),...e.imageModel&&vn(e.imageModel).provider==="local"?[e.imageModel]:[],...Mr(e.embeddingModel)?.provider==="local"?[e.embeddingModel]:[]];for(let i of r)t.addIssue({code:"custom",path:["modelRuntimeUrl"],message:`${i} needs modelRuntime.url`})}),embedding:l.object({enabled:l.boolean().default(!0)}),logging:l.object({level:Te.default("info"),format:l.enum(["text","json"]).default("text"),file:l.string().optional(),context:l.string().default("shell")}).prefault({level:"info",context:"shell"}),features:l.object({}).default({}),plugins:l.array(gt).default([]),dataDir:l.string().default("./brain-data"),gitBrokerSocket:l.string().min(1).optional(),gitBrokerCheckout:l.string().min(1).optional(),spaces:l.array(l.string()).default([]),siteBaseUrl:l.string().optional(),localSiteUrl:l.string().optional(),preferLocalUrls:l.boolean().default(!1),production:l.boolean().default(!1),themeCSS:l.string().default(""),entityDisplay:l.record(l.string(),ou).optional(),profileKind:l.string().trim().min(1).optional(),http:mt.prefault({})});function ft(e={}){let{plugins:t=[],permissions:r={},identity:i,profile:n,agentInstructions:o,evalHandlerRegistry:s,ai:a,logging:c,embedding:d,jobQueue:u,...p}=e,{entityDisplay:m,...g}=$r.parse({...Ur(),...Q(p),ai:Q({...a}),logging:Q({...c}),embedding:Q({...d}),jobQueue:Q({...u}),plugins:[]});return{...g,plugins:t,permissions:r,...Q({entityDisplay:m,identity:i,profile:n,agentInstructions:o,evalHandlerRegistry:s})}}var L={NOTE:"note",BRAIN_CHARACTER:"brain-character",ANCHOR_PROFILE:"anchor-profile"},Ne={KNOWLEDGE_QUERY:"shell:knowledge-query",BASE_ENTITY_DISPLAY:"shell:base-entity-display",CONTENT_GENERATION:"shell:content-generation"},Br={ENTITIES:"shell:entities"};var su=Rn.extend({templateName:l.string()}),au=l.object({slug:l.string()}),cu="The style guide governs voice, tone, wording and form: paragraphing, sentence rhythm, hooks, rhetorical questions and calls to action. The instructions below and any additional instructions in the request govern the task, required content, length limits, platform constraints and output format. When either conflicts with the style guide on voice or form, follow the style guide.",lu="Generate the content described in your instructions.";function du(e){return e instanceof l.ZodType}function uu(e){if(!e)return;return e.replace(/^https?:\/\//,"").replace(/\/$/,"")}class yt{aiService;entityService;templateRegistry;getIdentityContent;getProfileContent;entityUrls;id="ai-content";name="AI Content Generator";description="Generates content using AI based on templates and prompts";constructor(e,t,r,i,n,o,s){this.aiService=e,this.entityService=t,this.templateRegistry=r,this.getIdentityContent=i,this.getProfileContent=n,this.entityUrls=o,this.siteBaseUrl=uu(s)}siteBaseUrl;async generate(e,t,r){return this.generateWithContext(e,t,r)}async generateScoped(e,t,r){return this.generateWithContext(e,t,r.signal,r)}async generateWithContext(e,t,r,i){r?.throwIfAborted();let n=su.parse(e),o=this.templateRegistry.get(n.templateName);if(!o)throw Error(`Template not found: ${n.templateName}`);if(!o.basePrompt)throw Error(`Template ${n.templateName} must have basePrompt for content generation`);let s=i?await wn((v,y)=>i.getEntity(v,y),n.templateName,o.basePrompt):await ht(this.entityService,n.templateName,o.basePrompt);r?.throwIfAborted();let a=[s,n.prompt].filter(Boolean).join(" "),c=a.length>0&&o.useKnowledgeContext===!0,d=this.entityService.getWeightMap(),u=Object.keys(d).length>0,p=c?i?await i.search(a,{limit:5,...u&&{weight:d}}):await this.entityService.search({query:a,options:{limit:5,...u&&{weight:d},...r&&{signal:r}}}):[];r?.throwIfAborted();let m=this.buildPrompt(n,p),g=i?await this.readIdentities(i,n.representedIdentity):void 0,f=this.buildSystemPrompt(s,n,g);if(!du(o.schema))throw Error(`Template ${o.name} cannot be used for AI generation: schema is not an AI generation schema`);r?.throwIfAborted();let h=await this.aiService.generateObject(f,m,o.schema,r);return r?.throwIfAborted(),t.parse(h.object)}async readIdentities(e,t){let r=async(o)=>(await e.getEntity(o,o))?.content??"",[i,n]=await Promise.all([t!=="none"?r(L.BRAIN_CHARACTER):"",t===void 0||t==="anchor"?r(L.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",cu,"");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(`
@@ -7,7 +7,7 @@ ${e.conversationHistory}`);if(t.length>0){let i=t.map((n)=>this.formatRelevantEn
7
7
  ${i}`)}if(e.data)r.push(`Context data:
8
8
  ${JSON.stringify(e.data,null,2)}`);if(e.prompt)r.push(`Additional instructions: ${e.prompt}`);return r.length>0?r.join(`
9
9
 
10
- `):lu}formatRelevantEntity(e,t){let{entity:r,excerpt:i}=e,n=r.entityType,o=au.safeParse(r.metadata),s=o.success?o.data.slug:r.id;if(this.siteBaseUrl&&t.hasRoute(n)){let a=t.generateUrl(n,s),c=`https://${this.siteBaseUrl}${a}`;return`[${n}] ${r.id}: ${i} (${c})`}return`[${n}] ${r.id}: ${i}`}}var pu=l.object({entityType:l.string(),query:l.object({id:l.string()})});class vt{entityService;id=Br.ENTITIES;name="Entity DataSource";description="Fetches entity content from the entity service";constructor(e){this.entityService=e}async fetch(e,t,r){let i=pu.safeParse(e);if(!i.success){let a=i.error.issues.map((c)=>`${c.path.join(".")}: ${c.message}`).join(", ");throw Error(`EntityDataSource: Invalid query - ${a}`)}let n=i.data,s=await(r?.entityService??this.entityService).getEntity({entityType:n.entityType,id:n.query.id});if(!s)throw Error(`EntityDataSource: Entity not found (${n.entityType}:${n.query.id})`);return t.parse({markdown:s.content})}}function wn(e,t){e.dataSourceRegistry.register(new yt(e.aiService,e.entityService,e.templateRegistry,()=>e.identityService.getCharacterContent(),()=>e.profileService.getProfileContent(),new bt(t.entityDisplay),t.siteBaseUrl)),e.dataSourceRegistry.register(new vt(e.entityService)),e.logger.debug("Core DataSources registered")}async function Pn(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})}var Cn={lexicon:1,id:"ai.rizom.brain.card",defs:{main:{type:"record",description:"Public discovery card for a Rizom brain. A web-capable brain may advertise its operational A2A Agent Card through siteUrl; federation-only brains remain discoverable through this PDS record.",key:"literal:self",record:{type:"object",required:["brain","anchor","skills","model","version","createdAt"],properties:{siteUrl:{type:"string",format:"uri",description:"Optional public web-channel URL. Consumers may derive the A2A Agent Card URL from this base when present."},brain:{type:"ref",ref:"#brain",description:"Brain identity described by this discovery card."},anchor:{type:"ref",ref:"#anchor",description:"Minimal Anchor snapshot for discovery grouping and display."},skills:{type:"array",description:"User-facing skills this brain advertises for discovery.",items:{type:"ref",ref:"#skill"},maxLength:100},model:{type:"string",description:"Rizom brain model identifier."},version:{type:"string",description:"Brain runtime/model implementation version."},createdAt:{type:"string",format:"datetime"},updatedAt:{type:"string",format:"datetime"}}}},brain:{type:"object",description:"Brain identity described by this discovery card.",required:["did","name","role","purpose","values"],properties:{did:{type:"string",description:"Public DID for the brain identity."},name:{type:"string",maxLength:200,description:"Human-readable brain name."},role:{type:"string",maxLength:500,description:"Brain role or persona."},purpose:{type:"string",maxLength:2000,description:"Short public description of what this brain is for."},values:{type:"array",description:"Public values or principles for this brain.",items:{type:"string",maxLength:200},maxLength:50}}},anchor:{type:"object",description:"Minimal Anchor snapshot for discovery grouping and display.",required:["did","name","category","kind"],properties:{did:{type:"string",description:"Public DID for the Anchor identity."},name:{type:"string",maxLength:200,description:"Human-readable anchor name."},category:{type:"string",knownValues:["person","team","organization"],description:"Stable structural category for discovery and grouping."},kind:{type:"string",maxLength:200,description:"Open semantic profile kind selected by the publishing brain."}}},skill:{type:"object",description:"User-facing skill this brain advertises for discovery.",required:["id","name","description"],properties:{id:{type:"string",maxLength:200},name:{type:"string",maxLength:200},description:{type:"string",maxLength:2000},tags:{type:"array",items:{type:"string"},maxLength:50},examples:{type:"array",items:{type:"string"},maxLength:20}}}}};var xn={lexicon:1,id:"ai.rizom.brain.deck",defs:{main:{type:"record",description:"Public presentation deck from a Rizom brain.",key:"any",record:{type:"object",required:["title","body","createdAt"],properties:{title:{type:"string",maxLength:300},slug:{type:"string"},description:{type:"string",maxLength:2000},body:{type:"string",maxLength:1e5},format:{type:"string",knownValues:["text/markdown"]},author:{type:"string"},event:{type:"string"},publishedAt:{type:"string",format:"datetime"},canonicalUrl:{type:"string",format:"uri"},brainDid:{type:"string"},anchorDid:{type:"string"},sourceEntityType:{type:"string"},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},updatedAt:{type:"string",format:"datetime"}}}}}};var In={lexicon:1,id:"ai.rizom.brain.link",defs:{main:{type:"record",description:"Public curated link from a Rizom brain.",key:"any",record:{type:"object",required:["title","url","createdAt"],properties:{title:{type:"string",maxLength:500},url:{type:"string",format:"uri"},description:{type:"string",maxLength:2000},summary:{type:"string",maxLength:1e5},domain:{type:"string"},capturedAt:{type:"string",format:"datetime"},source:{type:"ref",ref:"#source"},canonicalUrl:{type:"string",format:"uri"},brainDid:{type:"string"},anchorDid:{type:"string"},sourceEntityType:{type:"string"},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},updatedAt:{type:"string",format:"datetime"}}}},source:{type:"object",description:"Attribution for where this link was captured.",required:["ref","label"],properties:{ref:{type:"string"},label:{type:"string"}}}}};var Tn={lexicon:1,id:"ai.rizom.brain.note",defs:{main:{type:"record",description:"Public knowledge note from a Rizom brain.",key:"any",record:{type:"object",required:["title","body","createdAt"],properties:{title:{type:"string",maxLength:300},body:{type:"string",maxLength:1e5},format:{type:"string",knownValues:["text/markdown"]},canonicalUrl:{type:"string",format:"uri"},brainDid:{type:"string"},anchorDid:{type:"string"},sourceEntityType:{type:"string"},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},updatedAt:{type:"string",format:"datetime"}}}}}};var En={lexicon:1,id:"ai.rizom.brain.post",defs:{main:{type:"record",description:"Markdown blog post distributed by a Rizom brain.",key:"any",record:{type:"object",required:["title","body","createdAt"],properties:{title:{type:"string",maxLength:300},summary:{type:"string",maxLength:2000},body:{type:"string",maxLength:1e5},format:{type:"string",knownValues:["text/markdown"]},brainDid:{type:"string"},anchorDid:{type:"string"},canonicalUrl:{type:"string",format:"uri"},topics:{type:"array",items:{type:"string"},maxLength:50},coverImage:{type:"ref",ref:"#coverImage"},series:{type:"string",maxLength:200},seriesIndex:{type:"integer"},sourceEntityType:{type:"string",knownValues:["post"]},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},publishedAt:{type:"string",format:"datetime"}}}},coverImage:{type:"object",description:"Cover image attached to the post.",required:["blob"],properties:{blob:{type:"blob"},alt:{type:"string",maxLength:1000},width:{type:"integer"},height:{type:"integer"}}}}};var kn={lexicon:1,id:"ai.rizom.brain.project",defs:{main:{type:"record",description:"Public project or case study from a Rizom brain.",key:"any",record:{type:"object",required:["title","body","year","createdAt"],properties:{title:{type:"string",maxLength:300},slug:{type:"string"},description:{type:"string",maxLength:2000},body:{type:"string",maxLength:1e5},format:{type:"string",knownValues:["text/markdown"]},year:{type:"integer"},url:{type:"string",format:"uri"},publishedAt:{type:"string",format:"datetime"},canonicalUrl:{type:"string",format:"uri"},brainDid:{type:"string"},anchorDid:{type:"string"},sourceEntityType:{type:"string"},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},updatedAt:{type:"string",format:"datetime"}}}}}};var An={lexicon:1,id:"ai.rizom.brain.series",defs:{main:{type:"record",description:"Public content series from a Rizom brain.",key:"any",record:{type:"object",required:["title","createdAt"],properties:{title:{type:"string",maxLength:300},slug:{type:"string"},description:{type:"string",maxLength:1e4},canonicalUrl:{type:"string",format:"uri"},brainDid:{type:"string"},anchorDid:{type:"string"},sourceEntityType:{type:"string"},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},updatedAt:{type:"string",format:"datetime"}}}}}};var jn={lexicon:1,id:"ai.rizom.brain.socialPost",defs:{main:{type:"record",description:"Semantic local social-post entity from a Rizom brain; not a Bluesky feed post.",key:"any",record:{type:"object",required:["title","platform","body","createdAt"],properties:{title:{type:"string",maxLength:300},platform:{type:"string"},body:{type:"string",maxLength:1e5},format:{type:"string",knownValues:["text/markdown"]},status:{type:"string"},publishedAt:{type:"string",format:"datetime"},platformPostId:{type:"string"},sourceLocalEntityType:{type:"string"},sourceLocalEntityId:{type:"string"},canonicalUrl:{type:"string",format:"uri"},brainDid:{type:"string"},anchorDid:{type:"string"},sourceEntityType:{type:"string"},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},updatedAt:{type:"string",format:"datetime"}}}}}};var Dn={lexicon:1,id:"ai.rizom.brain.topic",defs:{main:{type:"record",description:"Public topic page from a Rizom brain.",key:"any",record:{type:"object",required:["title","body","createdAt"],properties:{title:{type:"string",maxLength:300},body:{type:"string",maxLength:1e5},format:{type:"string",knownValues:["text/markdown"]},canonicalUrl:{type:"string",format:"uri"},brainDid:{type:"string"},anchorDid:{type:"string"},sourceEntityType:{type:"string"},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},updatedAt:{type:"string",format:"datetime"}}}}}};var zn=l.object({type:l.string()}).catchall(l.unknown()),wu=l.object({type:l.literal("object"),description:l.string().optional(),required:l.array(l.string()).optional(),properties:l.record(l.string(),zn)}),Pu=l.object({lexicon:l.literal(1),id:l.string(),defs:l.object({main:l.object({type:l.literal("record"),key:l.string().min(1),description:l.string().optional(),record:l.object({type:l.literal("object"),required:l.array(l.string()).optional(),properties:l.record(l.string(),zn)})})}).catchall(wu)});function N(e){return Pu.parse(e)}var D={"ai.rizom.brain.card":N(Cn),"ai.rizom.brain.deck":N(xn),"ai.rizom.brain.link":N(In),"ai.rizom.brain.note":N(Tn),"ai.rizom.brain.post":N(En),"ai.rizom.brain.project":N(kn),"ai.rizom.brain.series":N(An),"ai.rizom.brain.socialPost":N(jn),"ai.rizom.brain.topic":N(Dn)},Cu="Additive optional fields are compatible; required-field, type, or constraint changes require a migration plan or new NSID.";function K(e){return{status:"approved",version:"1.0.0",revision:1,owner:"Rizom",steward:"Rizom protocol registry",projectionPackage:e,compatibility:Cu}}var On={"ai.rizom.brain.card":K("@brains/atproto"),"ai.rizom.brain.deck":K("@brains/decks"),"ai.rizom.brain.link":K("@brains/link"),"ai.rizom.brain.note":K("@brains/note"),"ai.rizom.brain.post":K("@brains/blog"),"ai.rizom.brain.project":K("@brains/portfolio"),"ai.rizom.brain.series":K("@brains/series"),"ai.rizom.brain.socialPost":K("@brains/social-media"),"ai.rizom.brain.topic":K("@brains/topics")};function xu(){return Object.values(D)}function Iu(e){if(!_r(D,e))return;return D[e]}function Tu(){return St(On).map(([e,t])=>({id:e,...t}))}var Eu=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;function ku(e){let t=l.string(),r=e.maxLength!==void 0?t.max(e.maxLength):t;if(e.knownValues)r=r.refine((i)=>e.knownValues?.includes(i),{message:`expected one of ${e.knownValues.join(", ")}`});if(e.format==="datetime")r=r.refine((i)=>Eu.test(i)&&!Number.isNaN(Date.parse(i)),{message:"expected datetime"});if(e.format==="uri")r=r.refine((i)=>{try{return new URL(i),!0}catch{return!1}},{message:"expected uri"});return r}function Au(e,t){if(typeof e!=="string"||!e.startsWith("#"))return;let r=t[e.slice(1)];return r?.type==="object"?r:void 0}function Ln(e,t){switch(e.type){case"string":return ku(e);case"integer":return l.number().int();case"boolean":return l.boolean();case"array":{let r=e.items?Ln(e.items,t):l.unknown(),i=l.array(r);if(e.maxLength!==void 0)i=i.max(e.maxLength);return i}case"object":return Mn(e,t);case"ref":{let r=Au(e.ref,t);if(!r)return l.custom(()=>!1,{message:`unresolvable lexicon ref ${String(e.ref)}`});return l.lazy(()=>Mn(r,t))}case"blob":return l.custom(ae,{message:"expected blob"});default:return l.unknown()}}function Un(e,t){let r=new Set(e.required??[]),i={};for(let[n,o]of Object.entries(e.properties??{})){let s=Ln(o,t);i[n]=r.has(n)?s:s.optional()}return i}function Mn(e,t){return l.strictObject(Un(e,t))}function Z(e){return l.strictObject({...Un(e.defs.main.record,e.defs),$type:l.literal(e.id).optional()})}var Zr={"ai.rizom.brain.card":Z(D["ai.rizom.brain.card"]),"ai.rizom.brain.deck":Z(D["ai.rizom.brain.deck"]),"ai.rizom.brain.link":Z(D["ai.rizom.brain.link"]),"ai.rizom.brain.note":Z(D["ai.rizom.brain.note"]),"ai.rizom.brain.post":Z(D["ai.rizom.brain.post"]),"ai.rizom.brain.project":Z(D["ai.rizom.brain.project"]),"ai.rizom.brain.series":Z(D["ai.rizom.brain.series"]),"ai.rizom.brain.socialPost":Z(D["ai.rizom.brain.socialPost"]),"ai.rizom.brain.topic":Z(D["ai.rizom.brain.topic"])};function ju(e,t){let r=e;for(let i of t){if(typeof i==="symbol")return;if(Array.isArray(r)){r=r[Number(i)];continue}if(!ae(r))return;r=r[String(i)]}return r}function Du(e,t,r){let i=r.path.join(".");if(i==="$type")return`AT Protocol record $type must match lexicon id: ${String(t.$type)} !== ${e.id}`;if(r.code==="invalid_type"&&ju(t,r.path)===void 0)return`Missing required AT Protocol record field: ${i}`;if(r.code==="invalid_type")return`Invalid AT Protocol record field ${i}: expected ${r.expected}`;if(r.code==="too_big")return`Invalid AT Protocol record field ${i}: exceeds maxLength ${r.maximum}`;if(r.code==="custom")return`Invalid AT Protocol record field ${i}: ${r.message}`;if(r.code==="unrecognized_keys")return`Unrecognized AT Protocol record field(s): ${r.keys.join(", ")}`;return`Invalid AT Protocol record field ${i}: ${r.message}`}function zu(e,t){let r=Z(e).safeParse(t);if(r.success)return;let i=r.error.issues[0];if(!i)throw r.error;throw Error(Du(e,t,i))}var $n="atproto:brain-card-discovered",Bn="atproto:brain-discovered",_n="atproto:brain-card-refreshed",Zn="atproto:brain-card-unavailable",Fn="atproto:brain-card-conflict",Nn="atproto:jetstream-gap",Ou=l.custom((e)=>Zr["ai.rizom.brain.card"].safeParse(e).success),Hn=l.object({repoDid:l.string().min(1),uri:l.string().min(1),cid:l.string().min(1),record:Ou}).strict(),Fr=l.object({agentId:l.string().min(1),name:l.string().min(1),url:l.string().url(),status:l.enum(["discovered","approved","archived"]),repoDid:l.string().min(1).optional(),brainDid:l.string().min(1).optional(),anchorDid:l.string().min(1).optional(),cardUri:l.string().min(1).optional(),cardCid:l.string().min(1).optional()}).strict(),Wn=l.object({repoDid:l.string().startsWith("did:plc:"),observedAt:l.string().datetime(),staleAfter:l.string().datetime().optional(),reason:l.enum(["deleted","refresh-failed"]),error:l.string().min(1).optional()}).strict(),qn=l.object({domain:l.string().min(1),existingRepoDid:l.string().min(1).optional(),candidateRepoDid:l.string().startsWith("did:plc:"),observedAt:l.string().datetime(),reason:l.string().min(1)}).strict(),Jn=l.object({previousCursorTimeUs:l.number().int().nonnegative(),clampedCursorTimeUs:l.number().int().nonnegative(),observedAt:l.string().datetime()}).strict(),Mu=be($n,Hn),Lu=be(Bn,Fr),Uu=be(_n,Fr),$u=be(Zn,Wn),Bu=be(Fn,qn),_u=be(Nn,Jn);class Rt{projections=new Map;register(e){this.validateProjection(e);let t=this.get(e.entityType);if(t&&!this.isEquivalentProjection(t,e))throw Error(`AT Protocol projection already registered for entity type ${e.entityType}`);let r=this.projections.get(e.entityType)??[];return r.push(e),this.projections.set(e.entityType,r),this.createUnregister(e.entityType,e)}get(e){let t=this.projections.get(e);return t?.[t.length-1]}has(e){return this.get(e)!==void 0}list(){let e=[];for(let t of this.projections.keys()){let r=this.get(t);if(r)e.push(r)}return e}listLexicons(){return this.list().map((e)=>e.lexicon)}createUnregister(e,t){let r=!0;return()=>{if(!r)return;r=!1;let i=this.projections.get(e);if(!i)return;let n=i.lastIndexOf(t);if(n!==-1)i.splice(n,1);if(i.length===0)this.projections.delete(e)}}isEquivalentProjection(e,t){return e.entityType===t.entityType&&e.collection===t.collection&&e.lexicon.id===t.lexicon.id&&e.validate===t.validate}validateProjection(e){if(e.collection!==e.lexicon.id)throw Error(`AT Protocol projection collection must match lexicon id: ${e.collection} !== ${e.lexicon.id}`);if(!e.lexicon.defs.main.key)throw Error(`AT Protocol projection lexicon must define a record key: ${e.collection}`)}}function Zu({config:e,pageUrl:t},r){return{...e.brainDid&&{brainDid:e.brainDid},...e.anchorDid&&{anchorDid:e.anchorDid},...t&&{canonicalUrl:t},sourceEntityType:r.entityType,sourceEntityId:r.id,createdAt:r.created,...r.updated&&{updatedAt:r.updated}}}async function Pt(e,t,r){let i=await wt(e,Gn,{actor:r},t);if(i.status==="unavailable")return null;if(i.status==="failed")throw Qn(i.error,`Principal resolution failed: ${i.error.message}`);return i.data.principal}function Vn(e,t){return new Kn(e,(r)=>Pt(t,"shell:content-service",r))}var Nr=T.Service("@brains/conversation-service/ConversationService");function Fu(e){if(e.service){let r=e.service;return{service:r,close:()=>r.close()}}let t=Yn.createFreshFromConfig(e.logger,e.messageBus,e.dbConfig);try{return{service:t,close:()=>t.close()}}catch(r){throw t.close(),r}}function Xn(e){return ce(Nr,()=>Fu(e))}var Hr=T.Service("@brains/entity-service/EntityService");function Nu(e){return"close"in e&&typeof e.close==="function"}function to(e){return ce(Hr,()=>{let t=e.service??eo.createFresh(e);return{service:t,close:()=>{if(Nu(t))t.close()}}})}var He=l.strictObject({dedupeKey:l.string().min(1).max(512),title:l.string().min(1),body:l.string().min(1),html:l.string().min(1).optional(),sensitivity:l.enum(["normal","secret"]).optional(),includeInInbox:l.boolean().optional()}),Wr=l.strictObject({alerts:l.array(He).optional()});var Ct="shell:recurring-check",Jr=86400000,Hu=7*Jr,Wu=3*Jr,qu=l.strictObject({checkId:l.string().min(1)}),Ju=l.discriminatedUnion("kind",[l.strictObject({kind:l.literal("last-success"),checkId:l.string(),at:l.string().datetime()}),l.strictObject({kind:l.literal("alert"),checkId:l.string(),dedupeKey:l.string(),status:l.enum(["pending","suppressed","delivered","resolved"]),alert:He,observedAt:l.string().datetime(),includeInInbox:l.boolean().optional(),deliveredAt:l.string().datetime().optional(),resolvedAt:l.string().datetime().optional()})]);class It{brainId;scheduler;state;jobQueue;delivery;logger;clock;checks=new Map;pluginChecks=new Map;alertOperations=new oo;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.state=e.runtimeState.scoped({namespace:"shell.recurring-checks",schema:Ju});let t={validateAndParse:(r)=>{let i=qu.safeParse(r);return i.success?i.data:null},process:async(r)=>{await this.runNow(r.checkId)}};this.jobQueue.registerHandler(Ct,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(Ct),this.handlerRegistered=!1}namespace(e){return{register:(t)=>this.register(e,t)}}register(e,t){Qu(e),so(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 s=Promise.resolve().then(()=>this.executeRegisteredCheck(r,n)),a=()=>{if(r.activeCheck===o)delete r.activeCheck};return o.settled=s.then(a,a),s}async executeRegisteredCheck(e,t){let r=e.definition.id,i,n=async(a)=>{let c=AbortSignal.any([t,a]),d=e.definition.deliverAlerts!==!1;if(d)await this.flushPendingAlerts(r);else await this.suppressPendingAlerts(r);c.throwIfAborted();let u=await e.definition.run({signal:c});c.throwIfAborted();let p=Wr.parse(u);for(let m of p.alerts??[])c.throwIfAborted(),await this.recordAlert(r,m,{deliver:d,includeInInbox:m.includeInInbox??e.definition.includeInInbox!==!1});c.throwIfAborted(),await this.state.set(this.lastSuccessKey(r),{kind:"last-success",checkId:r,at:this.currentTime().toISOString()})},o=b.tryPromise({try:(a)=>(i=n(a),i),catch:(a)=>a}),s=await b.runPromiseExit(o,{signal:t});if(i)await Promise.allSettled([i]);if(k.isSuccess(s))return!0;if(t.aborted)throw t.reason;throw de.squash(s.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=xt(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=xt(this.brainId,r.id,r.cadence),n=qr(this.currentTime(),i).getTime()+i.periodMs,o=new AbortController,s={controller:o,settled:Promise.resolve()};e.enqueueRetry=s,s.settled=ro(()=>this.enqueue(r.id),t,{firstDelayMs:io,maxDelayMs:no,giveUpAt:n,signal:o.signal,clock:this.clock,onRetry:(a,c)=>{this.logger.warn(`Failed to enqueue recurring check ${r.id}; retrying in ${c}ms`,a)}}).then((a)=>{if(a.kind!=="abandoned")return;this.logger.error(`Failed to enqueue recurring check ${r.id}; the next scheduled run supersedes it`,a.error)},(a)=>{this.logger.error(`Retrying recurring check ${r.id} failed`,a)}).finally(()=>{if(e.enqueueRetry===s)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=xt(this.brainId,t.id,t.cadence),n=qr(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(s){this.retryRefusedEnqueue(e,s)}}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:Ct,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=He.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 a=o.includeInInbox===r.includeInInbox?o:{...o,includeInInbox:r.includeInInbox};if(a!==o)await this.state.set(n,a);if(a.status==="delivered"||a.status==="resolved")return;if(r.deliver)await this.deliverStoredAlert(n,a);return}let s={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,s),r.deliver)await this.deliverStoredAlert(n,s)})}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()):new Date}lastSuccessKey(e){return`run:${le(e)}`}alertKeyPrefix(e){return`alert:${le(e)}:`}alertKey(e,t){return`${this.alertKeyPrefix(e)}${le(t)}`}}function xt(e,t,r){let i=r==="daily"?Jr:Hu,n=i/60000,o=le(`${e}\x00${t}\x00${r}`),s=Number.parseInt(o.slice(0,12),16)%n,a=s%60,c=Math.floor(s/60),d=c%24;return{expression:r==="daily"?`${a} ${d} * * *`:`${a} ${d} * * ${Math.floor(c/24)}`,offsetMs:s*60000,periodMs:i,anchorMs:r==="daily"?0:Wu}}function qr(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)}var Gu=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*:[a-z][a-z0-9-]*$/;function Qu(e){if(e.length<=200&&Gu.test(e))return;so(e,"plugin ID")}function so(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 P=ao("runtime_state_records",{namespace:Tt("namespace").notNull(),key:Tt("key").notNull(),value:Tt("value",{mode:"json"}).notNull(),createdAt:Gr("created_at").notNull(),updatedAt:Gr("updated_at").notNull()},(e)=>({pk:lo({columns:[e.namespace,e.key]}),namespaceUpdatedAtIdx:co("idx_runtime_state_namespace_updated_at").on(e.namespace,e.updatedAt)}));function po(e){return uo({url:e.url,schema:{runtimeStateRecords:P},authToken:e.authToken,authTokenEnv:"RUNTIME_STATE_DATABASE_AUTH_TOKEN"})}function Et(e,t){let r=JSON.stringify(t);if(!r)throw Error("Runtime state must be a JSON wire value");let i=JSON.parse(r);return e.parse(i),i}import{isDeepStrictEqual as Ku}from"util";var Vu=/^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,511}$/,yo=512;class Qr{db;namespace;schema;now;constructor(e,t,r,i=()=>new Date){Yu(t),this.db=e,this.namespace=t,this.schema=r,this.now=i}async get(e){let t=Se(e),i=(await this.db.select().from(P).where(ue(z(P.namespace,this.namespace),z(P.key,t))).limit(1))[0];if(!i)return null;return this.schema.parse(i.value)}async has(e){let t=Se(e);return(await this.db.select({key:P.key}).from(P).where(ue(z(P.namespace,this.namespace),z(P.key,t))).limit(1)).length>0}async set(e,t){let r=Se(e),i=Et(this.schema,t),n=i===null?Re`'null'`:i,o=this.now().getTime();await this.db.insert(P).values({namespace:this.namespace,key:r,value:n,createdAt:o,updatedAt:o}).onConflictDoUpdate({target:[P.namespace,P.key],set:{value:n,updatedAt:o}})}async setIfNotExists(e,t){let r=Se(e),i=Et(this.schema,t),n=i===null?Re`'null'`:i,o=this.now().getTime(),s=await this.db.insert(P).values({namespace:this.namespace,key:r,value:n,createdAt:o,updatedAt:o}).onConflictDoNothing({target:[P.namespace,P.key]});return Number(s.rowsAffected)>0}async compareAndSet(e,t,r){let i=Se(e),n=Et(this.schema,r),[o]=await this.db.select({value:P.value}).from(P).where(ue(z(P.namespace,this.namespace),z(P.key,i))).limit(1);if(!o||!Ku(this.schema.parse(o.value),t))return!1;let s=o.value===null?Re`'null'`:o.value,a=n===null?Re`'null'`:n,c=await this.db.update(P).set({value:a,updatedAt:this.now().getTime()}).where(ue(z(P.namespace,this.namespace),z(P.key,i),z(P.value,s)));return Number(c.rowsAffected)===1}async delete(e){let t=Se(e),r=await this.db.delete(P).where(ue(z(P.namespace,this.namespace),z(P.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(P).where(ue(z(P.namespace,this.namespace),mo(e.keyPrefix)));return Number(t.rowsAffected)}async listRows(e){let{keyPrefix:t,afterKey:r,limit:i}=e;if(r!==void 0)Se(r);if(i!==void 0)l.number().int().min(1).max(1000).parse(i);let n=this.db.select({...go(P),key:Re`CAST(${P.key} AS BLOB)`.mapWith((o)=>new TextDecoder("utf-8",{fatal:!0}).decode(o))}).from(P).where(ue(z(P.namespace,this.namespace),mo(t),r!==void 0?fo(P.key,r):void 0)).orderBy(ho(P.key)).$dynamic();return i===void 0?n:n.limit(i)}}function Yu(e){if(!Vu.test(e))throw Error(`Invalid runtime state namespace: ${e}. Use 1-512 alphanumeric, _, ., :, or - characters.`)}function Se(e){if(e.length===0||e.length>yo)throw Error("Runtime state keys must be 1-512 characters long");return e}function mo(e){if(e===void 0)return;return Xu(e),Re`substr(CAST(${P.key} AS BLOB), 1, length(CAST(${e} AS BLOB))) = CAST(${e} AS BLOB)`}function Xu(e){if(e.length>yo)throw Error("Runtime state key prefixes must be 512 characters or shorter");return e}class kt{db;client;logger;databaseUrl;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;static createFresh(e,t){return new kt(e,t??Ee.getInstance())}constructor(e,t){let{db:r,client:i,url:n}=po(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 vo(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){let t=new Qr(this.db,e.namespace,e.schema);return Object.freeze({get:t.get.bind(t),has:t.has.bind(t),set:t.set.bind(t),setIfNotExists:t.setIfNotExists.bind(t),compareAndSet:t.compareAndSet.bind(t),delete:t.delete.bind(t),list:t.list.bind(t),clear:t.clear.bind(t)})}close(){if(this.closeRequested=!0,!this.walInitialization||this.walInitializationSettled)this.closeClient()}closeClient(){if(this.clientClosed)return;this.clientClosed=!0,this.client.close()}}var Kr=T.Service("@brains/runtime-state/RuntimeStateService");function bo(e){return ce(Kr,()=>{let t=e.service??kt.createFresh(e.config,e.logger);return{service:t,close:()=>t.close()}})}function Vr(e,t,r){let i=Bun.cron.parse(e,t,r?{tz:r}:void 0);if(i===null)throw Error(`Cron expression ${JSON.stringify(e)} has no future occurrences`);return i}function So(e){Vr(e,Date.now())}class qe{options;nextJobId=0;constructor(e={}){this.options=e}scheduleCron(e,t,r={}){Vr(e,Date.now(),r.timezone);let i=`cron:${this.nextJobId++}:${e}`,n={},o=new Yr(i,t,this.options,()=>n.current?.stop());return n.current=Bun.cron(e,()=>{o.trigger()},r.timezone?{tz:r.timezone}:void 0),o}scheduleInterval(e,t){ep(e);let r=`interval:${this.nextJobId++}:${e}`,i=new Yr(r,t,this.options);return i.startInterval(e),i}validateCron(e){So(e)}}class Yr{key;callback;options;stopTrigger;scope;cycles;intervalFiber=null;stopPromise=null;stopped=!1;constructor(e,t,r,i=()=>{}){this.key=e,this.callback=t,this.options=r,this.stopTrigger=i,this.scope=b.runSync(E.make()),this.cycles=b.runSync(E.provide(We.make(),this.scope))}startInterval(e){let t=b.sleep(e).pipe(b.andThen(b.sync(()=>{this.trigger()})),b.forever),r=wo(t,this.options.clock);this.intervalFiber=b.runFork(r)}trigger(){if(this.stopped)return;if(We.hasUnsafe(this.cycles,this.key)){this.options.onOverlapSkipped?.(this.key);return}let e=b.tryPromise({try:async()=>{await this.callback()},catch:(r)=>r}).pipe(b.catch((r)=>b.sync(()=>{this.options.onCallbackError?.(this.key,r)}))),t=b.runFork(e);We.setUnsafe(this.cycles,this.key,t,{onlyIfMissing:!0})}stop(){return this.stopPromise??=this.stopScheduledJob(),this.stopPromise}async stopScheduledJob(){this.stopped=!0;let e=[];try{this.stopTrigger()}catch(i){e.push(i)}let t=this.intervalFiber;this.intervalFiber=null;let r=[...t?[Ro.interrupt(t)]:[],We.awaitEmpty(this.cycles),E.close(this.scope,k.void)];for(let i of r)try{await b.runPromise(i)}catch(n){e.push(n)}if(e.length===1)throw e[0];if(e.length>1)throw AggregateError(e,"Scheduled job cleanup failed")}}function ep(e){if(!Number.isFinite(e)||e<=0)throw Error("Scheduler interval must be a positive finite number")}function Po(e){let t=e.scheduler??new qe,r=e.now??Date.now,i,n,o,s=!1,a=!1,c={status:"unknown"},d=0,u=0,p=async()=>{if(!s||a)return;a=!0,i=r();try{await e.run(),d++,c={status:"healthy",lastCheck:new Date(r()),details:{successes:d,failures:u}}}catch{u++,c={status:"warning",message:"Maintenance cycle failed",lastCheck:new Date(r()),details:{successes:d,failures:u}},e.logger.warn("Maintenance cycle failed",{successes:d,failures:u})}finally{a=!1}};return{start:async()=>{if(o)await o;if(n)return;c={status:"unknown"},i=r(),n=t.scheduleInterval(e.intervalMs,p),s=!0},stop:()=>{if(o)return o;if(s=!1,!n)return Promise.resolve();return o=n.stop().then(()=>{n=void 0,o=void 0}),o},healthCheck:async()=>{let m=r();if(!Number.isSafeInteger(m)||m<0||i!==void 0&&!Number.isSafeInteger(i))return{status:"warning",message:"Maintenance clock unavailable"};if(s&&i!==void 0&&(m<i||m-i>e.intervalMs*2))return{status:"warning",message:a?"Maintenance cycle is still running":"Maintenance cycle is overdue"};return{...c,...c.lastCheck?{lastCheck:new Date(c.lastCheck)}:{},...c.details?{details:{...c.details}}:{}}}}}async function Xr(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=Je(r),t.warn(`Daemon ${e.name} failed to start: ${C(r)}`),r}}async function ei(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=Je(r),t.error(`Failed to stop daemon: ${e.name}`,r),r}}async function Co(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 xo(e){return{name:e.name,pluginId:e.pluginId,status:e.status,health:e.health}}class At{daemons=new Map;daemonScopes=new Map;daemonTransitions=new Map;logger;static createFresh(e){return new At(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 Xr(t,this.logger);return}let r=b.runSync(E.make()),i=b.acquireRelease(b.promise(()=>Xr(t,this.logger)),()=>b.promise(()=>ei(t,this.logger)));try{await b.runPromise(E.provide(i,r)),this.daemonScopes.set(e,r)}catch(n){throw await b.runPromise(E.close(r,k.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 ei(t,this.logger);return}this.daemonScopes.delete(e),await b.runPromise(E.close(r,k.void))}async checkHealth(e){let t=this.daemons.get(e);if(!t)throw Error(`Daemon not registered: ${e}`);return Co(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(xo)}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(s){if(r??=Je(s),!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),s=()=>{if(n.pending--,n.pending===0)this.daemonTransitions.delete(e)},a=o.then(s,s);return n.tail=a,n.lastKind=t,n.lastPromise=o,o}}var tp=l.object({projectionId:l.string().min(1),reason:l.string().min(1),openedAt:l.number().int().nonnegative(),expiresAt:l.number().int().nonnegative()}),rp=8,ip=32,np=128,op=5,sp=600000,ap=600000,cp=1000,lp="shell.projection-circuits";class jt{operationContext;options;circuitStore;roots=new Map;reservedJobs=new Map;circuits=new Map;projections;static createFresh(e,t={}){return new jt(e,t)}constructor(e,t){this.operationContext=e,this.options={maxDerivationDepth:t.maxDerivationDepth??rp,maxJobsPerRoot:t.maxJobsPerRoot??ip,maxMutationsPerRoot:t.maxMutationsPerRoot??np,repeatedTargetLimit:t.repeatedTargetLimit??op,retentionMs:t.retentionMs??sp,circuitOpenMs:t.circuitOpenMs??ap,maxTrackedRoots:t.maxTrackedRoots??cp,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:lp,schema:tp})}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((d)=>d===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,s=this.reservedJobs.get(n)??0;if(o+s+1>this.options.maxJobsPerRoot)await this.rejectAndOpen(t,`Root ${n} exceeded projection job budget ${this.options.maxJobsPerRoot}`,r);this.reservedJobs.set(n,s+1);let a=!1,c=(d)=>{if(a)return;if(a=!0,this.releaseJobReservation(n),!d)return;let u=this.options.now(),p=this.getRootCounters(n,u);p.jobs++,p.updatedAt=u};return{commit:()=>c(!0),rollback:()=>c(!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}`,s=(n.targetMutations.get(o)??0)+1;if(n.targetMutations.set(o,s),s>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,s],[a,c])=>s.updatedAt-c.updatedAt||o.localeCompare(a))[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 dp={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 ke(e){return dp[e??"combined"]}var Io=[Dt.created,Dt.updated,Dt.deleted];function To(e,t,r){let i=Io.map((o)=>e.subscribe(o,(s)=>(t.send({type:o,payload:s.payload}),{success:!0}))),n=t.onEvent((o)=>{if(!Io.includes(o.type))return;e.deliverPeer(o.type,o.payload).catch((s)=>{r.warn(`Failed to deliver peer event ${o.type}`,{error:s})})});return()=>{for(let o of i)o();n()}}var up=20,pp=0.5,mp=0.06,gp=5;function ko(e){return async({answer:t})=>{let i=(await e.entityService.search({query:t,options:{limit:up,minScore:pp,visibilityScope:A("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-mp).slice(0,gp).map(({entity:o})=>Eo(o,e))}}function fp(e,t,r,i,n){return[zo,Oo,Mo].map((o)=>e.observe(o.name,async(s)=>{let a=o.schema.safeParse(s.payload);if(a.success&&a.data.entityType===t&&(r===null||a.data.entityId===r)){await i();let c=o.name.replace("entity:","");n.debug(`${t} entity ${c}, cache refreshed`)}return{success:!0}}))}function Ao(e,t,r,i){return fp(e,t,t,async()=>{await r(),await je(e,Lo,{entityType:t},"shell")},i)}async function hp(e,t,r){let i=yp(e.kind);if(!i)return null;try{let n=t.scoped({namespace:i,refKind:e.kind,routePath:""});return vp(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 yp(e){return e===Ae.refKind?Ae.namespace:null}function vp(e,t){let{record:r,content:i}=e;if(bp(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 bp(e){let t=e.toLowerCase();return t.startsWith("text/")||t==="application/json"}function Wo(e){let{config:t,entityService:r,logger:i,messageBus:n,aiService:o,mcpService:s,conversationService:a,runtimeUploadRegistry:c,disposables:d,executionOnly:u=!1}=e,p=Fo.createFresh(r,i,t.identity);d.push(...Ao(n,L.BRAIN_CHARACTER,()=>p.refreshCache(),i));let m=No.createFresh(r,i,t.profile),g=Ho.createFresh(i,async(R)=>{let w=await Pt(n,"shell:canonical-identity-service",R).catch(()=>null);if(!w?.canonicalId)return null;return{userId:w.userId,canonicalId:w.canonicalId,displayName:w.displayName}}),f=Zo({guestPricing:Uo(o.getConfig().model),model:o.getModel(),answerModel:o.getAnswerModel?.(),modelId:o.getConfig().model,webSearch:o.getConfig().webSearch,temperature:o.getConfig().temperature,reasoningEffort:o.getConfig().reasoningEffort,messageBus:n}),h=$o(t.name),v=new bt(t.entityDisplay),y={isCitable:(R)=>v.isCitable(R),urlFor:(R,w)=>v.generateUrl(R,w),siteBaseUrl:t.siteBaseUrl},S=Bo.createFresh(s,a,p,m,i,{agentFactory:f,turnEvents:_o(n),canonicalIdentityResolver:g,entityLinks:y,...e.generationUsage?{generationUsage:e.generationUsage}:{},...e.embeddingUsage?{embeddingUsage:e.embeddingUsage}:{},...t.embedding.enabled?{indexReadiness:r,guestAnswerSources:ko({entityService:r,...y})}:{},uploadAttachmentResolver:(R)=>hp(R,c,i),guestAskedBefore:async(R)=>{let w=await Ge(n,jo,R,"shell:agent-service");return w.status==="answered"?w.answers.find((x)=>x.hit)?.hit:void 0},agentContextProvider:async(R)=>{let w=await Ge(n,Do,R,"shell:agent-service");return w.status==="answered"?w.answers.flatMap((x)=>x.items):[]},...h?{assistantAgentId:h}:{},...t.agentInstructions&&{agentInstructions:t.agentInstructions}});if(d.push(...Ao(n,L.ANCHOR_PROFILE,()=>m.refreshCache(),i)),!u)d.push(n.subscribe(Qe.identityChanged,async()=>(S.invalidateAgent(),{success:!0})));return{identityService:p,profileService:m,canonicalIdentityService:g,agentService:S}}var Ke=T.Service("@brains/job-queue/JobQueueService"),zt=T.Service("@brains/job-queue/BatchJobManager"),Ot=T.Service("@brains/job-queue/JobProgressMonitor"),Mt=T.Service("@brains/job-queue/JobQueueWorker");function Ko(e){return ce(Ke,()=>{let t=e.service??qo.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 Vo(e){let t=!1,r=b.gen(function*(){let i=yield*Ke,n=e.batchJobManager??Go.createFresh(i,e.logger),o=e.jobProgressMonitor??Qo.createFresh(i,e.messageBus,n,e.logger,e.progressMonitorMode),s=e.jobQueueWorker??Jo.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(zt,n).pipe(T.add(Ot,o),T.add(Mt,s))});return{layer:V.effectContext(b.acquireRelease(r,(i)=>t?b.void:Sp(i))),abandon:()=>{t=!0}}}function Sp(e){let t=T.get(e,Mt),r=T.get(e,Ot),i=T.get(e,zt);return b.gen(function*(){let n=yield*b.exit(b.tryPromise({try:()=>t.stop(),catch:(c)=>c})),o=yield*b.exit(b.tryPromise({try:()=>r.stop(),catch:(c)=>c})),s=yield*b.exit(b.tryPromise({try:async()=>{await i.stop()},catch:(c)=>c})),a=[n,o,s].find(k.isFailure);if(a)yield*b.die(de.squash(a.cause))})}function Rp(e,t=(r)=>process.exit(r)){return(r)=>{e.error("Job queue worker requires process restart",{reason:r,exitCode:1}),t(1)}}function Lt(e){let t=b.runSyncExit(E.close(e,k.void));if(k.isFailure(t))throw de.squash(t.cause)}function Yo(e){let t=e.operationContext??Ut.createFresh(),r=b.runSync(E.make()),i,n;try{let o=b.runSync(V.buildWithScope(Ko({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)),s=T.get(o,Ke),a=b.runSync(E.make());i=a;let c=Vo({messageBus:e.messageBus,logger:e.logger,operationContext:t,...e.projectionBatchScope&&{projectionBatchScope:e.projectionBatchScope},onWorkerUnhealthy:Rp(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=c;let d=b.runSync(V.buildWithScope(c.layer.pipe(V.provide(V.succeed(Ke,s))),a)),u=T.get(d,zt),p=T.get(d,Ot),m=T.get(d,Mt),g,f=!1,h=!1;return{batchJobManager:u,jobProgressMonitor:p,jobQueueService:s,jobQueueWorker:m,closeRuntime:()=>(f=!0,g??=b.runPromise(E.close(a,k.void)),g),rollbackRuntime:()=>{if(f)return;f=!0,c.abandon(),Lt(a)},closeDatabase:()=>{if(h)return;h=!0,Lt(r)}}}catch(o){if(i)try{n?.abandon(),Lt(i)}catch(s){e.logger.warn("Failed to release partial job runtime acquisition",s)}try{Lt(r)}catch(s){e.logger.warn("Failed to release partial job database acquisition",s)}throw o}}function es(e){return{deliver:async(t)=>{let r=await wt(e,Xo,{title:t.title,body:t.body,...t.html?{html:t.html}:{}},"shell.recurring-checks");if(r.status==="unavailable")return!1;if(r.status==="failed"||r.data.status!=="sent")throw Error("Recurring alert delivery failed");return!0}}}function rs(e){return{sourceId:"recurring-checks",displayName:"Recurring checks",list:async()=>(await e.listOpenAlerts()).map((t)=>({id:t.id,title:ts(t.title,160),summary:ts(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 ts(e,t){return e.length<=t?e:e.slice(0,t)}function is(e,t){if(t)return t;let r={debug:Ve.DEBUG,info:Ve.INFO,warn:Ve.WARN,error:Ve.ERROR}[e.logging.level];return Ee.createFresh({level:r,context:e.logging.context,format:e.logging.format==="json"?"json":"text",...e.logging.file?{logFile:e.logging.file}:{}})}function ti(e){return{providerKeys:e.ai.providerKeys,model:e.ai.model,temperature:e.ai.temperature,webSearch:e.ai.webSearch,...e.ai.reasoningEffort&&{reasoningEffort:e.ai.reasoningEffort},...e.ai.modelRuntimeUrl?{modelRuntimeUrl:e.ai.modelRuntimeUrl}:{},...e.ai.answerModel?{answerModel:e.ai.answerModel}:{},...e.ai.visionModel?{visionModel:e.ai.visionModel}:{},...e.ai.imageModel?{imageModel:e.ai.imageModel}:{}}}function De(e){return{url:e.url,...e.authToken?{authToken:e.authToken}:{}}}function ks(e){let{config:t,dependencies:r,initializerLogger:i,lifecycle:n,processRole:o,peerChannel:s}=e;i.debug("Initializing Shell services");let a=ke(o),c=is(t,r?.logger),d=r?.operationContext??Ut.createFresh(),u=[],p=Cs.createFresh(!r?.embeddingService),m=r?.embeddingService??Ps.createFresh({providerKeys:t.ai.providerKeys,profile:Rs(t.ai.embeddingModel),runtimeUrl:t.ai.modelRuntimeUrl,logger:c,usage:p}),g=xs.createFresh(),f=r?.aiService??ws.createFresh(ti(t),c,g),h=r?.entityRegistry??ss.createFresh(c),v=r?.messageBus??os.createFresh(c,d);if(s)u.push(To(v,s,c));let y=r?.templateRegistry??cs.createFresh(c),S=r?.dataSourceRegistry??as.createFresh(c),R=r?.renderService??ds.createFresh(y),w=r?.daemonRegistry??At.createFresh(c),x=r?.pluginManager??Es.createFresh(c,w),I=r?.permissionService??new ls(t.permissions,{spaces:t.spaces,entityActionFloor:(G)=>h.getEntityTypeConfig(G).actionPolicy}),M=r?.profileKindRegistry??new Ts(t.profileKind),re=r?.channelRegistry??new gs,U=r?.inboxRegistry??new hs,_=r?.inboxFollowUpRegistry??new ys(c),st=r?.operationalHealthRegistry??new Is,at=r?.accountSettingsRegistry??new ms,ct=new fs,ie=new Rt,lt=r?.attachmentRegistry??vs.createFresh(),$e=r?.runtimeUploadRegistry??bs.createFresh({dataDir:t.dataDir,logger:c}),J=n.buildLayer(bo({config:De(t.runtimeStateDatabase),logger:c,...r?.runtimeStateService&&{service:r.runtimeStateService}})),xe=T.get(J,Kr),ne=r?.projectionRuntimeSupervisor??jt.createFresh(d,{runtimeState:xe}),oe=r?.mcpService??Ss.createFresh(v,c),Ar={},Ud={runFreshBatchScope:(G)=>Ar.current?Ar.current.runFreshBatchScope(G):G()},dt=Yo({dependencies:r,jobQueueConfig:{...De(t.jobQueueDatabase),brainVersion:t.version},workerConcurrency:t.jobQueue.workerConcurrency,messageBus:v,operationContext:d,projectionBatchScope:Ud,projectionAdmission:ne,handlerRegistrationMode:a.handlerRegistrationMode,progressMonitorMode:a.progressMonitorMode,logger:c}),{batchJobManager:$d,jobProgressMonitor:Bd,jobQueueService:jr,jobQueueWorker:_d}=dt;n.addSyncFinalizer(()=>dt.closeDatabase()),n.addSyncFinalizer(()=>dt.rollbackRuntime());let Be=r?.recurringCheckService??new It({brainId:t.siteBaseUrl??t.dataDir,scheduler:new qe,runtimeState:xe,clock:b.runSync(ns.Clock),jobQueue:jr,logger:c,delivery:es(v)});n.addSyncFinalizer(()=>Be.abandon()),U.registerSource("shell.recurring-checks",rs(Be)),n.addSyncFinalizer(()=>U.unregisterPlugin("shell.recurring-checks"));let ln=(G,zr)=>{if(!a.serves)return;w.register(G,zr,"shell"),n.addSyncFinalizer(()=>w.abandon(G))};ln("shell:recurring-checks",{start:()=>Be.start(),stop:()=>Be.stop()});let Zd=n.buildLayer(to({embeddingService:m,embeddingsEnabled:t.embedding.enabled,entityRegistry:h,logger:c,jobQueueService:jr,messageBus:v,mutationAdmission:ne,...r?.projectionRuntime?.now&&{projectionNow:r.projectionRuntime.now},dbConfig:De(t.database),embeddingDbConfig:De(t.embeddingDatabase),...r?.entityService&&{service:r.entityService}})),ut=T.get(Zd,Hr);Ar.current=ut.getProjectionStore();let Fd=n.buildLayer(Xn({dbConfig:De(t.conversationDatabase),logger:c,messageBus:v,...r?.conversationService&&{service:r.conversationService}})),Dr=T.get(Fd,Nr);ln("shell:guest-retention",Po({intervalMs:60000,logger:c,run:async()=>{await Dr.deleteExpiredGuestConversations(100)}})),n.addSyncFinalizer(()=>{for(let G of u.splice(0))try{G()}catch(zr){c.warn("Failed to dispose shell subscription",zr)}});let dn=Vn(I,v),Nd=r?.contentService??new ps({logger:c,entityService:ut,aiService:f,templateRegistry:y,dataSourceRegistry:S,generationAuthorizer:new us(I,dn)}),{identityService:Hd,profileService:Wd,canonicalIdentityService:qd,agentService:Jd}=Wo({config:t,entityService:ut,embeddingService:m,embeddingUsage:p,...!r?.aiService?{generationUsage:g}:{},entityRegistry:h,logger:c,messageBus:v,aiService:f,mcpService:oe,conversationService:Dr,runtimeUploadRegistry:$e,disposables:u,executionOnly:!a.serves});return{logger:c,operationContext:d,projectionRuntimeSupervisor:ne,disposables:u,entityRegistry:h,messageBus:v,renderService:R,daemonRegistry:w,pluginManager:x,templateRegistry:y,dataSourceRegistry:S,mcpService:oe,embeddingService:m,entityService:ut,aiService:f,conversationService:Dr,contentService:Nd,callerAuthorizer:dn,jobQueueService:jr,jobQueueWorker:_d,batchJobManager:$d,jobProgressMonitor:Bd,jobServicesLifecycle:dt,permissionService:I,identityService:Hd,profileService:Wd,canonicalIdentityService:qd,profileKindRegistry:M,channelRegistry:re,inboxRegistry:U,inboxFollowUpRegistry:_,operationalHealthRegistry:st,accountSettingsRegistry:at,authRegistry:ct,atprotoProjectionRegistry:ie,agentService:Jd,attachmentRegistry:lt,runtimeUploadRegistry:$e,runtimeStateService:xe,recurringCheckService:Be}}function Ms(e,t){e.register(ri.name,ri),t.debug("Shell system templates registered")}function Ls(e,t){e.register(Ne.BASE_ENTITY_DISPLAY,{name:"base-entity-display",description:"Display template for base entities",schema:ii,formatter:new As,requiredPermission:"public"}),t.debug("Base entity display template registered")}function Us(e,t){e.registerEntityType(L.NOTE,ii,new js,{projectionSourceRole:"primary"}),t.debug("Fallback base entity adapter registered")}function $s(e,t){let r=new Ds;e.registerEntityType(L.BRAIN_CHARACTER,r.schema,r,{classification:"system",projectionSource:!1,projectionSourceRole:"excluded"}),t.debug("Brain character entity support registered")}function Bs(e,t){let r=new zs;e.registerEntityType(L.ANCHOR_PROFILE,r.schema,r,{classification:"system",projectionSourceRole:"canonical"}),t.debug("Anchor profile entity support registered")}async function _s(e){let{plugins:t,pluginManager:r,logger:i,initOptions:n}=e,o=n?.registrationContext?.executionOnly,s=o?t.filter((a)=>a.type!=="interface"):t;i.debug(`Found ${s.length} plugins to register`);for(let a of s)i.debug(`Registering plugin: ${a.id}`),r.registerPlugin(a);if(await r.initializePlugins(n?.registrationContext),o)await r.registerInterfaceChannels(t.filter((a)=>a.type==="interface"),n.registrationContext);if(!n?.registerOnly)for(let{id:a,error:c}of r.getFailedPlugins()){let d=r.getPlugin(a);if(c instanceof Os||d?.requiresDaemonStartup?.())throw c}i.debug("Plugin initialization complete")}class $t{logger;config;processRole;peerChannel;static createFresh(e,t,r,i){return new $t(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){Ms(e,this.logger)}registerBaseEntityDisplayTemplate(e){Ls(e,this.logger)}registerFallbackBaseEntity(e){Us(e,this.logger)}registerBrainCharacterSupport(e){$s(e,this.logger)}registerAnchorProfileSupport(e){Bs(e,this.logger)}async initializePlugins(e,t){await _s({plugins:this.config.plugins,pluginManager:e,logger:this.logger,initOptions:t})}initializeServices(e,t){return ks({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=Fs.createFresh(t,r);e.registerHandler(Zs.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(L.NOTE))this.registerFallbackBaseEntity(t);this.logger.debug("Shell registration phase complete")}catch(n){throw this.logger.error("Shell initialization failed",n),n}}}var ni=l.strictObject({waveId:l.string().trim().min(1),ruleId:l.string().trim().min(1)});class oi{ruleById;store;coordinator;getJobStatus;onDiagnostic;inputContext;executionContext;reconcileTargets;graphFingerprint;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.graphFingerprint=e.graphFingerprint,this.now=e.now}validateAndParse(e){let t=ni.safeParse(e);return t.success?t.data:null}async onTerminalError(e,t,r){let i=ni.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=ni.parse(e),o=this.ruleById.get(n.ruleId);if(!o){if(await this.settleRetiredRuleJob(n.waveId))return{waveId:n.waveId,ruleId:n.ruleId,outcome:"superseded",inputFingerprint:null,changedTargets:[]};throw Error(`Projection rule "${n.ruleId}" is not executable`)}let[s,a,c,d]=await Promise.all([this.store.listWaveInputs(n.waveId),this.store.listWaveRules(n.waveId),this.store.getWave(n.waveId),this.getJobStatus(t)]);if(!c)throw Error(`Projection wave "${n.waveId}" does not exist`);if(c.status!=="running"&&c.status!=="superseded")throw Error(`Projection wave "${n.waveId}" is not active`);let u=a.find((x)=>x.ruleId===n.ruleId);if(!u)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:(d?.retryCount??0)+1,cutoffGeneration:c.cutoffGeneration};if(await this.recordDiagnostic({...p,event:"attempt-started"}),c.status==="superseded"){let x=await this.store.listPendingInputs();return await this.recordDiagnostic({...p,event:"apply-completed",applyOutcome:"superseded",highestPendingGeneration:Bt(x)}),{waveId:n.waveId,ruleId:o.id,outcome:"superseded",inputFingerprint:null,changedTargets:[]}}if(await this.store.supersedeWaveIfStale(n.waveId,this.now())){let x=await this.store.listPendingInputs();return await this.recordDiagnostic({...p,event:"apply-completed",applyOutcome:"superseded",highestPendingGeneration:Bt(x)}),await this.coordinator.continueAfterSupersession(n.waveId),{waveId:n.waveId,ruleId:o.id,outcome:"superseded",inputFingerprint:null,changedTargets:[]}}let m=Cp(s,a,u.level),g=await o.selectInput({waveId:n.waveId,inputs:m},this.inputContext,i),f=o.fingerprint(g),h={...p,inputFingerprint:f,selectedSourceCount:Pp(g,m)};await this.recordDiagnostic({...h,event:"input-selected"});let v={ruleId:o.id,ruleVersion:o.version,inputFingerprint:f},y=await this.store.getRuleMemo(v);await this.recordDiagnostic({...h,event:"memo-resolved",memoHit:y!==null});let S;if(y)S=y.writeIntents;else{await this.recordDiagnostic({...h,event:"derive-started",memoHit:!1});try{S=await o.derive(g,this.executionContext,i),await this.recordDiagnostic({...h,event:"derive-completed",memoHit:!1})}catch(x){throw await this.recordDiagnostic({...h,event:i.aborted?"derive-cancelled":"derive-failed",memoHit:!1}),x}}let R=await this.store.applyRuleResult({waveId:n.waveId,ruleId:o.id,ruleVersion:o.version,inputFingerprint:f,writeIntents:S,completedAt:this.now()}),w=await this.store.listPendingInputs();if(!R)return await this.recordDiagnostic({...h,event:"apply-completed",memoHit:y!==null,applyOutcome:"superseded",highestPendingGeneration:Bt(w)}),await this.coordinator.continueAfterSupersession(n.waveId),{waveId:n.waveId,ruleId:o.id,outcome:"superseded",inputFingerprint:f,changedTargets:[]};return await this.recordDiagnostic({...h,event:"apply-completed",memoHit:y!==null,applyOutcome:"applied",highestPendingGeneration:Bt(w)}),await this.reconcileTargets(R.changedTargets),await this.coordinator.advanceActiveWave(n.waveId),{waveId:n.waveId,ruleId:o.id,outcome:"applied",inputFingerprint:f,changedTargets:R.changedTargets}}async settleRetiredRuleJob(e){let t=await this.store.getWave(e);if(t?.status==="superseded")return!0;if(t?.status!=="running"||t.graphFingerprint===this.graphFingerprint)return!1;if((await this.store.supersedeWave(e,this.now())).status!=="superseded")return!1;return await this.coordinator.continueAfterSupersession(e),!0}async recordDiagnostic(e){if(!this.onDiagnostic)return;try{await this.onDiagnostic(e)}catch(t){this.executionContext.logger.warn("Projection diagnostics callback failed",t)}}}function Pp(e,t){if(typeof e==="object"&&e!==null&&"sources"in e&&Array.isArray(e.sources))return e.sources.length;return t.length}function Bt(e){if(e.length===0)return null;return e.reduce((t,r)=>Math.max(t,r.generation),e[0]?.generation??0)}function Cp(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((s)=>({sourceType:s.entityType,sourceId:s.entityId,revision:s.contentHash??`deleted:${s.entityType}:${s.entityId}`,operation:s.operation})));return[...i,...n]}function xp(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 ze="shell:projection-rule";class ai{store;queue;graph;ruleById;graphFingerprint;createWaveId;beforeWaveCompletion;scheduleWakeup;onScheduledWakeupError;now;operationQueue=new Ns;scheduledWakeup;constructor(e){this.store=e.store,this.queue=e.queue,this.graph=e.graph,this.ruleById=Ep(e.graph,e.rules),this.graphFingerprint=kp(e.graph,e.rules),this.createWaveId=e.createWaveId,this.beforeWaveCompletion=e.beforeWaveCompletion??(async()=>{}),this.scheduleWakeup=e.scheduleWakeup??Ip,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(si(r))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 s=await this.advanceWave(e);if(si(s))await this.startNextWaveInternal();return s}let t=await this.store.listPendingInputs();if(t.length===0)return this.cancelScheduledWakeup(),null;let r=Tp(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(si(o))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)return this.store.supersedeWave(e.id,this.now());let t=await this.store.listWaveRules(e.id);if(t.length===0){let s=await this.store.listWaveInputs(e.id),a=Ws(this.graph,this.ruleById,s);if(a.length===0)return this.completeWave(e);await this.store.putWaveRules(e.id,a),t=await this.store.listWaveRules(e.id)}if(t.every((s)=>s.status==="completed"))return this.completeWave(e,t);let r=t.find((s)=>s.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:xp(i),failedAt:this.now()});let n=Math.min(...t.filter((s)=>s.status!=="completed").map((s)=>s.level)),o=t.filter((s)=>s.level===n&&s.status==="pending");return await Promise.all(o.map((s)=>this.enqueueRule(e.id,s))),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:ze,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 si(e){return e.status==="completed"||e.status==="superseded"}function Ip(e,t){let r=setTimeout(()=>{t()},e);return()=>clearTimeout(r)}function Tp(e,t,r){let n=Ws(e,t,r).reduce((s,a)=>Math.max(s,t.get(a.ruleId)?.sourceChangeBatchDelayMs??0),0);if(n===0)return 0;return r.reduce((s,a)=>Math.max(s,a.markedAt),0)+n}function Ep(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 kp(e,t){return Hs({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 Ws(e,t,r){let i=new Map(e.projections.map((c)=>[c.id,c])),n=qs(e,(c)=>[c.from,c.to]),o=new Set(e.projections.filter((c)=>Ap(c,r)).map((c)=>c.id)),s=[...o];while(s.length>0){let c=s.flatMap((d)=>n.get(d)??[]).filter((d)=>i.has(d)&&!o.has(d));for(let d of c)o.add(d);s=[...new Set(c)].sort()}let a=jp(e,o);return[...o].map((c)=>{let d=i.get(c),u=t.get(c),p=a.get(c);if(!d||!u||p===void 0)throw Error(`Cannot plan projection rule "${c}"`);return{ruleId:c,targetType:d.targetType,level:p}}).sort((c,d)=>c.level-d.level||c.ruleId.localeCompare(d.ruleId))}function Ap(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 jp(e,t){let r=qs(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((s)=>(r.get(s)??[]).every((a)=>i.has(a))).sort();if(o.length===0)throw Error("Reachable projection graph is not acyclic");for(let s of o){let a=(r.get(s)??[]).map((d)=>i.get(d)).filter((d)=>d!==void 0),c=a.length===0?0:Math.max(...a)+1;i.set(s,c),n.delete(s)}}return i}function qs(e,t){let r=new Map;for(let i of e.edges){let n=t(i);if(!n)continue;let[o,s]=n,a=r.get(o);if(a)a.push(s);else r.set(o,[s])}return r}async function Js(e){let t=new ai({store:e.store,queue:e.queue,graph:e.graph,rules:e.rules,createWaveId:e.createWaveId,beforeWaveCompletion:e.beforeWaveCompletion,onScheduledWakeupError:(s)=>e.logger.error("Scheduled projection wakeup failed",s),...e.scheduleWakeup&&{scheduleWakeup:e.scheduleWakeup},now:e.now}),r=new oi({rules:e.rules,store:e.store,coordinator:t,getJobStatus:(s)=>e.queue.getStatus(s),...e.onDiagnostic&&{onDiagnostic:e.onDiagnostic},inputContext:e.inputContext,executionContext:e.executionContext,reconcileTargets:e.reconcileTargets,graphFingerprint:t.graphFingerprint,now:e.now});e.queue.registerHandler(ze,r,"shell");let i=()=>{},n=()=>{};try{if(e.activationMode!=="executor"){let s=async(u)=>{if(u)await e.reconcileBatches?.();await t.startNextWave()},a,c=(u)=>{if(a)return a;let p=Promise.resolve().then(()=>s(u));a=p;let m=()=>{if(a===p)a=void 0};return p.then(m,m),p},d=async()=>{if(a)return;if(await e.store.hasActiveProjectionBatch())return;await c(!1)};i=e.setWakeup(d),await c(!0),n=(e.scheduleSweep??Dp)(e.sweepIntervalMs??1000,async()=>{try{await c(!0)}catch(u){e.logger.error("Projection coordination sweep failed",u)}})}}catch(s){throw n(),i(),e.queue.unregisterHandler(ze),s}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(ze)}}}function Dp(e,t){let r=setInterval(()=>{t()},e);return r.unref(),()=>clearInterval(r)}import{existsSync as wm}from"fs";import{mkdir as Pm,writeFile as Cm}from"fs/promises";import{join as xm,resolve as _a}from"path";function Gs(e,t,r){let i=e.filter((n)=>n.kind==="handler"&&n.method===t);return i.find((n)=>n.match==="exact"&&n.fullPath===r)??i.filter((n)=>n.match==="prefix"&&(r===n.fullPath||r.startsWith(`${n.fullPath.replace(/\/$/,"")}/`))).sort((n,o)=>o.fullPath.length-n.fullPath.length)[0]??i.find((n)=>n.match==="claim"&&n.claims?.(r))}import{resolve as H,join as vm,sep as bm}from"path";var Qs=Symbol();var Ks=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,(r)=>r.toLowerCase())}}).formData();var zp=1e4,_t=(e)=>("headers"in e),Xs=async(e,t=Object.create(null))=>{let{all:r=!1,dot:i=!1}=t,n=(_t(e)?e.headers:e.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();if(n==="multipart/form-data"||n==="application/x-www-form-urlencoded")return Op(e,{all:r,dot:i});return{}};async function Op(e,t){if(!_t(e)&&e.bodyCache.formData)return Vs(await e.bodyCache.formData,t);let r=_t(e)?e.headers:e.raw.headers,i=await e.arrayBuffer(),n=Ks(i,r.get("Content-Type")||"");if(!_t(e))e.bodyCache.formData=n;let o=await n;if(o)return Vs(o,t);return{}}function Vs(e,t){let r=Object.create(null),i={count:0};if(e.forEach((n,o)=>{if(!(t.all||o.endsWith("[]")))r[o]=n;else Mp(r,o,n)}),t.dot)Object.entries(r).forEach(([n,o])=>{if(n.includes("."))Lp(r,n,o,i),delete r[n]});return r}var Mp=(e,t,r)=>{if(e[t]!==void 0)if(Array.isArray(e[t]))e[t].push(r);else e[t]=[e[t],r];else if(!t.endsWith("[]"))e[t]=r;else e[t]=[r]},Lp=(e,t,r,i)=>{if(/(?:^|\.)__proto__\./.test(t))return;let n=e,o=t.split(".",34);if(o.length>33)Ys();o.forEach((s,a)=>{if(a===o.length-1)n[s]=r;else{if(!n[s]||typeof n[s]!=="object"||Array.isArray(n[s])||n[s]instanceof File){if(i.count++>=zp)Ys();n[s]=Object.create(null)}n=n[s]}})},Ys=()=>{throw Error("Nesting limit exceeded")};var li=(e)=>{let t=e.split("/");if(t[0]==="")t.shift();return t},ea=(e)=>{let{groups:t,path:r}=Up(e),i=li(r);return $p(i,t)},Up=(e)=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,i)=>{let n=`@${i}`;return t.push([n,r]),n}),{groups:t,path:e}},$p=(e,t)=>{for(let r=t.length-1;r>=0;r--){let[i]=t[r];for(let n=e.length-1;n>=0;n--)if(e[n].includes(i)){e[n]=e[n].replace(i,t[r][1]);break}}return e},Zt={},ta=(e,t)=>{if(e==="*")return"*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let i=`${e}#${t}`;if(!Zt[i])if(r[2])Zt[i]=t&&t[0]!==":"&&t[0]!=="*"?[i,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)];else Zt[i]=[e,r[1],!0];return Zt[i]}return null},ra=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,(r)=>{try{return t(r)}catch{return r}})}},di=(e)=>ra(e,decodeURI),ui=(e)=>{let t=e.url,r=t.indexOf("/",t.indexOf(":")+4),i=r;for(;i<t.length;i++){let n=t.charCodeAt(i);if(n===37){let o=t.indexOf("?",i),s=t.indexOf("#",i),a=o===-1?s===-1?void 0:s:s===-1?o:Math.min(o,s),c=t.slice(r,a);return di(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(n===63||n===35)break}return t.slice(r,i)};var ia=(e)=>{let t=ui(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},pe=(e,t,...r)=>{if(r.length)t=pe(t,...r);return`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`},Ft=(e)=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),r=[],i="";return t.forEach((n)=>{if(n!==""&&!/\:/.test(n))i+="/"+n;else if(/\:/.test(n))if(n.charCodeAt(n.length-1)===63){if(r.length===0&&i==="")r.push("/");else r.push(i);let o=n.slice(0,-1);i+="/"+o,r.push(i)}else i+="/"+n}),r.filter((n,o,s)=>s.indexOf(n)===o)},Nt=(e)=>e.indexOf("%")!==-1?ra(e,Bp):e,ci=(e)=>{if(e.indexOf("+")!==-1)e=e.replace(/\+/g," ");return Nt(e)},na=(e,t,r)=>{let i=e.indexOf("#",8);if(i!==-1)e=e.slice(0,i);let n;if(!r&&t&&t.indexOf("%")===-1&&t.indexOf("+")===-1){let a=e.indexOf("?",8);if(a===-1)return;if(!e.startsWith(t,a+1))a=e.indexOf(`&${t}`,a+1);while(a!==-1){let c=e.charCodeAt(a+t.length+1);if(c===61){let d=a+t.length+2,u=e.indexOf("&",d);return ci(e.slice(d,u===-1?void 0:u))}else if(c==38||isNaN(c))return"";a=e.indexOf(`&${t}`,a+1)}if(n=/[%+]/.test(e),!n)return}let o=Object.create(null);n??=/[%+]/.test(e);let s=e.indexOf("?",8);while(s!==-1){let a=e.indexOf("&",s+1),c=e.indexOf("=",s);if(c>a&&a!==-1)c=-1;let d=e.slice(s+1,c===-1?a===-1?void 0:a:c);if(n)d=ci(d);if(s=a,d==="")continue;let u;if(c===-1)u="";else if(u=e.slice(c+1,a===-1?void 0:a),n)u=ci(u);if(r){if(!(o[d]&&Array.isArray(o[d])))o[d]=[];o[d].push(u)}else o[d]??=u}return t?o[t]:o},oa=na,sa=(e,t)=>na(e,t,!0),Bp=decodeURIComponent;var aa=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(e,t="/",r=[[]]){this.raw=e,this.path=t,this.#e=r}param(e){return e?this.#r(e):this.#o()}#r(e){let t=this.#e[0][this.routeIndex]?.[1][e],r=this.#i(t);return r&&Nt(r)}#o(){let e={},t=Object.keys(this.#e[0][this.routeIndex]?.[1]??{});for(let r of t){let i=this.#i(this.#e[0][this.routeIndex][1][r]);if(i!==void 0)e[r]=Nt(i)}return e}#i(e){return this.#e[1]?this.#e[1][e]:e}query(e){return oa(this.url,e)}queries(e){return sa(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t=Object.create(null);return this.raw.headers.forEach((r,i)=>{t[i]=r}),t}async parseBody(e){return Xs(this,e)}#n=(e)=>{let{bodyCache:t,raw:r}=this,i=t[e];if(i)return i;for(let n in t)return t[n].then((o)=>{if(n==="json")o=JSON.stringify(o);let s=n==="formData"?void 0:r.headers.get("content-type");return new Response(o,{headers:s?{"Content-Type":s}:void 0})[e]()});return t[e]=r[e]()};json(){return this.#n("text").then((e)=>JSON.parse(e))}text(){return this.#n("text")}arrayBuffer(){return this.#n("arrayBuffer")}bytes(){return this.#n("arrayBuffer").then((e)=>new Uint8Array(e))}blob(){return this.#n("blob")}formData(){return this.#n("formData")}addValidatedData(e,t){(this.#t??={})[e]=t}valid(e){return this.#t?.[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[Qs](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,e]])=>e)}get routePath(){return this.#e[0].map(([[,e]])=>e)[this.routeIndex].path}};var ca={Stringify:1,BeforeStream:2,Stream:3},la=(e,t)=>{let r=new String(e);return r.isEscaped=!0,r.callbacks=t,r};var pi=async(e,t,r,i,n)=>{if(typeof e==="object"&&!(e instanceof String)){if(!(e instanceof Promise))e=e.toString();if(e instanceof Promise)e=await e}let o=e.callbacks;if(!o?.length)return Promise.resolve(e);if(n)n[0]+=e;else n=[e];let s=Promise.all(o.map((a)=>a({phase:t,buffer:n,context:i}))).then((a)=>Promise.all(a.filter(Boolean).map((c)=>pi(c,t,!1,i,n))).then(()=>n[0]));if(r)return la(await s,o);else return s};var _p="text/plain; charset=UTF-8",mi=(e,t)=>({"Content-Type":e,...t}),Ye=(e,t)=>new Response(e,t),gi=class{#t;#e;env={};#r;finalized=!1;error;#o;#i;#n;#d;#c;#l;#a;#u;#p;constructor(e,t){if(this.#t=e,t)this.#i=t.executionCtx,this.env=t.env,this.#l=t.notFoundHandler,this.#p=t.path,this.#u=t.matchResult}get req(){return this.#e??=new aa(this.#t,this.#p,this.#u),this.#e}get event(){if(this.#i&&"respondWith"in this.#i)return this.#i;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#i)return this.#i;else throw Error("This context has no ExecutionContext")}get res(){return this.#n||=Ye(null,{headers:this.#a??=new Headers})}set res(e){if(this.#n&&e){e=Ye(e.body,e);for(let[t,r]of this.#n.headers.entries()){if(t==="content-type")continue;if(t==="set-cookie"){let i=this.#n.headers.getSetCookie();e.headers.delete("set-cookie");for(let n of i)e.headers.append("set-cookie",n)}else e.headers.set(t,r)}}this.#n=e,this.finalized=!0}render=(...e)=>(this.#c??=(t)=>this.html(t),this.#c(...e));setLayout=(e)=>this.#d=e;getLayout=()=>this.#d;setRenderer=(e)=>{this.#c=e};header=(e,t,r)=>{if(this.finalized)this.#n=Ye(this.#n.body,this.#n);let i=this.#n?this.#n.headers:this.#a??=new Headers;if(t===void 0)i.delete(e);else if(r?.append)i.append(e,t);else i.set(e,t)};status=(e)=>{this.#o=e};set=(e,t)=>{this.#r??=new Map,this.#r.set(e,t)};get=(e)=>this.#r?this.#r.get(e):void 0;get var(){if(!this.#r)return{};return Object.fromEntries(this.#r)}#s(e,t,r){let i=this.#n?new Headers(this.#n.headers):this.#a;if(typeof t==="object"&&t.headers){i??=new Headers;for(let[o,s]of new Headers(t.headers))if(o==="set-cookie")i.append(o,s);else i.set(o,s)}if(r){if(!i){let o=0;for(let s in r)if(++o>1||typeof r[s]!=="string"){i=new Headers;break}}if(i)for(let o in r){let s=r[o];if(typeof s==="string")i.set(o,s);else{i.delete(o);for(let a of s)i.append(o,a)}}}let n=typeof t==="number"?t:t?.status??this.#o;return Ye(e,{status:n,headers:i??r})}newResponse=(...e)=>this.#s(...e);body=(e,t,r)=>this.#s(e,t,r);text=(e,t,r)=>!this.#a&&!this.#o&&!t&&!r&&!this.finalized?new Response(e):this.#s(e,t,mi(_p,r));json=(e,t,r)=>this.#s(JSON.stringify(e),t,mi("application/json",r));html=(e,t,r)=>{let i=(n)=>this.#s(n,t,mi("text/html; charset=UTF-8",r));return typeof e==="object"?pi(e,ca.Stringify,!1,{}).then(i):i(e)};redirect=(e,t)=>{let r=String(e);return this.header("Location",!/[^\x00-\xFF]/.test(r)?r:encodeURI(r)),this.newResponse(null,t??302)};notFound=()=>(this.#l??=()=>Ye(),this.#l(this))};var fi=(e,t,r)=>(i,n)=>{let o=-1;return s(0);async function s(a){if(a<=o)throw Error("next() called multiple times");o=a;let c,d=!1,u;if(e[a])u=e[a][0][0],i.req.routeIndex=a;else u=a===e.length&&n||void 0;if(u)try{c=await u(i,()=>s(a+1))}catch(p){if(p instanceof Error&&t)i.error=p,c=await t(p,i),d=!0;else throw p}else if(i.finalized===!1&&r)c=await r(i);if(c&&(i.finalized===!1||d))i.res=c;return i}};var da=["get","post","put","delete","options","patch","query"],Ht="Can not add a route since the matcher is already built.",Wt=class extends Error{};var hi="__COMPOSED_HANDLER";var Zp=(e)=>e.text("404 Not Found",404),ua=(e,t)=>{if("getResponse"in e){let r=e.getResponse();return t.newResponse(r.body,r)}return console.error(e),t.text("Internal Server Error",500)},pa=class e{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...da,"all"].forEach((n)=>{this[n]=(o,...s)=>{let a=n.toUpperCase();if(typeof o==="string")this.#t=o;else this.#o(a,this.#t,o);return s.forEach((c)=>{this.#o(a,this.#t,c)}),this}}),this.on=(n,o,...s)=>{for(let a of[o].flat()){this.#t=a;for(let c of[n].flat()){let d=c.toUpperCase();for(let u of s)this.#o(d,this.#t,u)}}return this},this.use=(n,...o)=>{if(typeof n==="string")this.#t=n;else this.#t="*",o.unshift(n);return o.forEach((s)=>{this.#o("ALL",this.#t,s)}),this};let{strict:r,...i}=t;Object.assign(this,i),this.getPath=r??!0?t.getPath??ui:ia}#e(){let t=new e({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=Zp;errorHandler=ua;route(t,r){let i=this.basePath(t);return r.routes.map((n)=>{let o;if(r.errorHandler===ua)o=n.handler;else o=async(s,a)=>(await fi([],r.errorHandler)(s,()=>n.handler(s,a))).res,o[hi]=n.handler;i.#o(n.method,n.path,o,n.basePath)}),this}basePath(t){let r=this.#e();return r._basePath=pe(this._basePath,t),r}onError=(t)=>(this.errorHandler=t,this);notFound=(t)=>(this.#r=t,this);mount(t,r,i){let n,o;if(i)if(typeof i==="function")o=i;else if(o=i.optionHandler,i.replaceRequest===!1)n=(c)=>c;else n=i.replaceRequest;let s=o?(c)=>{let d=o(c);return Array.isArray(d)?d:[d]}:(c)=>{let d=void 0;try{d=c.executionCtx}catch{}return[c.env,d]};n||=(()=>{let c=pe(this._basePath,t),d=c==="/"?0:c.length;return(u)=>{let p=new URL(u.url);return p.pathname=this.getPath(u).slice(d)||"/",new Request(p,u)}})();let a=async(c,d)=>{let u=await r(n(c.req.raw),...s(c));if(u)return u;await d()};return this.#o("ALL",pe(t,"*"),a),this}#o(t,r,i,n){r=pe(this._basePath,r);let o={basePath:n!==void 0?pe(this._basePath,n):this._basePath,path:r,method:t,handler:i};this.router.add(t,r,[i,o]),this.routes.push(o)}#i(t,r){if(t instanceof Error)return this.errorHandler(t,r);throw t}#n(t,r,i,n){if(n==="HEAD")return(async()=>new Response(null,await this.#n(t,r,i,"GET")))();let o=this.getPath(t,{env:i}),s=this.router.match(n,o),a=new gi(t,{path:o,matchResult:s,env:i,executionCtx:r,notFoundHandler:this.#r});if(s[0].length===1){let d;try{d=s[0][0][0][0](a,async()=>{a.res=await this.#r(a)})}catch(u){return this.#i(u,a)}return d instanceof Promise?d.then((u)=>u||(a.finalized?a.res:this.#r(a))).catch((u)=>this.#i(u,a)):d??this.#r(a)}let c=fi(s[0],this.errorHandler,this.#r);return(async()=>{try{let d=await c(a);if(!d.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return d.res}catch(d){return this.#i(d,a)}})()}fetch=(t,...r)=>this.#n(t,r[1],r[0],t.method);request=(t,r,i,n)=>{if(t instanceof Request)return this.fetch(r?new Request(t,r):t,i,n);return t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${pe("/",t)}`,r),i,n)};fire=()=>{addEventListener("fetch",(t)=>{t.respondWith(this.#n(t.request,t,void 0,t.request.method))})}};var j=()=>Object.create(null);var qt=[];function yi(e,t){let r=this.buildAllMatchers(),i=(n,o)=>{let s=r[n]||r.ALL,a=s[2][o];if(a)return a;let c=o.match(s[0]);if(!c)return[[],qt];let d=c.indexOf("",1);return[s[1][d],c]};return this.match=i,i(e,t)}var vi="[^/]+";var bi="(?:|/.*)",me=Symbol(),ma=new Set(".\\+*[^]$()");function Fp(e,t){if(e.length===1)return t.length===1?e<t?-1:1:-1;if(t.length===1)return 1;if(e===".*"||e==="(?:|/.*)")return t==="(?:|/.*)"?-1:1;else if(t===".*"||t==="(?:|/.*)")return-1;if(e==="[^/]+")return 1;else if(t==="[^/]+")return-1;return e.length===t.length?e<t?-1:1:t.length-e.length}var ga=class e{#t;#e;#r=j();insert(t,r,i,n,o){let s=this;for(let a=0,c=t.length;a<c;a++){let d=t[a],u=d.length===1?d==="*"?a===c-1?["","",".*"]:["","",vi]:null:d==="/*"?["","",bi]:d.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),p;if(u){let m=u[1],g=u[2]||"[^/]+";if(m&&u[2]){if(g===".*")throw me;if(g=g.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(g))throw me;if(g.length===1&&ma.has(g))throw me}if(p=s.#r[g],!p){if(g!==".*"&&g!=="(?:|/.*)"){for(let f in s.#r)if((g.length>1||f.length>1)&&f!==".*"&&f!=="(?:|/.*)")throw me}p=s.#r[g]=new e}if(m!=="")p.#e??=n.varIndex++,i.push([m,p.#e])}else if(p=s.#r[d],!p){for(let m in s.#r)if(m.length>1&&m!==".*"&&m!=="(?:|/.*)")throw me;p=s.#r[d]=new e}s=p}if(s.#t!==void 0)throw me;s.#t=o?-1:r}buildRegExpStr(){let t=Object.keys(this.#r).sort(Fp).map((r)=>{let i=this.#r[r],n=i.buildRegExpStr();return n===""?"":(typeof i.#e==="number"?`(${r})@${i.#e}`:ma.has(r)?`\\${r}`:r)+n}).filter(Boolean);if(typeof this.#t==="number"&&this.#t!==-1)t.unshift(`#${this.#t}`);if(t.length===0)return"";if(t.length===1)return t[0];return"(?:"+t.join("|")+")"}};var Si=class{#t={varIndex:0};#e=new ga;#r=0;paths=j();insert(e,t){if(t){this.#e.insert(e.split(""),0,[],this.#t,!0);return}let r=[],i=[],n=e;for(let s=0;;){let a=!1;if(n=n.replace(/\{[^}]+\}/g,(c)=>{let d=`@\\${s}`;return i[s]=[d,c],s++,a=!0,d}),!a)break}let o=n.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let s=i.length-1;s>=0;s--){let[a]=i[s];for(let c=o.length-1;c>=0;c--)if(o[c].indexOf(a)!==-1){o[c]=o[c].replace(a,i[s][1]);break}}this.#e.insert(o,this.#r,r,this.#t,!1),this.paths[e]=[this.#r++,r]}buildRegExp(){let e=this.#e.buildRegExpStr();if(e==="")return[/^$/,[],[]];let t=0,r=[],i=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(n,o,s)=>{if(o!==void 0)return r[++t]=Number(o),"$()";if(s!==void 0)return i[Number(s)]=++t,"";return""}),[new RegExp(`^${e}`),r,i]}};var fa=j();function ha(e){return fa[e]??=new RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(t,r)=>r?`\\${r}`:t==="/*"?bi:t==="*"?".*":`/:${vi}`)}$`)}function Jt(e,t){for(let r of Object.keys(e).sort((i,n)=>n.length-i.length))if(ha(r).test(t))return[...e[r]]}var Gt=class{name="RegExpRouter";#t;#e;#r;constructor(){this.#t={["ALL"]:j()},this.#e={["ALL"]:j()},this.#r={["ALL"]:new Si}}#o(e,t){try{this.#r[e].insert(t,!/\*|\/:/.test(t))}catch(r){throw r===me?new Wt(t):r}}add(e,t,r){let i=this.#t,n=this.#e;if(!i)throw Error(Ht);if(!i[e]){this.#r[e]=new Si;for(let a of[i,n]){a[e]=j();for(let c in a.ALL)a[e][c]=[...a.ALL[c]],this.#o(e,c)}}if(t==="/*")t="*";let o=e==="ALL"?Object.keys(i):[e];if(/\*$/.test(t)){let a=ha(t);for(let c of o)if(!i[c][t])this.#o(c,t),i[c][t]=Jt(i[c],t)||Jt(i.ALL,t)||[];for(let c of[i,n])for(let d of o)for(let u in c[d])a.test(u)&&c[d][u].push([r,t]);return}let s=Ft(t)||[t];for(let a of s)for(let c of o){if(!n[c][a])this.#o(c,a),n[c][a]=Jt(i[c],a)||Jt(i.ALL,a)||[];n[c][a].push([r,a])}}match=yi;buildAllMatchers(){let e=j();for(let t of Object.keys(this.#e))e[t]=this.#i(t);return this.#t=this.#e=this.#r=void 0,fa=j(),e}#i(e){let t=this.#t[e],r=this.#e[e],i=this.#r[e],n=j(),o=[],[s,a,c]=i.buildRegExp();for(let d of[t,r])for(let u in d){let p=d[u],m=i.paths[u];if(!m){n[u]=[p.map(([g])=>[g,j()]),qt];continue}o[m[0]]=p.map(([g,f])=>[g,i.paths[f][1].reduceRight((h,[v],y)=>(h[v]=c[m[1][y][1]],h),j())])}return[s,a.map((d)=>o[d]),n]}};var ya=class{name="SmartRouter";#t=[];#e=[];constructor(e){this.#t=e.routers}add(e,t,r){if(!this.#e)throw Error(Ht);this.#e.push([e,t,r])}match(e,t){if(!this.#e)throw Error("Fatal error");let r=this.#t,i=this.#e,n=r.length,o=0,s;for(;o<n;o++){let a=r[o];try{for(let c=0,d=i.length;c<d;c++)a.add(...i[c]);s=a.match(e,t)}catch(c){if(c instanceof Wt)continue;throw c}this.match=a.match.bind(a),this.#t=[a],this.#e=void 0;break}if(o===n)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,s}get activeRouter(){if(this.#e||this.#t.length!==1)throw Error("No active router has been determined yet.");return this.#t[0]}};var Ri=j(),Np=0,va=class e{#t=[];#e=j();#r=[];#o;#i=Ri;insert(t,r,i){let n=this,o=ea(r),s=new Set,a=0;for(let c of o){let d=o[++a],u=ta(c,d)||(d===void 0&&c&&c.indexOf("*")===c.length-1?c:null),p=Array.isArray(u),m=p?u[0]:u||c,g=n.#e[m]||=new e;if(u&&!g.#o)g.#o=u,n.#r.push(g);if(n=g,p)s.add(u[1])}n.#t.push({[t]:{handler:i,possibleKeys:[...s],score:++Np}})}#n(t,r,i,n,o){for(let s=0,a=r.#t.length;s<a;s++){let c=r.#t[s],d=c[i]||c.ALL;if(d){d.params=j(),t.push(d);for(let u=0,p=d.possibleKeys.length;u<p;u++){let m=d.possibleKeys[u];d.params[m]=o?.[m]&&!u?o[m]:n[m]??o?.[m]}}}}search(t,r){let i=[];this.#i=Ri;let n=[this],o=li(r),s=[],a=o.length,c=null;for(let d=0;d<a;d++){let u=o[d],p=d===a-1,m=[];for(let f=0,h=n.length;f<h;f++){let v=n[f],y=v.#e[u];if(y)if(y.#i=v.#i,p){if(y.#e["*"])this.#n(i,y.#e["*"],t,v.#i);this.#n(i,y,t,v.#i)}else m.push(y);for(let S of v.#r){let R=S.#o,w=v.#i===Ri?{}:{...v.#i};if(typeof R==="string"){if(R==="*"||u.startsWith(R.slice(0,-1))){if(this.#n(i,S,t,v.#i),R==="*")S.#i=w,m.push(S)}continue}let[,x,I]=R;if(!u&&I===!0)continue;if(I!==!0){if(!c){c=[];let U=r[0]==="/"?1:0;for(let _=0;_<a;_++)c[_]=U,U+=o[_].length+1}let M=r.slice(c[d]),re=I.exec(M);if(re){if(w[x]=re[0],this.#n(i,S,t,v.#i,w),re[0].length===M.length&&S.#e["*"])this.#n(i,S.#e["*"],t,v.#i,w);for(let U in S.#e){S.#i=w;let _=re[0].match(/\//g)?.length??0;(s[_]||=[]).push(S);break}continue}}if(I===!0||I.test(u))if(w[x]=u,p){if(this.#n(i,S,t,w,v.#i),S.#e["*"])this.#n(i,S.#e["*"],t,w,v.#i)}else S.#i=w,m.push(S)}}let g=s.shift();n=g?m.concat(g):m}if(i[1])i.sort((d,u)=>d.score-u.score);return[i.map(({handler:d,params:u})=>[d,u])]}};var wi=class{name="TrieRouter";#t=new va;add(e,t,r){for(let i of Ft(t)||[t])this.#t.insert(e,i,r)}match(e,t){return this.#t.search(e,t)}};var Pi=class extends pa{constructor(e={}){super(e);this.router=e.router??new ya({routers:[new Gt,new wi]})}};var Qt=(e)=>("server"in e.env)?e.env.server:e.env;var Oe=/^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|msgpack|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|vnd\.msgpack|wasm|x-httpd-php|x-javascript|x-msgpack|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml|msgpack))(?:[;\s]|$)/i;var Ci=(e,t=Hp)=>{let r=e.match(/\.([a-zA-Z0-9]+?)$/);if(!r)return;return t[r[1].toLowerCase()]};var Hp={aac:"audio/aac",avi:"video/x-msvideo",avif:"image/avif",av1:"video/av1",bin:"application/octet-stream",bmp:"image/bmp",css:"text/css; charset=utf-8",csv:"text/csv; charset=utf-8",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gif:"image/gif",gz:"application/gzip",htm:"text/html; charset=utf-8",html:"text/html; charset=utf-8",ico:"image/x-icon",ics:"text/calendar; charset=utf-8",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript; charset=utf-8",json:"application/json",jsonld:"application/ld+json",map:"application/json",mid:"audio/x-midi",midi:"audio/x-midi",mjs:"text/javascript; charset=utf-8",mp3:"audio/mpeg",mp4:"video/mp4",mpeg:"video/mpeg",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",opus:"audio/opus",otf:"font/otf",pdf:"application/pdf",png:"image/png",rtf:"application/rtf",svg:"image/svg+xml; charset=utf-8",tif:"image/tiff",tiff:"image/tiff",ts:"video/mp2t",ttf:"font/ttf",txt:"text/plain; charset=utf-8",wasm:"application/wasm",webm:"video/webm",weba:"audio/webm",webmanifest:"application/manifest+json",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml; charset=utf-8",xml:"application/xml; charset=utf-8",zip:"application/zip","3gp":"video/3gpp","3g2":"video/3gpp2",gltf:"model/gltf+json",glb:"model/gltf-binary"};var ba=(...e)=>{let t=e.filter((n)=>n!=="").join("/");t=t.replace(/(?<=\/)\/+/g,"");let r=t.split("/"),i=[];for(let n of r)if(n===".."&&i.length>0&&i.at(-1)!=="..")i.pop();else if(n!==".")i.push(n);return i.join("/")||"."};var Sa={br:".br",zstd:".zst",gzip:".gz"},Wp=Object.keys(Sa),qp="index.html",Ra=(e)=>{let t=e.root??"./",r=e.path,i=e.join??ba;return async(n,o)=>{if(n.finalized)return o();let s;if(e.path)s=e.path;else try{if(!e.allowPercentInPath&&n.req.path.includes("%"))throw Error();if(s=di(n.req.path),/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}|\\/.test(s))throw Error()}catch{return await e.onNotFound?.(n.req.path,n),o()}let a=i(t,!r&&e.rewriteRequestPath?e.rewriteRequestPath(s):s);if(e.isDir&&await e.isDir(a))a=i(a,qp);let c=e.getContent,d=await c(a,n);if(d instanceof Response)return n.newResponse(d.body,d);if(d!=null){let u=e.mimes&&Ci(a,e.mimes)||Ci(a);if(n.header("Content-Type",u||"application/octet-stream"),e.precompressed&&(!u||Oe.test(u))){let p=new Set(n.req.header("Accept-Encoding")?.split(",").map((m)=>m.trim()));for(let m of Wp){if(!p.has(m))continue;let g=await c(a+Sa[m],n);if(g){d=g,n.header("Content-Encoding",m),n.header("Vary","Accept-Encoding",{append:!0});break}}}return await e.onFound?.(a,n),n.body(d)}await e.onNotFound?.(a,n),await o()}};import{stat as Jp}from"fs/promises";import{join as Gp}from"path";var xi=(e={})=>async function(r,i){return Ra({...e,getContent:async(s)=>{let a=Bun.file(s);return await a.exists()?a:null},join:Gp,isDir:async(s)=>{let a;try{a=(await Jp(s)).isDirectory()}catch{}return a}})(r,i)};var wa="x-hono-disable-ssg",ew=(()=>{try{return new Response("SSG is disabled",{status:404,headers:{[wa]:"true"}})}catch{return null}})();var{write:Nw}=Bun;var Pa=(e)=>(...t)=>{if(typeof t[0]==="function"){let[r,i]=t;return async function(o,s){let a=await e(o,await r(o),i);if(a)return a;await s()}}else{let[r,i,n]=t;return(async()=>{let o=await e(r,i,n);if(!o)throw Error("Failed to upgrade WebSocket");return o})()}};var Yp=Pa((e,t)=>{let r=Qt(e);if(!r)throw TypeError("env has to include the 2nd argument of fetch.");if(r.upgrade(e.req.raw,{data:{events:t,url:new URL(e.req.url),protocol:e.req.header("sec-websocket-protocol")?.split(",")[0]?.trim()??""}}))return new Response(null)});var xa=(e)=>e===32||e===9||e===10||e===13,Kt=(e,t)=>{while(t<e.length){if(!xa(e.charCodeAt(t)))break;t++}return t},Xe=(e,t)=>{while(t>0){if(!xa(e.charCodeAt(t-1)))break;t--}return t},Ca=(e,t)=>{while(t<e.length){let r=e.charCodeAt(t);if(r===59)return[t+1,!0];if(r===44)return[t+1,!1];t++}return[t,!1]},Xp=(e,t)=>{let r=t,i=!1;while(r<e.length){let n=e.charCodeAt(r);if(i&&n===92)r++;else if(n===34)i=!i;else if(!i&&n===44)return r+1;r++}return r},em=(e,t)=>{t=Kt(e,t);let r=t,i,n,o=!1;while(r<e.length){let c=e.charCodeAt(r);if(c===61){i=e.slice(t,Xe(e,r)),r++;break}if(c===59)return[r+1,void 0,void 0,!0];if(c===44)return[r+1,void 0,void 0,!1];r++}if(i===void 0)return[r,void 0,void 0,!1];if(r=Kt(e,r),e.charCodeAt(r)===61){let c=Ca(e,r+1);return[c[0],i,void 0,c[1]]}let s=!1,a=r;while(r<e.length){let c=e.charCodeAt(r);if(s&&c===92)r++;else if(c===34){if(s){let d=Kt(e,r+1),u=e.charCodeAt(d);if(d<e.length&&!(u===59||u===44)){let p=Ca(e,d);return[p[0],i,void 0,p[1]]}if(n=e.slice(a+1,r),n.includes("\\"))n=n.replace(/\\(.)/g,"$1");if(u===44)return[d+1,i,n,!1];if(u===59)o=!0,d++;r=d;break}s=!0}else if(!s&&(c===59||c===44)){if(n=e.slice(a,Xe(e,r)),c===59)o=!0;r++;break}r++}return[r,i,n??e.slice(a,Xe(e,r)),o]},tm=(e,t)=>{let r={type:"",params:Object.create(null),q:1};t=Kt(e,t);let i=t;while(i<e.length){let a=e.charCodeAt(i);if(a===59||a===44){if(r.type=e.slice(t,Xe(e,i)),i++,a===44)return[i,r.type?r:void 0];if(!r.type)return[Xp(e,i),void 0];break}i++}if(!r.type)return r.type=e.slice(t,Xe(e,e.length)),[e.length,r.type?r:void 0];let n,o,s;while(i<e.length){if([i,n,o,s]=em(e,i),n&&o)r.params[n]=o;if(!s)break}return[i,r]},Ia=(e)=>{if(!e)return[];let t=[],r=0,i,n=!1,o;while(r<e.length)if([r,i]=tm(e,r),i){if(i.q=rm(i.params.q??i.params.Q),t.push(i),o&&o.q<i.q)n=!0;o=i}if(n)t.sort((s,a)=>a.q-s.q);return t},rm=(e)=>{if(e===void 0)return 1;if(e==="")return 1;if(e==="NaN")return 0;let t=Number(e);if(Number.isNaN(t))return 1;if(t<0)return 0;if(t>1)return 1;return t};var im=["gzip","deflate"],nm=/(?:^|,)\s*?no-transform\s*?(?:,|$)/i,om=(e,t)=>{if(e===void 0)return;let r=Ia(e),i=r.find((o)=>o.type==="*")?.q,n;for(let o of t){let s=r.find((c)=>c.type.toLowerCase()===o),a=s?s.q:i??0;if(a===1)return o;else if(a>0&&(!n||a>n.q))n={encoding:o,q:a}}return n?.encoding},sm=/(?:^|,)\s*accept-encoding\s*(?:,|$)/i,Ta=(e)=>{let t=e?.threshold??1024,r=e?.encoding?[e.encoding]:im,i=e?.contentTypeFilter??Oe,n=typeof i==="function"?(o)=>{let s=o.headers.get("Content-Type");return s&&i(s)}:(o)=>{let s=o.headers.get("Content-Type");return s&&i.test(s)};return async function(s,a){await a();let c=s.res.headers.get("Content-Length");if(s.res.status===206||s.res.headers.has("Content-Encoding")||s.res.headers.has("Transfer-Encoding")||s.req.method==="HEAD"||c&&Number(c)<t||!n(s.res)||!am(s.res))return;let d=s.res.headers.get("Vary");if(d!=="*"&&!(d&&sm.test(d)))s.header("Vary",d?`${d}, Accept-Encoding`:"Accept-Encoding");let u=s.req.header("Accept-Encoding"),p=om(u,r);if(!p||!s.res.body)return;let m=new CompressionStream(p);s.res=new Response(s.res.body.pipeThrough(m),s.res),s.res.headers.delete("Content-Length"),s.res.headers.set("Content-Encoding",p);let g=s.res.headers.get("ETag");if(g&&!g.startsWith("W/"))s.res.headers.set("ETag",`W/${g}`)}},am=(e)=>{let t=e.headers.get("Cache-Control");return!t||!nm.test(t)};import{Readable as Ea}from"stream";import{createDeflate as cm,createGzip as lm}from"zlib";var dm=["gzip","deflate"],um=/(?:^|,)\s*?no-transform\s*?(?:,|$)/i,ka=(e)=>{if(typeof CompressionStream<"u")return Ta(e);let t=e?.threshold??1024;return async function(i,n){await n();let o=i.res.headers.get("Content-Length");if(i.res.headers.has("Content-Encoding")||i.res.headers.has("Transfer-Encoding")||i.req.method==="HEAD"||o&&Number(o)<t||!pm(i.res)||!mm(i.res))return;let s=i.req.header("Accept-Encoding"),a=e?.encoding??dm.find((c)=>s?.includes(c));if(!a||!i.res.body)return;try{let c=a==="gzip"?lm():cm(),d=Ea.fromWeb(i.res.body).pipe(c),u=Ea.toWeb(d);i.res=new Response(u,i.res),i.res.headers.delete("Content-Length"),i.res.headers.set("Content-Encoding",a)}catch(c){console.error("Compression error:",c)}}},pm=(e)=>{let t=e.headers.get("Content-Type");return t&&Oe.test(t)},mm=(e)=>{let t=e.headers.get("Cache-Control");return!t||!um.test(t)};var gm=(e,t)=>{if(!e)return t;let r=new Uint8Array(new ArrayBuffer(e.byteLength+t.byteLength));return r.set(new Uint8Array(e),0),r.set(t,e.byteLength),r};var Aa=async(e,t)=>{if(!e)return null;let r=void 0,i,n=0,o=async(a)=>{r=await t(gm(r,a))},s=e.getReader();for(;;){let{value:a,done:c}=await s.read();if(c)break;let d=0;while(d<a.byteLength){let u=a.byteLength-d;if(n===0&&u>=262144){await o(a.subarray(d,d+262144)),d+=262144;continue}let p=n+u;if(p<262144){if(!i)i=a.slice(d);else{if(i.byteLength<p){let g=new Uint8Array(new ArrayBuffer(Math.min(262144,Math.max(p,i.byteLength*2))));g.set(i.subarray(0,n)),i=g}i.set(a.subarray(d),n)}n=p;break}let m=262144-n;if(i?.byteLength!==262144){let g=new Uint8Array(new ArrayBuffer(262144));if(i)g.set(i.subarray(0,n));i=g}i.set(a.subarray(d,d+m),n),await o(i),n=0,d+=m}}if(i&&n>0)await o(i.subarray(0,n));if(!r)return null;return Array.prototype.map.call(new Uint8Array(r),(a)=>a.toString(16).padStart(2,"0")).join("")};var fm=["cache-control","content-location","date","etag","expires","vary"],ja=(e)=>e.replace(/^W\//,"");function hm(e,t){return t!=null&&t.split(",").some((r)=>ja(r.trim())===ja(e))}function ym(e){if(!e){if(crypto&&crypto.subtle)e=(t)=>crypto.subtle.digest({name:"SHA-1"},t)}return e}var Da=(e)=>{let t=new Set((e?.retainedHeaders??fm).map((n)=>n.toLowerCase())),r=e?.weak??!1,i=ym(e?.generateDigest);return async function(o,s){let a=o.req.header("If-None-Match")??null;if(await s(),!(o.req.method==="GET"||o.req.method==="HEAD"||o.req.method==="QUERY")||!o.res.ok)return;let c=o.res,d=c.headers.get("ETag");if(!d){if(!i)return;let u=await Aa(c.clone().body,i);if(u===null)return;d=r?`W/"${u}"`:`"${u}"`}if(a==="*"||hm(d,a)){o.res=new Response(null,{status:304,statusText:"Not Modified",headers:{ETag:d}});for(let u of Array.from(o.res.headers.keys()))if(!t.has(u.toLowerCase()))o.res.headers.delete(u)}else o.res.headers.set("ETag",d)}};function Ii(e,t){return async(r)=>{let i=r.req.raw,n=i.headers.get("content-type")??"",o=i.headers.get("accept")?.includes("application/json"),s={};if(n.includes("application/json"))s=await i.json();else if(n.includes("form")){let m=await i.formData();for(let[g,f]of m.entries())s[g]=f}let a=await t(e,s),c=typeof a==="object"&&a!==null&&"data"in a?a.data:a,d=za.safeParse(c),u=d.success?d.data:c,p=d.success&&d.data.success===!0;if(o)return r.json(u,p?200:400);if(p&&e.definition.successRedirect)return r.redirect(e.definition.successRedirect);if(!p&&e.definition.errorRedirect)return r.redirect(e.definition.errorRedirect);return r.json(u,p?200:400)}}function et(e,t){return e===t||e.startsWith(t+bm)}var Oa="public, max-age=31536000, immutable";function Sm(e){return e.getRoutes?.()??[]}var Rm=255;class Yt{logger;options;routes=Object.freeze([]);productionServer=null;transport=new WeakMap;async fillSitePage(e,t,r){let i=r.slot;if(!i)return;let n=H(e,`.${t}`,"index.html");if(!et(n,H(e)))return;let o=Bun.file(n);if(!await o.exists())return;let s=`<div ${Ua}="${i.name}"></div>`,a=await o.text();if(!a.includes(s))return;let c=new Headers(r.headers);return c.delete("Content-Length"),c.delete("Content-Encoding"),c.delete("ETag"),c.set("Content-Type","text/html; charset=utf-8"),new Response(a.replace(s,()=>i.html),{status:r.status,headers:c})}isPreviewHost(e){if(!e)return!1;let t=e.replace(/:\d+$/,"").toLowerCase();return/^(?:preview\..+|.+-preview\..+)$/.test(t)}constructor(e){this.logger=e.logger,this.options={...e,productionDistDir:H(process.cwd(),e.productionDistDir),sharedImagesDir:H(process.cwd(),e.sharedImagesDir),...e.previewDistDir&&{previewDistDir:H(process.cwd(),e.previewDistDir)}}}async start(){if(this.productionServer){this.logger.warn("Webserver already running");return}this.routes=Object.freeze([...Sm(this.options)]);let e=this.createApp({distDir:this.options.productionDistDir,compress:!0,defaultCache:"public, max-age=3600",immutableExtensions:/\.(jpg|jpeg|png|gif|ico|webp|svg|woff|woff2)$/,revalidateExtensions:/\.(js|css)$/,healthEndpoint:!0}),t=this.options.previewDistDir?this.createApp({distDir:this.options.previewDistDir,compress:!1,defaultCache:"no-cache",immutableExtensions:/\.(jpg|jpeg|png|gif|ico|webp|svg|woff|woff2)$/,healthEndpoint:!1}):void 0,r=this.options.serve??Bun.serve;try{this.productionServer=r({...this.options.hostname?{hostname:this.options.hostname}:{},port:this.options.productionPort,idleTimeout:this.options.idleTimeout??Rm,fetch:async(i,n)=>{let o=n?.requestIP(i)?.address;this.transport.set(i,Object.freeze({...o?{remoteAddress:o}:{}}));let s=await this.serveImageFastPath(i);if(s)return s;let a=new URL(i.url).pathname;if(a==="/health"||a.startsWith("/health/"))return e.fetch(i);if(t&&this.isPreviewHost(i.headers.get("host")))return t.fetch(i);return e.fetch(i)}})}catch(i){let n=String(i);if(n.includes("EADDRINUSE")||n.includes("address already in use")||/Is port \d+ in use\?/.test(n))throw Error(`Port ${this.options.productionPort} is already in use. Another brain may be running \u2014 stop it first or configure a different port.`,{cause:i});throw i}this.logger.info(`Production server listening on http://localhost:${this.productionServer.port}`)}async stop(){if(this.productionServer)await this.productionServer.stop(),this.productionServer=null;this.logger.debug("Webserver stopped")}getStatus(){return{running:this.productionServer!==null,productionUrl:this.productionServer?`http://localhost:${this.productionServer.port}`:void 0,previewUrl:this.productionServer&&this.options.previewDistDir?`http://localhost:${this.productionServer.port}`:void 0}}createApp(e){let t=new Pi;if(e.healthEndpoint)t.all("/health",(r)=>r.notFound()),t.get("/health/live",(r)=>r.json({status:"alive",uptime:Math.floor(process.uptime()),checkedAt:new Date().toISOString()},200)),t.get("/health/ready",async(r)=>{let i=await this.getReadinessData();return r.json(i,i.status==="ready"?200:503)}),t.get("/health/operate",async(r)=>{let i=await this.getReadinessData(),n;if(this.options.getOperationalInfo)try{n=await this.options.getOperationalInfo()}catch(o){i={...i,operationalStatus:"degraded",checks:[...i.checks,{name:"app-info",status:"unhealthy",message:C(o)}]}}return r.json({...i,...n&&{app:n}},i.operationalStatus==="operational"?200:503)});if(t.use("/*",async(r,i)=>{let n=await this.handleDynamicRoute(r,e);if(n)return n;return i()}),e.compress)t.use("/*",ka());return t.use("/*",Da()),t.use("/*",async(r,i)=>{if(await i(),r.res.status>=400)r.header("Cache-Control","no-cache");else if(r.res.headers.has("Cache-Control"))return;else if(e.revalidateExtensions?.test(r.req.path))r.header("Cache-Control","no-cache");else if(e.immutableExtensions.test(r.req.path))r.header("Cache-Control",Oa);else r.header("Cache-Control",e.defaultCache)}),t.use("/*",async(r,i)=>{if(r.req.path===Vt)return r.notFound();return i()}),t.use("/*",this.createCleanUrlMiddleware(e.distDir)),t.use("/*",xi({root:e.distDir})),t.get(Ma,(r)=>r.body(La,200,{"Content-Type":"image/svg+xml; charset=utf-8","Cache-Control":"public, max-age=86400"})),t.notFound(async(r)=>{let i=Bun.file(vm(e.distDir,"404.html"));if(await i.exists())return r.html(await i.text(),404);return r.text("Not Found",404)}),t}async getReadinessData(){if(!this.options.getReadinessData)return{status:"ready",operationalStatus:"degraded",checkedAt:new Date().toISOString(),checks:[],resources:this.getUnavailableResourceSignals()};try{return await this.options.getReadinessData()}catch(e){return{status:"not_ready",operationalStatus:"degraded",checkedAt:new Date().toISOString(),checks:[{name:"runtime-readiness",status:"unhealthy",message:C(e)}],resources:this.getUnavailableResourceSignals()}}}getUnavailableResourceSignals(){let e=process.memoryUsage();return{memory:{rssBytes:e.rss,heapUsedBytes:e.heapUsed,heapTotalBytes:e.heapTotal},fileDescriptors:null,processes:{total:null,zombies:null},queue:null,projection:{initialized:!1,trackedRoots:0,openCircuits:[]},worker:{total:0,active:0,stale:0,latestHeartbeatAgeMs:null}}}async handleDynamicRoute(e,t){let r=e.req.method.toUpperCase(),i=e.req.path,n=Gs(this.routes,r,i);if(n){if(!t.healthEndpoint&&n.preview!==!0)return null;if(n.sharedHostAdmission==="deny")return e.text("Unauthorized",401);let s=await n.handler(e.req.raw,this.transport.get(e.req.raw));if(s instanceof Ti&&s.slot)return await this.fillSitePage(t.distDir,i,s)??s;if(r==="GET"&&s instanceof Ti&&s.status===200){let a=H(t.distDir,`.${i}`,"index.html");if(et(a,H(t.distDir))){let c=Bun.file(a);if(await c.exists()){let d=new Headers(s.headers);return d.delete("Content-Length"),d.delete("Content-Encoding"),d.delete("ETag"),d.set("Content-Type","text/html; charset=utf-8"),new Response(c,{headers:d})}}}return s}if(!t.healthEndpoint)return null;let o=this.routes.find((s)=>s.kind==="tool"&&s.fullPath===i&&s.method===r);if(o){if(o.sharedHostAdmission==="deny")return e.text("Unauthorized",401);if(!this.options.executeTool)return e.text("HTTP tool route unavailable",500);return Ii({pluginId:o.ownerPluginId,fullPath:o.fullPath,definition:o.definition},this.options.executeTool)(e)}return null}async serveImageFastPath(e){let t;try{t=new URL(e.url)}catch{return null}if(!t.pathname.startsWith("/images/"))return null;let r=t.pathname.slice(8),i=H(this.options.sharedImagesDir,r);if(!et(i,this.options.sharedImagesDir))return null;let n=Bun.file(i);if(!await n.exists())return null;return new Response(n,{headers:{"Cache-Control":Oa}})}createCleanUrlMiddleware(e){return async(t,r)=>{let i=t.req.path;if(i.includes(".")||i==="/"){await r();return}let n=H(e,`.${i}`,"index.html");if(!et(n,e)){await r();return}let o=Bun.file(n);if(await o.exists())return t.html(await o.text());let s=H(e,`.${i}.html`);if(et(s,e)){let a=Bun.file(s);if(await a.exists())return t.html(await a.text())}await r()}}}function Ei(e,t){return(r,i)=>e.send({type:Xt.toolExecute(r.pluginId),payload:{toolName:r.definition.tool.includes("_")?r.definition.tool:`${r.pluginId}_${r.definition.tool}`,args:i,interfaceType:t,actor:{kind:"external",externalActorId:$a(t,"anonymous")}},sender:t})}var ki=`<!DOCTYPE html>
10
+ `):lu}formatRelevantEntity(e,t){let{entity:r,excerpt:i}=e,n=r.entityType,o=au.safeParse(r.metadata),s=o.success?o.data.slug:r.id;if(this.siteBaseUrl&&t.hasRoute(n)){let a=t.generateUrl(n,s),c=`https://${this.siteBaseUrl}${a}`;return`[${n}] ${r.id}: ${i} (${c})`}return`[${n}] ${r.id}: ${i}`}}var pu=l.object({entityType:l.string(),query:l.object({id:l.string()})});class vt{entityService;id=Br.ENTITIES;name="Entity DataSource";description="Fetches entity content from the entity service";constructor(e){this.entityService=e}async fetch(e,t,r){let i=pu.safeParse(e);if(!i.success){let a=i.error.issues.map((c)=>`${c.path.join(".")}: ${c.message}`).join(", ");throw Error(`EntityDataSource: Invalid query - ${a}`)}let n=i.data,s=await(r?.entityService??this.entityService).getEntity({entityType:n.entityType,id:n.query.id});if(!s)throw Error(`EntityDataSource: Entity not found (${n.entityType}:${n.query.id})`);return t.parse({markdown:s.content})}}function Pn(e,t){e.dataSourceRegistry.register(new yt(e.aiService,e.entityService,e.templateRegistry,()=>e.identityService.getCharacterContent(),()=>e.profileService.getProfileContent(),new bt(t.entityDisplay),t.siteBaseUrl)),e.dataSourceRegistry.register(new vt(e.entityService)),e.logger.debug("Core DataSources registered")}async function Cn(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})}var xn={lexicon:1,id:"ai.rizom.brain.card",defs:{main:{type:"record",description:"Public discovery card for a Rizom brain. A web-capable brain may advertise its operational A2A Agent Card through siteUrl; federation-only brains remain discoverable through this PDS record.",key:"literal:self",record:{type:"object",required:["brain","anchor","skills","model","version","createdAt"],properties:{siteUrl:{type:"string",format:"uri",description:"Optional public web-channel URL. Consumers may derive the A2A Agent Card URL from this base when present."},brain:{type:"ref",ref:"#brain",description:"Brain identity described by this discovery card."},anchor:{type:"ref",ref:"#anchor",description:"Minimal Anchor snapshot for discovery grouping and display."},skills:{type:"array",description:"User-facing skills this brain advertises for discovery.",items:{type:"ref",ref:"#skill"},maxLength:100},model:{type:"string",description:"Rizom brain model identifier."},version:{type:"string",description:"Brain runtime/model implementation version."},createdAt:{type:"string",format:"datetime"},updatedAt:{type:"string",format:"datetime"}}}},brain:{type:"object",description:"Brain identity described by this discovery card.",required:["did","name","role","purpose","values"],properties:{did:{type:"string",description:"Public DID for the brain identity."},name:{type:"string",maxLength:200,description:"Human-readable brain name."},role:{type:"string",maxLength:500,description:"Brain role or persona."},purpose:{type:"string",maxLength:2000,description:"Short public description of what this brain is for."},values:{type:"array",description:"Public values or principles for this brain.",items:{type:"string",maxLength:200},maxLength:50}}},anchor:{type:"object",description:"Minimal Anchor snapshot for discovery grouping and display.",required:["did","name","category","kind"],properties:{did:{type:"string",description:"Public DID for the Anchor identity."},name:{type:"string",maxLength:200,description:"Human-readable anchor name."},category:{type:"string",knownValues:["person","team","organization"],description:"Stable structural category for discovery and grouping."},kind:{type:"string",maxLength:200,description:"Open semantic profile kind selected by the publishing brain."}}},skill:{type:"object",description:"User-facing skill this brain advertises for discovery.",required:["id","name","description"],properties:{id:{type:"string",maxLength:200},name:{type:"string",maxLength:200},description:{type:"string",maxLength:2000},tags:{type:"array",items:{type:"string"},maxLength:50},examples:{type:"array",items:{type:"string"},maxLength:20}}}}};var In={lexicon:1,id:"ai.rizom.brain.deck",defs:{main:{type:"record",description:"Public presentation deck from a Rizom brain.",key:"any",record:{type:"object",required:["title","body","createdAt"],properties:{title:{type:"string",maxLength:300},slug:{type:"string"},description:{type:"string",maxLength:2000},body:{type:"string",maxLength:1e5},format:{type:"string",knownValues:["text/markdown"]},author:{type:"string"},event:{type:"string"},publishedAt:{type:"string",format:"datetime"},canonicalUrl:{type:"string",format:"uri"},brainDid:{type:"string"},anchorDid:{type:"string"},sourceEntityType:{type:"string"},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},updatedAt:{type:"string",format:"datetime"}}}}}};var Tn={lexicon:1,id:"ai.rizom.brain.link",defs:{main:{type:"record",description:"Public curated link from a Rizom brain.",key:"any",record:{type:"object",required:["title","url","createdAt"],properties:{title:{type:"string",maxLength:500},url:{type:"string",format:"uri"},description:{type:"string",maxLength:2000},summary:{type:"string",maxLength:1e5},domain:{type:"string"},capturedAt:{type:"string",format:"datetime"},source:{type:"ref",ref:"#source"},canonicalUrl:{type:"string",format:"uri"},brainDid:{type:"string"},anchorDid:{type:"string"},sourceEntityType:{type:"string"},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},updatedAt:{type:"string",format:"datetime"}}}},source:{type:"object",description:"Attribution for where this link was captured.",required:["ref","label"],properties:{ref:{type:"string"},label:{type:"string"}}}}};var En={lexicon:1,id:"ai.rizom.brain.note",defs:{main:{type:"record",description:"Public knowledge note from a Rizom brain.",key:"any",record:{type:"object",required:["title","body","createdAt"],properties:{title:{type:"string",maxLength:300},body:{type:"string",maxLength:1e5},format:{type:"string",knownValues:["text/markdown"]},canonicalUrl:{type:"string",format:"uri"},brainDid:{type:"string"},anchorDid:{type:"string"},sourceEntityType:{type:"string"},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},updatedAt:{type:"string",format:"datetime"}}}}}};var kn={lexicon:1,id:"ai.rizom.brain.post",defs:{main:{type:"record",description:"Markdown blog post distributed by a Rizom brain.",key:"any",record:{type:"object",required:["title","body","createdAt"],properties:{title:{type:"string",maxLength:300},summary:{type:"string",maxLength:2000},body:{type:"string",maxLength:1e5},format:{type:"string",knownValues:["text/markdown"]},brainDid:{type:"string"},anchorDid:{type:"string"},canonicalUrl:{type:"string",format:"uri"},topics:{type:"array",items:{type:"string"},maxLength:50},coverImage:{type:"ref",ref:"#coverImage"},series:{type:"string",maxLength:200},seriesIndex:{type:"integer"},sourceEntityType:{type:"string",knownValues:["post"]},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},publishedAt:{type:"string",format:"datetime"}}}},coverImage:{type:"object",description:"Cover image attached to the post.",required:["blob"],properties:{blob:{type:"blob"},alt:{type:"string",maxLength:1000},width:{type:"integer"},height:{type:"integer"}}}}};var An={lexicon:1,id:"ai.rizom.brain.project",defs:{main:{type:"record",description:"Public project or case study from a Rizom brain.",key:"any",record:{type:"object",required:["title","body","year","createdAt"],properties:{title:{type:"string",maxLength:300},slug:{type:"string"},description:{type:"string",maxLength:2000},body:{type:"string",maxLength:1e5},format:{type:"string",knownValues:["text/markdown"]},year:{type:"integer"},url:{type:"string",format:"uri"},publishedAt:{type:"string",format:"datetime"},canonicalUrl:{type:"string",format:"uri"},brainDid:{type:"string"},anchorDid:{type:"string"},sourceEntityType:{type:"string"},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},updatedAt:{type:"string",format:"datetime"}}}}}};var jn={lexicon:1,id:"ai.rizom.brain.series",defs:{main:{type:"record",description:"Public content series from a Rizom brain.",key:"any",record:{type:"object",required:["title","createdAt"],properties:{title:{type:"string",maxLength:300},slug:{type:"string"},description:{type:"string",maxLength:1e4},canonicalUrl:{type:"string",format:"uri"},brainDid:{type:"string"},anchorDid:{type:"string"},sourceEntityType:{type:"string"},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},updatedAt:{type:"string",format:"datetime"}}}}}};var Dn={lexicon:1,id:"ai.rizom.brain.socialPost",defs:{main:{type:"record",description:"Semantic local social-post entity from a Rizom brain; not a Bluesky feed post.",key:"any",record:{type:"object",required:["title","platform","body","createdAt"],properties:{title:{type:"string",maxLength:300},platform:{type:"string"},body:{type:"string",maxLength:1e5},format:{type:"string",knownValues:["text/markdown"]},status:{type:"string"},publishedAt:{type:"string",format:"datetime"},platformPostId:{type:"string"},sourceLocalEntityType:{type:"string"},sourceLocalEntityId:{type:"string"},canonicalUrl:{type:"string",format:"uri"},brainDid:{type:"string"},anchorDid:{type:"string"},sourceEntityType:{type:"string"},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},updatedAt:{type:"string",format:"datetime"}}}}}};var zn={lexicon:1,id:"ai.rizom.brain.topic",defs:{main:{type:"record",description:"Public topic page from a Rizom brain.",key:"any",record:{type:"object",required:["title","body","createdAt"],properties:{title:{type:"string",maxLength:300},body:{type:"string",maxLength:1e5},format:{type:"string",knownValues:["text/markdown"]},canonicalUrl:{type:"string",format:"uri"},brainDid:{type:"string"},anchorDid:{type:"string"},sourceEntityType:{type:"string"},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},updatedAt:{type:"string",format:"datetime"}}}}}};var On=l.object({type:l.string()}).catchall(l.unknown()),wu=l.object({type:l.literal("object"),description:l.string().optional(),required:l.array(l.string()).optional(),properties:l.record(l.string(),On)}),Pu=l.object({lexicon:l.literal(1),id:l.string(),defs:l.object({main:l.object({type:l.literal("record"),key:l.string().min(1),description:l.string().optional(),record:l.object({type:l.literal("object"),required:l.array(l.string()).optional(),properties:l.record(l.string(),On)})})}).catchall(wu)});function N(e){return Pu.parse(e)}var D={"ai.rizom.brain.card":N(xn),"ai.rizom.brain.deck":N(In),"ai.rizom.brain.link":N(Tn),"ai.rizom.brain.note":N(En),"ai.rizom.brain.post":N(kn),"ai.rizom.brain.project":N(An),"ai.rizom.brain.series":N(jn),"ai.rizom.brain.socialPost":N(Dn),"ai.rizom.brain.topic":N(zn)},Cu="Additive optional fields are compatible; required-field, type, or constraint changes require a migration plan or new NSID.";function K(e){return{status:"approved",version:"1.0.0",revision:1,owner:"Rizom",steward:"Rizom protocol registry",projectionPackage:e,compatibility:Cu}}var Mn={"ai.rizom.brain.card":K("@brains/atproto"),"ai.rizom.brain.deck":K("@brains/decks"),"ai.rizom.brain.link":K("@brains/link"),"ai.rizom.brain.note":K("@brains/note"),"ai.rizom.brain.post":K("@brains/blog"),"ai.rizom.brain.project":K("@brains/portfolio"),"ai.rizom.brain.series":K("@brains/series"),"ai.rizom.brain.socialPost":K("@brains/social-media"),"ai.rizom.brain.topic":K("@brains/topics")};function xu(){return Object.values(D)}function Iu(e){if(!_r(D,e))return;return D[e]}function Tu(){return St(Mn).map(([e,t])=>({id:e,...t}))}var Eu=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;function ku(e){let t=l.string(),r=e.maxLength!==void 0?t.max(e.maxLength):t;if(e.knownValues)r=r.refine((i)=>e.knownValues?.includes(i),{message:`expected one of ${e.knownValues.join(", ")}`});if(e.format==="datetime")r=r.refine((i)=>Eu.test(i)&&!Number.isNaN(Date.parse(i)),{message:"expected datetime"});if(e.format==="uri")r=r.refine((i)=>{try{return new URL(i),!0}catch{return!1}},{message:"expected uri"});return r}function Au(e,t){if(typeof e!=="string"||!e.startsWith("#"))return;let r=t[e.slice(1)];return r?.type==="object"?r:void 0}function Un(e,t){switch(e.type){case"string":return ku(e);case"integer":return l.number().int();case"boolean":return l.boolean();case"array":{let r=e.items?Un(e.items,t):l.unknown(),i=l.array(r);if(e.maxLength!==void 0)i=i.max(e.maxLength);return i}case"object":return Ln(e,t);case"ref":{let r=Au(e.ref,t);if(!r)return l.custom(()=>!1,{message:`unresolvable lexicon ref ${String(e.ref)}`});return l.lazy(()=>Ln(r,t))}case"blob":return l.custom(ae,{message:"expected blob"});default:return l.unknown()}}function $n(e,t){let r=new Set(e.required??[]),i={};for(let[n,o]of Object.entries(e.properties??{})){let s=Un(o,t);i[n]=r.has(n)?s:s.optional()}return i}function Ln(e,t){return l.strictObject($n(e,t))}function Z(e){return l.strictObject({...$n(e.defs.main.record,e.defs),$type:l.literal(e.id).optional()})}var Zr={"ai.rizom.brain.card":Z(D["ai.rizom.brain.card"]),"ai.rizom.brain.deck":Z(D["ai.rizom.brain.deck"]),"ai.rizom.brain.link":Z(D["ai.rizom.brain.link"]),"ai.rizom.brain.note":Z(D["ai.rizom.brain.note"]),"ai.rizom.brain.post":Z(D["ai.rizom.brain.post"]),"ai.rizom.brain.project":Z(D["ai.rizom.brain.project"]),"ai.rizom.brain.series":Z(D["ai.rizom.brain.series"]),"ai.rizom.brain.socialPost":Z(D["ai.rizom.brain.socialPost"]),"ai.rizom.brain.topic":Z(D["ai.rizom.brain.topic"])};function ju(e,t){let r=e;for(let i of t){if(typeof i==="symbol")return;if(Array.isArray(r)){r=r[Number(i)];continue}if(!ae(r))return;r=r[String(i)]}return r}function Du(e,t,r){let i=r.path.join(".");if(i==="$type")return`AT Protocol record $type must match lexicon id: ${String(t.$type)} !== ${e.id}`;if(r.code==="invalid_type"&&ju(t,r.path)===void 0)return`Missing required AT Protocol record field: ${i}`;if(r.code==="invalid_type")return`Invalid AT Protocol record field ${i}: expected ${r.expected}`;if(r.code==="too_big")return`Invalid AT Protocol record field ${i}: exceeds maxLength ${r.maximum}`;if(r.code==="custom")return`Invalid AT Protocol record field ${i}: ${r.message}`;if(r.code==="unrecognized_keys")return`Unrecognized AT Protocol record field(s): ${r.keys.join(", ")}`;return`Invalid AT Protocol record field ${i}: ${r.message}`}function zu(e,t){let r=Z(e).safeParse(t);if(r.success)return;let i=r.error.issues[0];if(!i)throw r.error;throw Error(Du(e,t,i))}var Bn="atproto:brain-card-discovered",_n="atproto:brain-discovered",Zn="atproto:brain-card-refreshed",Fn="atproto:brain-card-unavailable",Nn="atproto:brain-card-conflict",Hn="atproto:jetstream-gap",Ou=l.custom((e)=>Zr["ai.rizom.brain.card"].safeParse(e).success),Wn=l.object({repoDid:l.string().min(1),uri:l.string().min(1),cid:l.string().min(1),record:Ou}).strict(),Fr=l.object({agentId:l.string().min(1),name:l.string().min(1),url:l.string().url(),status:l.enum(["discovered","approved","archived"]),repoDid:l.string().min(1).optional(),brainDid:l.string().min(1).optional(),anchorDid:l.string().min(1).optional(),cardUri:l.string().min(1).optional(),cardCid:l.string().min(1).optional()}).strict(),qn=l.object({repoDid:l.string().startsWith("did:plc:"),observedAt:l.string().datetime(),staleAfter:l.string().datetime().optional(),reason:l.enum(["deleted","refresh-failed"]),error:l.string().min(1).optional()}).strict(),Jn=l.object({domain:l.string().min(1),existingRepoDid:l.string().min(1).optional(),candidateRepoDid:l.string().startsWith("did:plc:"),observedAt:l.string().datetime(),reason:l.string().min(1)}).strict(),Gn=l.object({previousCursorTimeUs:l.number().int().nonnegative(),clampedCursorTimeUs:l.number().int().nonnegative(),observedAt:l.string().datetime()}).strict(),Mu=be(Bn,Wn),Lu=be(_n,Fr),Uu=be(Zn,Fr),$u=be(Fn,qn),Bu=be(Nn,Jn),_u=be(Hn,Gn);class Rt{projections=new Map;register(e){this.validateProjection(e);let t=this.get(e.entityType);if(t&&!this.isEquivalentProjection(t,e))throw Error(`AT Protocol projection already registered for entity type ${e.entityType}`);let r=this.projections.get(e.entityType)??[];return r.push(e),this.projections.set(e.entityType,r),this.createUnregister(e.entityType,e)}get(e){let t=this.projections.get(e);return t?.[t.length-1]}has(e){return this.get(e)!==void 0}list(){let e=[];for(let t of this.projections.keys()){let r=this.get(t);if(r)e.push(r)}return e}listLexicons(){return this.list().map((e)=>e.lexicon)}createUnregister(e,t){let r=!0;return()=>{if(!r)return;r=!1;let i=this.projections.get(e);if(!i)return;let n=i.lastIndexOf(t);if(n!==-1)i.splice(n,1);if(i.length===0)this.projections.delete(e)}}isEquivalentProjection(e,t){return e.entityType===t.entityType&&e.collection===t.collection&&e.lexicon.id===t.lexicon.id&&e.validate===t.validate}validateProjection(e){if(e.collection!==e.lexicon.id)throw Error(`AT Protocol projection collection must match lexicon id: ${e.collection} !== ${e.lexicon.id}`);if(!e.lexicon.defs.main.key)throw Error(`AT Protocol projection lexicon must define a record key: ${e.collection}`)}}function Zu({config:e,pageUrl:t},r){return{...e.brainDid&&{brainDid:e.brainDid},...e.anchorDid&&{anchorDid:e.anchorDid},...t&&{canonicalUrl:t},sourceEntityType:r.entityType,sourceEntityId:r.id,createdAt:r.created,...r.updated&&{updatedAt:r.updated}}}async function Pt(e,t,r){let i=await wt(e,Qn,{actor:r},t);if(i.status==="unavailable")return null;if(i.status==="failed")throw Kn(i.error,`Principal resolution failed: ${i.error.message}`);return i.data.principal}function Yn(e,t){return new Vn(e,(r)=>Pt(t,"shell:content-service",r))}var Nr=T.Service("@brains/conversation-service/ConversationService");function Fu(e){if(e.service){let r=e.service;return{service:r,close:()=>r.close()}}let t=Xn.createFreshFromConfig(e.logger,e.messageBus,e.dbConfig);try{return{service:t,close:()=>t.close()}}catch(r){throw t.close(),r}}function eo(e){return ce(Nr,()=>Fu(e))}var Hr=T.Service("@brains/entity-service/EntityService");function Nu(e){return"close"in e&&typeof e.close==="function"}function ro(e){return ce(Hr,()=>{let t=e.service??to.createFresh(e);return{service:t,close:()=>{if(Nu(t))t.close()}}})}var He=l.strictObject({dedupeKey:l.string().min(1).max(512),title:l.string().min(1),body:l.string().min(1),html:l.string().min(1).optional(),sensitivity:l.enum(["normal","secret"]).optional(),includeInInbox:l.boolean().optional()}),Wr=l.strictObject({alerts:l.array(He).optional()});var Ct="shell:recurring-check",Jr=86400000,Hu=7*Jr,Wu=3*Jr,qu=l.strictObject({checkId:l.string().min(1)}),Ju=l.discriminatedUnion("kind",[l.strictObject({kind:l.literal("last-success"),checkId:l.string(),at:l.string().datetime()}),l.strictObject({kind:l.literal("alert"),checkId:l.string(),dedupeKey:l.string(),status:l.enum(["pending","suppressed","delivered","resolved"]),alert:He,observedAt:l.string().datetime(),includeInInbox:l.boolean().optional(),deliveredAt:l.string().datetime().optional(),resolvedAt:l.string().datetime().optional()})]);class It{brainId;scheduler;state;jobQueue;delivery;logger;clock;checks=new Map;pluginChecks=new Map;alertOperations=new so;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.state=e.runtimeState.scoped({namespace:"shell.recurring-checks",schema:Ju});let t={validateAndParse:(r)=>{let i=qu.safeParse(r);return i.success?i.data:null},process:async(r)=>{await this.runNow(r.checkId)}};this.jobQueue.registerHandler(Ct,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(Ct),this.handlerRegistered=!1}namespace(e){return{register:(t)=>this.register(e,t)}}register(e,t){Qu(e),ao(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 s=Promise.resolve().then(()=>this.executeRegisteredCheck(r,n)),a=()=>{if(r.activeCheck===o)delete r.activeCheck};return o.settled=s.then(a,a),s}async executeRegisteredCheck(e,t){let r=e.definition.id,i,n=async(a)=>{let c=AbortSignal.any([t,a]),d=e.definition.deliverAlerts!==!1;if(d)await this.flushPendingAlerts(r);else await this.suppressPendingAlerts(r);c.throwIfAborted();let u=await e.definition.run({signal:c});c.throwIfAborted();let p=Wr.parse(u);for(let m of p.alerts??[])c.throwIfAborted(),await this.recordAlert(r,m,{deliver:d,includeInInbox:m.includeInInbox??e.definition.includeInInbox!==!1});c.throwIfAborted(),await this.state.set(this.lastSuccessKey(r),{kind:"last-success",checkId:r,at:this.currentTime().toISOString()})},o=b.tryPromise({try:(a)=>(i=n(a),i),catch:(a)=>a}),s=await b.runPromiseExit(o,{signal:t});if(i)await Promise.allSettled([i]);if(k.isSuccess(s))return!0;if(t.aborted)throw t.reason;throw de.squash(s.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=xt(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=xt(this.brainId,r.id,r.cadence),n=qr(this.currentTime(),i).getTime()+i.periodMs,o=new AbortController,s={controller:o,settled:Promise.resolve()};e.enqueueRetry=s,s.settled=io(()=>this.enqueue(r.id),t,{firstDelayMs:no,maxDelayMs:oo,giveUpAt:n,signal:o.signal,clock:this.clock,onRetry:(a,c)=>{this.logger.warn(`Failed to enqueue recurring check ${r.id}; retrying in ${c}ms`,a)}}).then((a)=>{if(a.kind!=="abandoned")return;this.logger.error(`Failed to enqueue recurring check ${r.id}; the next scheduled run supersedes it`,a.error)},(a)=>{this.logger.error(`Retrying recurring check ${r.id} failed`,a)}).finally(()=>{if(e.enqueueRetry===s)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=xt(this.brainId,t.id,t.cadence),n=qr(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(s){this.retryRefusedEnqueue(e,s)}}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:Ct,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=He.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 a=o.includeInInbox===r.includeInInbox?o:{...o,includeInInbox:r.includeInInbox};if(a!==o)await this.state.set(n,a);if(a.status==="delivered"||a.status==="resolved")return;if(r.deliver)await this.deliverStoredAlert(n,a);return}let s={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,s),r.deliver)await this.deliverStoredAlert(n,s)})}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()):new Date}lastSuccessKey(e){return`run:${le(e)}`}alertKeyPrefix(e){return`alert:${le(e)}:`}alertKey(e,t){return`${this.alertKeyPrefix(e)}${le(t)}`}}function xt(e,t,r){let i=r==="daily"?Jr:Hu,n=i/60000,o=le(`${e}\x00${t}\x00${r}`),s=Number.parseInt(o.slice(0,12),16)%n,a=s%60,c=Math.floor(s/60),d=c%24;return{expression:r==="daily"?`${a} ${d} * * *`:`${a} ${d} * * ${Math.floor(c/24)}`,offsetMs:s*60000,periodMs:i,anchorMs:r==="daily"?0:Wu}}function qr(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)}var Gu=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*:[a-z][a-z0-9-]*$/;function Qu(e){if(e.length<=200&&Gu.test(e))return;ao(e,"plugin ID")}function ao(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 P=co("runtime_state_records",{namespace:Tt("namespace").notNull(),key:Tt("key").notNull(),value:Tt("value",{mode:"json"}).notNull(),createdAt:Gr("created_at").notNull(),updatedAt:Gr("updated_at").notNull()},(e)=>({pk:uo({columns:[e.namespace,e.key]}),namespaceUpdatedAtIdx:lo("idx_runtime_state_namespace_updated_at").on(e.namespace,e.updatedAt)}));function mo(e){return po({url:e.url,schema:{runtimeStateRecords:P},authToken:e.authToken,authTokenEnv:"RUNTIME_STATE_DATABASE_AUTH_TOKEN"})}function Et(e,t){let r=JSON.stringify(t);if(!r)throw Error("Runtime state must be a JSON wire value");let i=JSON.parse(r);return e.parse(i),i}import{isDeepStrictEqual as Ku}from"util";var Vu=/^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,511}$/,vo=512;class Qr{db;namespace;schema;now;constructor(e,t,r,i=()=>new Date){Yu(t),this.db=e,this.namespace=t,this.schema=r,this.now=i}async get(e){let t=Se(e),i=(await this.db.select().from(P).where(ue(z(P.namespace,this.namespace),z(P.key,t))).limit(1))[0];if(!i)return null;return this.schema.parse(i.value)}async has(e){let t=Se(e);return(await this.db.select({key:P.key}).from(P).where(ue(z(P.namespace,this.namespace),z(P.key,t))).limit(1)).length>0}async set(e,t){let r=Se(e),i=Et(this.schema,t),n=i===null?Re`'null'`:i,o=this.now().getTime();await this.db.insert(P).values({namespace:this.namespace,key:r,value:n,createdAt:o,updatedAt:o}).onConflictDoUpdate({target:[P.namespace,P.key],set:{value:n,updatedAt:o}})}async setIfNotExists(e,t){let r=Se(e),i=Et(this.schema,t),n=i===null?Re`'null'`:i,o=this.now().getTime(),s=await this.db.insert(P).values({namespace:this.namespace,key:r,value:n,createdAt:o,updatedAt:o}).onConflictDoNothing({target:[P.namespace,P.key]});return Number(s.rowsAffected)>0}async compareAndSet(e,t,r){let i=Se(e),n=Et(this.schema,r),[o]=await this.db.select({value:P.value}).from(P).where(ue(z(P.namespace,this.namespace),z(P.key,i))).limit(1);if(!o||!Ku(this.schema.parse(o.value),t))return!1;let s=o.value===null?Re`'null'`:o.value,a=n===null?Re`'null'`:n,c=await this.db.update(P).set({value:a,updatedAt:this.now().getTime()}).where(ue(z(P.namespace,this.namespace),z(P.key,i),z(P.value,s)));return Number(c.rowsAffected)===1}async delete(e){let t=Se(e),r=await this.db.delete(P).where(ue(z(P.namespace,this.namespace),z(P.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(P).where(ue(z(P.namespace,this.namespace),go(e.keyPrefix)));return Number(t.rowsAffected)}async listRows(e){let{keyPrefix:t,afterKey:r,limit:i}=e;if(r!==void 0)Se(r);if(i!==void 0)l.number().int().min(1).max(1000).parse(i);let n=this.db.select({...fo(P),key:Re`CAST(${P.key} AS BLOB)`.mapWith((o)=>new TextDecoder("utf-8",{fatal:!0}).decode(o))}).from(P).where(ue(z(P.namespace,this.namespace),go(t),r!==void 0?ho(P.key,r):void 0)).orderBy(yo(P.key)).$dynamic();return i===void 0?n:n.limit(i)}}function Yu(e){if(!Vu.test(e))throw Error(`Invalid runtime state namespace: ${e}. Use 1-512 alphanumeric, _, ., :, or - characters.`)}function Se(e){if(e.length===0||e.length>vo)throw Error("Runtime state keys must be 1-512 characters long");return e}function go(e){if(e===void 0)return;return Xu(e),Re`substr(CAST(${P.key} AS BLOB), 1, length(CAST(${e} AS BLOB))) = CAST(${e} AS BLOB)`}function Xu(e){if(e.length>vo)throw Error("Runtime state key prefixes must be 512 characters or shorter");return e}class kt{db;client;logger;databaseUrl;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;static createFresh(e,t){return new kt(e,t??Ee.getInstance())}constructor(e,t){let{db:r,client:i,url:n}=mo(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 bo(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){let t=new Qr(this.db,e.namespace,e.schema);return Object.freeze({get:t.get.bind(t),has:t.has.bind(t),set:t.set.bind(t),setIfNotExists:t.setIfNotExists.bind(t),compareAndSet:t.compareAndSet.bind(t),delete:t.delete.bind(t),list:t.list.bind(t),clear:t.clear.bind(t)})}close(){if(this.closeRequested=!0,!this.walInitialization||this.walInitializationSettled)this.closeClient()}closeClient(){if(this.clientClosed)return;this.clientClosed=!0,this.client.close()}}var Kr=T.Service("@brains/runtime-state/RuntimeStateService");function So(e){return ce(Kr,()=>{let t=e.service??kt.createFresh(e.config,e.logger);return{service:t,close:()=>t.close()}})}function Vr(e,t,r){let i=Bun.cron.parse(e,t,r?{tz:r}:void 0);if(i===null)throw Error(`Cron expression ${JSON.stringify(e)} has no future occurrences`);return i}function Ro(e){Vr(e,Date.now())}class qe{options;nextJobId=0;constructor(e={}){this.options=e}scheduleCron(e,t,r={}){Vr(e,Date.now(),r.timezone);let i=`cron:${this.nextJobId++}:${e}`,n={},o=new Yr(i,t,this.options,()=>n.current?.stop());return n.current=Bun.cron(e,()=>{o.trigger()},r.timezone?{tz:r.timezone}:void 0),o}scheduleInterval(e,t){ep(e);let r=`interval:${this.nextJobId++}:${e}`,i=new Yr(r,t,this.options);return i.startInterval(e),i}validateCron(e){Ro(e)}}class Yr{key;callback;options;stopTrigger;scope;cycles;intervalFiber=null;stopPromise=null;stopped=!1;constructor(e,t,r,i=()=>{}){this.key=e,this.callback=t,this.options=r,this.stopTrigger=i,this.scope=b.runSync(E.make()),this.cycles=b.runSync(E.provide(We.make(),this.scope))}startInterval(e){let t=b.sleep(e).pipe(b.andThen(b.sync(()=>{this.trigger()})),b.forever),r=Po(t,this.options.clock);this.intervalFiber=b.runFork(r)}trigger(){if(this.stopped)return;if(We.hasUnsafe(this.cycles,this.key)){this.options.onOverlapSkipped?.(this.key);return}let e=b.tryPromise({try:async()=>{await this.callback()},catch:(r)=>r}).pipe(b.catch((r)=>b.sync(()=>{this.options.onCallbackError?.(this.key,r)}))),t=b.runFork(e);We.setUnsafe(this.cycles,this.key,t,{onlyIfMissing:!0})}stop(){return this.stopPromise??=this.stopScheduledJob(),this.stopPromise}async stopScheduledJob(){this.stopped=!0;let e=[];try{this.stopTrigger()}catch(i){e.push(i)}let t=this.intervalFiber;this.intervalFiber=null;let r=[...t?[wo.interrupt(t)]:[],We.awaitEmpty(this.cycles),E.close(this.scope,k.void)];for(let i of r)try{await b.runPromise(i)}catch(n){e.push(n)}if(e.length===1)throw e[0];if(e.length>1)throw AggregateError(e,"Scheduled job cleanup failed")}}function ep(e){if(!Number.isFinite(e)||e<=0)throw Error("Scheduler interval must be a positive finite number")}function Co(e){let t=e.scheduler??new qe,r=e.now??Date.now,i,n,o,s=!1,a=!1,c={status:"unknown"},d=0,u=0,p=async()=>{if(!s||a)return;a=!0,i=r();try{await e.run(),d++,c={status:"healthy",lastCheck:new Date(r()),details:{successes:d,failures:u}}}catch{u++,c={status:"warning",message:"Maintenance cycle failed",lastCheck:new Date(r()),details:{successes:d,failures:u}},e.logger.warn("Maintenance cycle failed",{successes:d,failures:u})}finally{a=!1}};return{start:async()=>{if(o)await o;if(n)return;c={status:"unknown"},i=r(),n=t.scheduleInterval(e.intervalMs,p),s=!0},stop:()=>{if(o)return o;if(s=!1,!n)return Promise.resolve();return o=n.stop().then(()=>{n=void 0,o=void 0}),o},healthCheck:async()=>{let m=r();if(!Number.isSafeInteger(m)||m<0||i!==void 0&&!Number.isSafeInteger(i))return{status:"warning",message:"Maintenance clock unavailable"};if(s&&i!==void 0&&(m<i||m-i>e.intervalMs*2))return{status:"warning",message:a?"Maintenance cycle is still running":"Maintenance cycle is overdue"};return{...c,...c.lastCheck?{lastCheck:new Date(c.lastCheck)}:{},...c.details?{details:{...c.details}}:{}}}}}async function Xr(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=Je(r),t.warn(`Daemon ${e.name} failed to start: ${C(r)}`),r}}async function ei(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=Je(r),t.error(`Failed to stop daemon: ${e.name}`,r),r}}async function xo(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 Io(e){return{name:e.name,pluginId:e.pluginId,status:e.status,health:e.health}}class At{daemons=new Map;daemonScopes=new Map;daemonTransitions=new Map;logger;static createFresh(e){return new At(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 Xr(t,this.logger);return}let r=b.runSync(E.make()),i=b.acquireRelease(b.promise(()=>Xr(t,this.logger)),()=>b.promise(()=>ei(t,this.logger)));try{await b.runPromise(E.provide(i,r)),this.daemonScopes.set(e,r)}catch(n){throw await b.runPromise(E.close(r,k.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 ei(t,this.logger);return}this.daemonScopes.delete(e),await b.runPromise(E.close(r,k.void))}async checkHealth(e){let t=this.daemons.get(e);if(!t)throw Error(`Daemon not registered: ${e}`);return xo(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(Io)}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(s){if(r??=Je(s),!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),s=()=>{if(n.pending--,n.pending===0)this.daemonTransitions.delete(e)},a=o.then(s,s);return n.tail=a,n.lastKind=t,n.lastPromise=o,o}}var tp=l.object({projectionId:l.string().min(1),reason:l.string().min(1),openedAt:l.number().int().nonnegative(),expiresAt:l.number().int().nonnegative()}),rp=8,ip=32,np=128,op=5,sp=600000,ap=600000,cp=1000,lp="shell.projection-circuits";class jt{operationContext;options;circuitStore;roots=new Map;reservedJobs=new Map;circuits=new Map;projections;static createFresh(e,t={}){return new jt(e,t)}constructor(e,t){this.operationContext=e,this.options={maxDerivationDepth:t.maxDerivationDepth??rp,maxJobsPerRoot:t.maxJobsPerRoot??ip,maxMutationsPerRoot:t.maxMutationsPerRoot??np,repeatedTargetLimit:t.repeatedTargetLimit??op,retentionMs:t.retentionMs??sp,circuitOpenMs:t.circuitOpenMs??ap,maxTrackedRoots:t.maxTrackedRoots??cp,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:lp,schema:tp})}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((d)=>d===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,s=this.reservedJobs.get(n)??0;if(o+s+1>this.options.maxJobsPerRoot)await this.rejectAndOpen(t,`Root ${n} exceeded projection job budget ${this.options.maxJobsPerRoot}`,r);this.reservedJobs.set(n,s+1);let a=!1,c=(d)=>{if(a)return;if(a=!0,this.releaseJobReservation(n),!d)return;let u=this.options.now(),p=this.getRootCounters(n,u);p.jobs++,p.updatedAt=u};return{commit:()=>c(!0),rollback:()=>c(!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}`,s=(n.targetMutations.get(o)??0)+1;if(n.targetMutations.set(o,s),s>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,s],[a,c])=>s.updatedAt-c.updatedAt||o.localeCompare(a))[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 dp={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 ke(e){return dp[e??"combined"]}var To=[Dt.created,Dt.updated,Dt.deleted];function Eo(e,t,r){let i=To.map((o)=>e.subscribe(o,(s)=>(t.send({type:o,payload:s.payload}),{success:!0}))),n=t.onEvent((o)=>{if(!To.includes(o.type))return;e.deliverPeer(o.type,o.payload).catch((s)=>{r.warn(`Failed to deliver peer event ${o.type}`,{error:s})})});return()=>{for(let o of i)o();n()}}var up=20,pp=0.5,mp=0.06,gp=5;function Ao(e){return async({answer:t})=>{let i=(await e.entityService.search({query:t,options:{limit:up,minScore:pp,visibilityScope:A("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-mp).slice(0,gp).map(({entity:o})=>ko(o,e))}}function fp(e,t,r,i,n){return[Oo,Mo,Lo].map((o)=>e.observe(o.name,async(s)=>{let a=o.schema.safeParse(s.payload);if(a.success&&a.data.entityType===t&&(r===null||a.data.entityId===r)){await i();let c=o.name.replace("entity:","");n.debug(`${t} entity ${c}, cache refreshed`)}return{success:!0}}))}function jo(e,t,r,i){return fp(e,t,t,async()=>{await r(),await je(e,Uo,{entityType:t},"shell")},i)}async function hp(e,t,r){let i=yp(e.kind);if(!i)return null;try{let n=t.scoped({namespace:i,refKind:e.kind,routePath:""});return vp(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 yp(e){return e===Ae.refKind?Ae.namespace:null}function vp(e,t){let{record:r,content:i}=e;if(bp(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 bp(e){let t=e.toLowerCase();return t.startsWith("text/")||t==="application/json"}function qo(e){let{config:t,entityService:r,logger:i,messageBus:n,aiService:o,mcpService:s,conversationService:a,runtimeUploadRegistry:c,disposables:d,executionOnly:u=!1}=e,p=No.createFresh(r,i,t.identity);d.push(...jo(n,L.BRAIN_CHARACTER,()=>p.refreshCache(),i));let m=Ho.createFresh(r,i,t.profile),g=Wo.createFresh(i,async(R)=>{let w=await Pt(n,"shell:canonical-identity-service",R).catch(()=>null);if(!w?.canonicalId)return null;return{userId:w.userId,canonicalId:w.canonicalId,displayName:w.displayName}}),f=Fo({guestPricing:$o(o.getConfig().model),model:o.getModel(),answerModel:o.getAnswerModel?.(),modelId:o.getConfig().model,webSearch:o.getConfig().webSearch,temperature:o.getConfig().temperature,reasoningEffort:o.getConfig().reasoningEffort,messageBus:n}),h=Bo(t.name),v=new bt(t.entityDisplay),y={isCitable:(R)=>v.isCitable(R),urlFor:(R,w)=>v.generateUrl(R,w),siteBaseUrl:t.siteBaseUrl},S=_o.createFresh(s,a,p,m,i,{agentFactory:f,turnEvents:Zo(n),canonicalIdentityResolver:g,entityLinks:y,...e.generationUsage?{generationUsage:e.generationUsage}:{},...e.embeddingUsage?{embeddingUsage:e.embeddingUsage}:{},...t.embedding.enabled?{indexReadiness:r,guestAnswerSources:Ao({entityService:r,...y})}:{},uploadAttachmentResolver:(R)=>hp(R,c,i),guestAskedBefore:async(R)=>{let w=await Ge(n,Do,R,"shell:agent-service");return w.status==="answered"?w.answers.find((x)=>x.hit)?.hit:void 0},agentContextProvider:async(R)=>{let w=await Ge(n,zo,R,"shell:agent-service");return w.status==="answered"?w.answers.flatMap((x)=>x.items):[]},...h?{assistantAgentId:h}:{},...t.agentInstructions&&{agentInstructions:t.agentInstructions}});if(d.push(...jo(n,L.ANCHOR_PROFILE,()=>m.refreshCache(),i)),!u)d.push(n.subscribe(Qe.identityChanged,async()=>(S.invalidateAgent(),{success:!0})));return{identityService:p,profileService:m,canonicalIdentityService:g,agentService:S}}var Ke=T.Service("@brains/job-queue/JobQueueService"),zt=T.Service("@brains/job-queue/BatchJobManager"),Ot=T.Service("@brains/job-queue/JobProgressMonitor"),Mt=T.Service("@brains/job-queue/JobQueueWorker");function Vo(e){return ce(Ke,()=>{let t=e.service??Jo.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 Yo(e){let t=!1,r=b.gen(function*(){let i=yield*Ke,n=e.batchJobManager??Qo.createFresh(i,e.logger),o=e.jobProgressMonitor??Ko.createFresh(i,e.messageBus,n,e.logger,e.progressMonitorMode),s=e.jobQueueWorker??Go.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(zt,n).pipe(T.add(Ot,o),T.add(Mt,s))});return{layer:V.effectContext(b.acquireRelease(r,(i)=>t?b.void:Sp(i))),abandon:()=>{t=!0}}}function Sp(e){let t=T.get(e,Mt),r=T.get(e,Ot),i=T.get(e,zt);return b.gen(function*(){let n=yield*b.exit(b.tryPromise({try:()=>t.stop(),catch:(c)=>c})),o=yield*b.exit(b.tryPromise({try:()=>r.stop(),catch:(c)=>c})),s=yield*b.exit(b.tryPromise({try:async()=>{await i.stop()},catch:(c)=>c})),a=[n,o,s].find(k.isFailure);if(a)yield*b.die(de.squash(a.cause))})}function Rp(e,t=(r)=>process.exit(r)){return(r)=>{e.error("Job queue worker requires process restart",{reason:r,exitCode:1}),t(1)}}function Lt(e){let t=b.runSyncExit(E.close(e,k.void));if(k.isFailure(t))throw de.squash(t.cause)}function Xo(e){let t=e.operationContext??Ut.createFresh(),r=b.runSync(E.make()),i,n;try{let o=b.runSync(V.buildWithScope(Vo({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)),s=T.get(o,Ke),a=b.runSync(E.make());i=a;let c=Yo({messageBus:e.messageBus,logger:e.logger,operationContext:t,...e.projectionBatchScope&&{projectionBatchScope:e.projectionBatchScope},onWorkerUnhealthy:Rp(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=c;let d=b.runSync(V.buildWithScope(c.layer.pipe(V.provide(V.succeed(Ke,s))),a)),u=T.get(d,zt),p=T.get(d,Ot),m=T.get(d,Mt),g,f=!1,h=!1;return{batchJobManager:u,jobProgressMonitor:p,jobQueueService:s,jobQueueWorker:m,closeRuntime:()=>(f=!0,g??=b.runPromise(E.close(a,k.void)),g),rollbackRuntime:()=>{if(f)return;f=!0,c.abandon(),Lt(a)},closeDatabase:()=>{if(h)return;h=!0,Lt(r)}}}catch(o){if(i)try{n?.abandon(),Lt(i)}catch(s){e.logger.warn("Failed to release partial job runtime acquisition",s)}try{Lt(r)}catch(s){e.logger.warn("Failed to release partial job database acquisition",s)}throw o}}function ts(e){return{deliver:async(t)=>{let r=await wt(e,es,{title:t.title,body:t.body,...t.html?{html:t.html}:{}},"shell.recurring-checks");if(r.status==="unavailable")return!1;if(r.status==="failed"||r.data.status!=="sent")throw Error("Recurring alert delivery failed");return!0}}}function is(e){return{sourceId:"recurring-checks",displayName:"Recurring checks",list:async()=>(await e.listOpenAlerts()).map((t)=>({id:t.id,title:rs(t.title,160),summary:rs(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 rs(e,t){return e.length<=t?e:e.slice(0,t)}function ns(e,t){if(t)return t;let r={debug:Ve.DEBUG,info:Ve.INFO,warn:Ve.WARN,error:Ve.ERROR}[e.logging.level];return Ee.createFresh({level:r,context:e.logging.context,format:e.logging.format==="json"?"json":"text",...e.logging.file?{logFile:e.logging.file}:{}})}function ti(e){return{providerKeys:e.ai.providerKeys,model:e.ai.model,temperature:e.ai.temperature,webSearch:e.ai.webSearch,...e.ai.reasoningEffort&&{reasoningEffort:e.ai.reasoningEffort},...e.ai.modelRuntimeUrl?{modelRuntimeUrl:e.ai.modelRuntimeUrl}:{},...e.ai.answerModel?{answerModel:e.ai.answerModel}:{},...e.ai.visionModel?{visionModel:e.ai.visionModel}:{},...e.ai.imageModel?{imageModel:e.ai.imageModel}:{}}}function De(e){return{url:e.url,...e.authToken?{authToken:e.authToken}:{}}}function As(e){let{config:t,dependencies:r,initializerLogger:i,lifecycle:n,processRole:o,peerChannel:s}=e;i.debug("Initializing Shell services");let a=ke(o),c=ns(t,r?.logger),d=r?.operationContext??Ut.createFresh(),u=[],p=xs.createFresh(!r?.embeddingService),m=r?.embeddingService??Cs.createFresh({providerKeys:t.ai.providerKeys,profile:ws(t.ai.embeddingModel),runtimeUrl:t.ai.modelRuntimeUrl,logger:c,usage:p}),g=Is.createFresh(),f=r?.aiService??Ps.createFresh(ti(t),c,g),h=r?.entityRegistry??as.createFresh(c),v=r?.messageBus??ss.createFresh(c,d);if(s)u.push(Eo(v,s,c));let y=r?.templateRegistry??ls.createFresh(c),S=r?.dataSourceRegistry??cs.createFresh(c),R=r?.renderService??us.createFresh(y),w=r?.daemonRegistry??At.createFresh(c),x=r?.pluginManager??ks.createFresh(c,w),I=r?.permissionService??new ds(t.permissions,{spaces:t.spaces,entityActionFloor:(G)=>h.getEntityTypeConfig(G).actionPolicy}),M=r?.profileKindRegistry??new Es(t.profileKind),re=r?.channelRegistry??new fs,U=r?.inboxRegistry??new ys,_=r?.inboxFollowUpRegistry??new vs(c),st=r?.operationalHealthRegistry??new Ts,at=r?.accountSettingsRegistry??new gs,ct=new hs,ie=new Rt,lt=r?.attachmentRegistry??bs.createFresh(),$e=r?.runtimeUploadRegistry??Ss.createFresh({dataDir:t.dataDir,logger:c}),J=n.buildLayer(So({config:De(t.runtimeStateDatabase),logger:c,...r?.runtimeStateService&&{service:r.runtimeStateService}})),xe=T.get(J,Kr),ne=r?.projectionRuntimeSupervisor??jt.createFresh(d,{runtimeState:xe}),oe=r?.mcpService??Rs.createFresh(v,c),Ar={},Ud={runFreshBatchScope:(G)=>Ar.current?Ar.current.runFreshBatchScope(G):G()},dt=Xo({dependencies:r,jobQueueConfig:{...De(t.jobQueueDatabase),brainVersion:t.version},workerConcurrency:t.jobQueue.workerConcurrency,messageBus:v,operationContext:d,projectionBatchScope:Ud,projectionAdmission:ne,handlerRegistrationMode:a.handlerRegistrationMode,progressMonitorMode:a.progressMonitorMode,logger:c}),{batchJobManager:$d,jobProgressMonitor:Bd,jobQueueService:jr,jobQueueWorker:_d}=dt;n.addSyncFinalizer(()=>dt.closeDatabase()),n.addSyncFinalizer(()=>dt.rollbackRuntime());let Be=r?.recurringCheckService??new It({brainId:t.siteBaseUrl??t.dataDir,scheduler:new qe,runtimeState:xe,clock:b.runSync(os.Clock),jobQueue:jr,logger:c,delivery:ts(v)});n.addSyncFinalizer(()=>Be.abandon()),U.registerSource("shell.recurring-checks",is(Be)),n.addSyncFinalizer(()=>U.unregisterPlugin("shell.recurring-checks"));let dn=(G,zr)=>{if(!a.serves)return;w.register(G,zr,"shell"),n.addSyncFinalizer(()=>w.abandon(G))};dn("shell:recurring-checks",{start:()=>Be.start(),stop:()=>Be.stop()});let Zd=n.buildLayer(ro({embeddingService:m,embeddingsEnabled:t.embedding.enabled,entityRegistry:h,logger:c,jobQueueService:jr,messageBus:v,mutationAdmission:ne,...r?.projectionRuntime?.now&&{projectionNow:r.projectionRuntime.now},dbConfig:De(t.database),embeddingDbConfig:De(t.embeddingDatabase),...r?.entityService&&{service:r.entityService}})),ut=T.get(Zd,Hr);Ar.current=ut.getProjectionStore();let Fd=n.buildLayer(eo({dbConfig:De(t.conversationDatabase),logger:c,messageBus:v,...r?.conversationService&&{service:r.conversationService}})),Dr=T.get(Fd,Nr);dn("shell:guest-retention",Co({intervalMs:60000,logger:c,run:async()=>{await Dr.deleteExpiredGuestConversations(100)}})),n.addSyncFinalizer(()=>{for(let G of u.splice(0))try{G()}catch(zr){c.warn("Failed to dispose shell subscription",zr)}});let un=Yn(I,v),Nd=r?.contentService??new ms({logger:c,entityService:ut,aiService:f,templateRegistry:y,dataSourceRegistry:S,generationAuthorizer:new ps(I,un)}),{identityService:Hd,profileService:Wd,canonicalIdentityService:qd,agentService:Jd}=qo({config:t,entityService:ut,embeddingService:m,embeddingUsage:p,...!r?.aiService?{generationUsage:g}:{},entityRegistry:h,logger:c,messageBus:v,aiService:f,mcpService:oe,conversationService:Dr,runtimeUploadRegistry:$e,disposables:u,executionOnly:!a.serves});return{logger:c,operationContext:d,projectionRuntimeSupervisor:ne,disposables:u,entityRegistry:h,messageBus:v,renderService:R,daemonRegistry:w,pluginManager:x,templateRegistry:y,dataSourceRegistry:S,mcpService:oe,embeddingService:m,entityService:ut,aiService:f,conversationService:Dr,contentService:Nd,callerAuthorizer:un,jobQueueService:jr,jobQueueWorker:_d,batchJobManager:$d,jobProgressMonitor:Bd,jobServicesLifecycle:dt,permissionService:I,identityService:Hd,profileService:Wd,canonicalIdentityService:qd,profileKindRegistry:M,channelRegistry:re,inboxRegistry:U,inboxFollowUpRegistry:_,operationalHealthRegistry:st,accountSettingsRegistry:at,authRegistry:ct,atprotoProjectionRegistry:ie,agentService:Jd,attachmentRegistry:lt,runtimeUploadRegistry:$e,runtimeStateService:xe,recurringCheckService:Be}}function Ls(e,t){e.register(ri.name,ri),t.debug("Shell system templates registered")}function Us(e,t){e.register(Ne.BASE_ENTITY_DISPLAY,{name:"base-entity-display",description:"Display template for base entities",schema:ii,formatter:new js,requiredPermission:"public"}),t.debug("Base entity display template registered")}function $s(e,t){e.registerEntityType(L.NOTE,ii,new Ds,{projectionSourceRole:"primary"}),t.debug("Fallback base entity adapter registered")}function Bs(e,t){let r=new zs;e.registerEntityType(L.BRAIN_CHARACTER,r.schema,r,{classification:"system",projectionSource:!1,projectionSourceRole:"excluded"}),t.debug("Brain character entity support registered")}function _s(e,t){let r=new Os;e.registerEntityType(L.ANCHOR_PROFILE,r.schema,r,{classification:"system",projectionSourceRole:"canonical"}),t.debug("Anchor profile entity support registered")}async function Zs(e){let{plugins:t,pluginManager:r,logger:i,initOptions:n}=e,o=n?.registrationContext?.executionOnly,s=o?t.filter((a)=>a.type!=="interface"):t;i.debug(`Found ${s.length} plugins to register`);for(let a of s)i.debug(`Registering plugin: ${a.id}`),r.registerPlugin(a);if(await r.initializePlugins(n?.registrationContext),o)await r.registerInterfaceChannels(t.filter((a)=>a.type==="interface"),n.registrationContext);if(!n?.registerOnly)for(let{id:a,error:c}of r.getFailedPlugins()){let d=r.getPlugin(a);if(c instanceof Ms||d?.requiresDaemonStartup?.())throw c}i.debug("Plugin initialization complete")}class $t{logger;config;processRole;peerChannel;static createFresh(e,t,r,i){return new $t(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){Ls(e,this.logger)}registerBaseEntityDisplayTemplate(e){Us(e,this.logger)}registerFallbackBaseEntity(e){$s(e,this.logger)}registerBrainCharacterSupport(e){Bs(e,this.logger)}registerAnchorProfileSupport(e){_s(e,this.logger)}async initializePlugins(e,t){await Zs({plugins:this.config.plugins,pluginManager:e,logger:this.logger,initOptions:t})}initializeServices(e,t){return As({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=Ns.createFresh(t,r);e.registerHandler(Fs.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(L.NOTE))this.registerFallbackBaseEntity(t);this.logger.debug("Shell registration phase complete")}catch(n){throw this.logger.error("Shell initialization failed",n),n}}}var ni=l.strictObject({waveId:l.string().trim().min(1),ruleId:l.string().trim().min(1)});class oi{ruleById;store;coordinator;getJobStatus;onDiagnostic;inputContext;executionContext;reconcileTargets;graphFingerprint;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.graphFingerprint=e.graphFingerprint,this.now=e.now}validateAndParse(e){let t=ni.safeParse(e);return t.success?t.data:null}async onTerminalError(e,t,r){let i=ni.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=ni.parse(e),o=this.ruleById.get(n.ruleId);if(!o){if(await this.settleRetiredRuleJob(n.waveId))return{waveId:n.waveId,ruleId:n.ruleId,outcome:"superseded",inputFingerprint:null,changedTargets:[]};throw Error(`Projection rule "${n.ruleId}" is not executable`)}let[s,a,c,d]=await Promise.all([this.store.listWaveInputs(n.waveId),this.store.listWaveRules(n.waveId),this.store.getWave(n.waveId),this.getJobStatus(t)]);if(!c)throw Error(`Projection wave "${n.waveId}" does not exist`);if(c.status!=="running"&&c.status!=="superseded")throw Error(`Projection wave "${n.waveId}" is not active`);let u=a.find((x)=>x.ruleId===n.ruleId);if(!u)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:(d?.retryCount??0)+1,cutoffGeneration:c.cutoffGeneration};if(await this.recordDiagnostic({...p,event:"attempt-started"}),c.status==="superseded"){let x=await this.store.listPendingInputs();return await this.recordDiagnostic({...p,event:"apply-completed",applyOutcome:"superseded",highestPendingGeneration:Bt(x)}),{waveId:n.waveId,ruleId:o.id,outcome:"superseded",inputFingerprint:null,changedTargets:[]}}if(await this.store.supersedeWaveIfStale(n.waveId,this.now())){let x=await this.store.listPendingInputs();return await this.recordDiagnostic({...p,event:"apply-completed",applyOutcome:"superseded",highestPendingGeneration:Bt(x)}),await this.coordinator.continueAfterSupersession(n.waveId),{waveId:n.waveId,ruleId:o.id,outcome:"superseded",inputFingerprint:null,changedTargets:[]}}let m=Cp(s,a,u.level),g=await o.selectInput({waveId:n.waveId,inputs:m},this.inputContext,i),f=o.fingerprint(g),h={...p,inputFingerprint:f,selectedSourceCount:Pp(g,m)};await this.recordDiagnostic({...h,event:"input-selected"});let v={ruleId:o.id,ruleVersion:o.version,inputFingerprint:f},y=await this.store.getRuleMemo(v);await this.recordDiagnostic({...h,event:"memo-resolved",memoHit:y!==null});let S;if(y)S=y.writeIntents;else{await this.recordDiagnostic({...h,event:"derive-started",memoHit:!1});try{S=await o.derive(g,this.executionContext,i),await this.recordDiagnostic({...h,event:"derive-completed",memoHit:!1})}catch(x){throw await this.recordDiagnostic({...h,event:i.aborted?"derive-cancelled":"derive-failed",memoHit:!1}),x}}let R=await this.store.applyRuleResult({waveId:n.waveId,ruleId:o.id,ruleVersion:o.version,inputFingerprint:f,writeIntents:S,completedAt:this.now()}),w=await this.store.listPendingInputs();if(!R)return await this.recordDiagnostic({...h,event:"apply-completed",memoHit:y!==null,applyOutcome:"superseded",highestPendingGeneration:Bt(w)}),await this.coordinator.continueAfterSupersession(n.waveId),{waveId:n.waveId,ruleId:o.id,outcome:"superseded",inputFingerprint:f,changedTargets:[]};return await this.recordDiagnostic({...h,event:"apply-completed",memoHit:y!==null,applyOutcome:"applied",highestPendingGeneration:Bt(w)}),await this.reconcileTargets(R.changedTargets),await this.coordinator.advanceActiveWave(n.waveId),{waveId:n.waveId,ruleId:o.id,outcome:"applied",inputFingerprint:f,changedTargets:R.changedTargets}}async settleRetiredRuleJob(e){let t=await this.store.getWave(e);if(t?.status==="superseded")return!0;if(t?.status!=="running"||t.graphFingerprint===this.graphFingerprint)return!1;if((await this.store.supersedeWave(e,this.now())).status!=="superseded")return!1;return await this.coordinator.continueAfterSupersession(e),!0}async recordDiagnostic(e){if(!this.onDiagnostic)return;try{await this.onDiagnostic(e)}catch(t){this.executionContext.logger.warn("Projection diagnostics callback failed",t)}}}function Pp(e,t){if(typeof e==="object"&&e!==null&&"sources"in e&&Array.isArray(e.sources))return e.sources.length;return t.length}function Bt(e){if(e.length===0)return null;return e.reduce((t,r)=>Math.max(t,r.generation),e[0]?.generation??0)}function Cp(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((s)=>({sourceType:s.entityType,sourceId:s.entityId,revision:s.contentHash??`deleted:${s.entityType}:${s.entityId}`,operation:s.operation})));return[...i,...n]}function xp(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 ze="shell:projection-rule";class ai{store;queue;graph;ruleById;graphFingerprint;createWaveId;beforeWaveCompletion;scheduleWakeup;onScheduledWakeupError;now;operationQueue=new Hs;scheduledWakeup;constructor(e){this.store=e.store,this.queue=e.queue,this.graph=e.graph,this.ruleById=Ep(e.graph,e.rules),this.graphFingerprint=kp(e.graph,e.rules),this.createWaveId=e.createWaveId,this.beforeWaveCompletion=e.beforeWaveCompletion??(async()=>{}),this.scheduleWakeup=e.scheduleWakeup??Ip,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(si(r))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 s=await this.advanceWave(e);if(si(s))await this.startNextWaveInternal();return s}let t=await this.store.listPendingInputs();if(t.length===0)return this.cancelScheduledWakeup(),null;let r=Tp(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(si(o))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)return this.store.supersedeWave(e.id,this.now());let t=await this.store.listWaveRules(e.id);if(t.length===0){let s=await this.store.listWaveInputs(e.id),a=qs(this.graph,this.ruleById,s);if(a.length===0)return this.completeWave(e);await this.store.putWaveRules(e.id,a),t=await this.store.listWaveRules(e.id)}if(t.every((s)=>s.status==="completed"))return this.completeWave(e,t);let r=t.find((s)=>s.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:xp(i),failedAt:this.now()});let n=Math.min(...t.filter((s)=>s.status!=="completed").map((s)=>s.level)),o=t.filter((s)=>s.level===n&&s.status==="pending");return await Promise.all(o.map((s)=>this.enqueueRule(e.id,s))),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:ze,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 si(e){return e.status==="completed"||e.status==="superseded"}function Ip(e,t){let r=setTimeout(()=>{t()},e);return()=>clearTimeout(r)}function Tp(e,t,r){let n=qs(e,t,r).reduce((s,a)=>Math.max(s,t.get(a.ruleId)?.sourceChangeBatchDelayMs??0),0);if(n===0)return 0;return r.reduce((s,a)=>Math.max(s,a.markedAt),0)+n}function Ep(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 kp(e,t){return Ws({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 qs(e,t,r){let i=new Map(e.projections.map((c)=>[c.id,c])),n=Js(e,(c)=>[c.from,c.to]),o=new Set(e.projections.filter((c)=>Ap(c,r)).map((c)=>c.id)),s=[...o];while(s.length>0){let c=s.flatMap((d)=>n.get(d)??[]).filter((d)=>i.has(d)&&!o.has(d));for(let d of c)o.add(d);s=[...new Set(c)].sort()}let a=jp(e,o);return[...o].map((c)=>{let d=i.get(c),u=t.get(c),p=a.get(c);if(!d||!u||p===void 0)throw Error(`Cannot plan projection rule "${c}"`);return{ruleId:c,targetType:d.targetType,level:p}}).sort((c,d)=>c.level-d.level||c.ruleId.localeCompare(d.ruleId))}function Ap(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 jp(e,t){let r=Js(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((s)=>(r.get(s)??[]).every((a)=>i.has(a))).sort();if(o.length===0)throw Error("Reachable projection graph is not acyclic");for(let s of o){let a=(r.get(s)??[]).map((d)=>i.get(d)).filter((d)=>d!==void 0),c=a.length===0?0:Math.max(...a)+1;i.set(s,c),n.delete(s)}}return i}function Js(e,t){let r=new Map;for(let i of e.edges){let n=t(i);if(!n)continue;let[o,s]=n,a=r.get(o);if(a)a.push(s);else r.set(o,[s])}return r}async function Gs(e){let t=new ai({store:e.store,queue:e.queue,graph:e.graph,rules:e.rules,createWaveId:e.createWaveId,beforeWaveCompletion:e.beforeWaveCompletion,onScheduledWakeupError:(s)=>e.logger.error("Scheduled projection wakeup failed",s),...e.scheduleWakeup&&{scheduleWakeup:e.scheduleWakeup},now:e.now}),r=new oi({rules:e.rules,store:e.store,coordinator:t,getJobStatus:(s)=>e.queue.getStatus(s),...e.onDiagnostic&&{onDiagnostic:e.onDiagnostic},inputContext:e.inputContext,executionContext:e.executionContext,reconcileTargets:e.reconcileTargets,graphFingerprint:t.graphFingerprint,now:e.now});e.queue.registerHandler(ze,r,"shell");let i=()=>{},n=()=>{};try{if(e.activationMode!=="executor"){let s=async(u)=>{if(u)await e.reconcileBatches?.();await t.startNextWave()},a,c=(u)=>{if(a)return a;let p=Promise.resolve().then(()=>s(u));a=p;let m=()=>{if(a===p)a=void 0};return p.then(m,m),p},d=async()=>{if(a)return;if(await e.store.hasActiveProjectionBatch())return;await c(!1)};i=e.setWakeup(d),await c(!0),n=(e.scheduleSweep??Dp)(e.sweepIntervalMs??1000,async()=>{try{await c(!0)}catch(u){e.logger.error("Projection coordination sweep failed",u)}})}}catch(s){throw n(),i(),e.queue.unregisterHandler(ze),s}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(ze)}}}function Dp(e,t){let r=setInterval(()=>{t()},e);return r.unref(),()=>clearInterval(r)}import{existsSync as wm}from"fs";import{mkdir as Pm,writeFile as Cm}from"fs/promises";import{join as xm,resolve as Za}from"path";function Qs(e,t,r){let i=e.filter((n)=>n.kind==="handler"&&n.method===t);return i.find((n)=>n.match==="exact"&&n.fullPath===r)??i.filter((n)=>n.match==="prefix"&&(r===n.fullPath||r.startsWith(`${n.fullPath.replace(/\/$/,"")}/`))).sort((n,o)=>o.fullPath.length-n.fullPath.length)[0]??i.find((n)=>n.match==="claim"&&n.claims?.(r))}import{resolve as H,join as vm,sep as bm}from"path";var Ks=Symbol();var Vs=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,(r)=>r.toLowerCase())}}).formData();var zp=1e4,_t=(e)=>("headers"in e),ea=async(e,t=Object.create(null))=>{let{all:r=!1,dot:i=!1}=t,n=(_t(e)?e.headers:e.raw.headers).get("Content-Type")?.split(";")[0].trim().toLowerCase();if(n==="multipart/form-data"||n==="application/x-www-form-urlencoded")return Op(e,{all:r,dot:i});return{}};async function Op(e,t){if(!_t(e)&&e.bodyCache.formData)return Ys(await e.bodyCache.formData,t);let r=_t(e)?e.headers:e.raw.headers,i=await e.arrayBuffer(),n=Vs(i,r.get("Content-Type")||"");if(!_t(e))e.bodyCache.formData=n;let o=await n;if(o)return Ys(o,t);return{}}function Ys(e,t){let r=Object.create(null),i={count:0};if(e.forEach((n,o)=>{if(!(t.all||o.endsWith("[]")))r[o]=n;else Mp(r,o,n)}),t.dot)Object.entries(r).forEach(([n,o])=>{if(n.includes("."))Lp(r,n,o,i),delete r[n]});return r}var Mp=(e,t,r)=>{if(e[t]!==void 0)if(Array.isArray(e[t]))e[t].push(r);else e[t]=[e[t],r];else if(!t.endsWith("[]"))e[t]=r;else e[t]=[r]},Lp=(e,t,r,i)=>{if(/(?:^|\.)__proto__\./.test(t))return;let n=e,o=t.split(".",34);if(o.length>33)Xs();o.forEach((s,a)=>{if(a===o.length-1)n[s]=r;else{if(!n[s]||typeof n[s]!=="object"||Array.isArray(n[s])||n[s]instanceof File){if(i.count++>=zp)Xs();n[s]=Object.create(null)}n=n[s]}})},Xs=()=>{throw Error("Nesting limit exceeded")};var li=(e)=>{let t=e.split("/");if(t[0]==="")t.shift();return t},ta=(e)=>{let{groups:t,path:r}=Up(e),i=li(r);return $p(i,t)},Up=(e)=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,i)=>{let n=`@${i}`;return t.push([n,r]),n}),{groups:t,path:e}},$p=(e,t)=>{for(let r=t.length-1;r>=0;r--){let[i]=t[r];for(let n=e.length-1;n>=0;n--)if(e[n].includes(i)){e[n]=e[n].replace(i,t[r][1]);break}}return e},Zt={},ra=(e,t)=>{if(e==="*")return"*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let i=`${e}#${t}`;if(!Zt[i])if(r[2])Zt[i]=t&&t[0]!==":"&&t[0]!=="*"?[i,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)];else Zt[i]=[e,r[1],!0];return Zt[i]}return null},ia=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,(r)=>{try{return t(r)}catch{return r}})}},di=(e)=>ia(e,decodeURI),ui=(e)=>{let t=e.url,r=t.indexOf("/",t.indexOf(":")+4),i=r;for(;i<t.length;i++){let n=t.charCodeAt(i);if(n===37){let o=t.indexOf("?",i),s=t.indexOf("#",i),a=o===-1?s===-1?void 0:s:s===-1?o:Math.min(o,s),c=t.slice(r,a);return di(c.includes("%25")?c.replace(/%25/g,"%2525"):c)}else if(n===63||n===35)break}return t.slice(r,i)};var na=(e)=>{let t=ui(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},pe=(e,t,...r)=>{if(r.length)t=pe(t,...r);return`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`},Ft=(e)=>{if(e.charCodeAt(e.length-1)!==63||!e.includes(":"))return null;let t=e.split("/"),r=[],i="";return t.forEach((n)=>{if(n!==""&&!/\:/.test(n))i+="/"+n;else if(/\:/.test(n))if(n.charCodeAt(n.length-1)===63){if(r.length===0&&i==="")r.push("/");else r.push(i);let o=n.slice(0,-1);i+="/"+o,r.push(i)}else i+="/"+n}),r.filter((n,o,s)=>s.indexOf(n)===o)},Nt=(e)=>e.indexOf("%")!==-1?ia(e,Bp):e,ci=(e)=>{if(e.indexOf("+")!==-1)e=e.replace(/\+/g," ");return Nt(e)},oa=(e,t,r)=>{let i=e.indexOf("#",8);if(i!==-1)e=e.slice(0,i);let n;if(!r&&t&&t.indexOf("%")===-1&&t.indexOf("+")===-1){let a=e.indexOf("?",8);if(a===-1)return;if(!e.startsWith(t,a+1))a=e.indexOf(`&${t}`,a+1);while(a!==-1){let c=e.charCodeAt(a+t.length+1);if(c===61){let d=a+t.length+2,u=e.indexOf("&",d);return ci(e.slice(d,u===-1?void 0:u))}else if(c==38||isNaN(c))return"";a=e.indexOf(`&${t}`,a+1)}if(n=/[%+]/.test(e),!n)return}let o=Object.create(null);n??=/[%+]/.test(e);let s=e.indexOf("?",8);while(s!==-1){let a=e.indexOf("&",s+1),c=e.indexOf("=",s);if(c>a&&a!==-1)c=-1;let d=e.slice(s+1,c===-1?a===-1?void 0:a:c);if(n)d=ci(d);if(s=a,d==="")continue;let u;if(c===-1)u="";else if(u=e.slice(c+1,a===-1?void 0:a),n)u=ci(u);if(r){if(!(o[d]&&Array.isArray(o[d])))o[d]=[];o[d].push(u)}else o[d]??=u}return t?o[t]:o},sa=oa,aa=(e,t)=>oa(e,t,!0),Bp=decodeURIComponent;var ca=class{raw;#t;#e;routeIndex=0;path;bodyCache={};constructor(e,t="/",r=[[]]){this.raw=e,this.path=t,this.#e=r}param(e){return e?this.#r(e):this.#o()}#r(e){let t=this.#e[0][this.routeIndex]?.[1][e],r=this.#i(t);return r&&Nt(r)}#o(){let e={},t=Object.keys(this.#e[0][this.routeIndex]?.[1]??{});for(let r of t){let i=this.#i(this.#e[0][this.routeIndex][1][r]);if(i!==void 0)e[r]=Nt(i)}return e}#i(e){return this.#e[1]?this.#e[1][e]:e}query(e){return sa(this.url,e)}queries(e){return aa(this.url,e)}header(e){if(e)return this.raw.headers.get(e)??void 0;let t=Object.create(null);return this.raw.headers.forEach((r,i)=>{t[i]=r}),t}async parseBody(e){return ea(this,e)}#n=(e)=>{let{bodyCache:t,raw:r}=this,i=t[e];if(i)return i;for(let n in t)return t[n].then((o)=>{if(n==="json")o=JSON.stringify(o);let s=n==="formData"?void 0:r.headers.get("content-type");return new Response(o,{headers:s?{"Content-Type":s}:void 0})[e]()});return t[e]=r[e]()};json(){return this.#n("text").then((e)=>JSON.parse(e))}text(){return this.#n("text")}arrayBuffer(){return this.#n("arrayBuffer")}bytes(){return this.#n("arrayBuffer").then((e)=>new Uint8Array(e))}blob(){return this.#n("blob")}formData(){return this.#n("formData")}addValidatedData(e,t){(this.#t??={})[e]=t}valid(e){return this.#t?.[e]}get url(){return this.raw.url}get method(){return this.raw.method}get[Ks](){return this.#e}get matchedRoutes(){return this.#e[0].map(([[,e]])=>e)}get routePath(){return this.#e[0].map(([[,e]])=>e)[this.routeIndex].path}};var la={Stringify:1,BeforeStream:2,Stream:3},da=(e,t)=>{let r=new String(e);return r.isEscaped=!0,r.callbacks=t,r};var pi=async(e,t,r,i,n)=>{if(typeof e==="object"&&!(e instanceof String)){if(!(e instanceof Promise))e=e.toString();if(e instanceof Promise)e=await e}let o=e.callbacks;if(!o?.length)return Promise.resolve(e);if(n)n[0]+=e;else n=[e];let s=Promise.all(o.map((a)=>a({phase:t,buffer:n,context:i}))).then((a)=>Promise.all(a.filter(Boolean).map((c)=>pi(c,t,!1,i,n))).then(()=>n[0]));if(r)return da(await s,o);else return s};var _p="text/plain; charset=UTF-8",mi=(e,t)=>({"Content-Type":e,...t}),Ye=(e,t)=>new Response(e,t),gi=class{#t;#e;env={};#r;finalized=!1;error;#o;#i;#n;#d;#c;#l;#a;#u;#p;constructor(e,t){if(this.#t=e,t)this.#i=t.executionCtx,this.env=t.env,this.#l=t.notFoundHandler,this.#p=t.path,this.#u=t.matchResult}get req(){return this.#e??=new ca(this.#t,this.#p,this.#u),this.#e}get event(){if(this.#i&&"respondWith"in this.#i)return this.#i;else throw Error("This context has no FetchEvent")}get executionCtx(){if(this.#i)return this.#i;else throw Error("This context has no ExecutionContext")}get res(){return this.#n||=Ye(null,{headers:this.#a??=new Headers})}set res(e){if(this.#n&&e){e=Ye(e.body,e);for(let[t,r]of this.#n.headers.entries()){if(t==="content-type")continue;if(t==="set-cookie"){let i=this.#n.headers.getSetCookie();e.headers.delete("set-cookie");for(let n of i)e.headers.append("set-cookie",n)}else e.headers.set(t,r)}}this.#n=e,this.finalized=!0}render=(...e)=>(this.#c??=(t)=>this.html(t),this.#c(...e));setLayout=(e)=>this.#d=e;getLayout=()=>this.#d;setRenderer=(e)=>{this.#c=e};header=(e,t,r)=>{if(this.finalized)this.#n=Ye(this.#n.body,this.#n);let i=this.#n?this.#n.headers:this.#a??=new Headers;if(t===void 0)i.delete(e);else if(r?.append)i.append(e,t);else i.set(e,t)};status=(e)=>{this.#o=e};set=(e,t)=>{this.#r??=new Map,this.#r.set(e,t)};get=(e)=>this.#r?this.#r.get(e):void 0;get var(){if(!this.#r)return{};return Object.fromEntries(this.#r)}#s(e,t,r){let i=this.#n?new Headers(this.#n.headers):this.#a;if(typeof t==="object"&&t.headers){i??=new Headers;for(let[o,s]of new Headers(t.headers))if(o==="set-cookie")i.append(o,s);else i.set(o,s)}if(r){if(!i){let o=0;for(let s in r)if(++o>1||typeof r[s]!=="string"){i=new Headers;break}}if(i)for(let o in r){let s=r[o];if(typeof s==="string")i.set(o,s);else{i.delete(o);for(let a of s)i.append(o,a)}}}let n=typeof t==="number"?t:t?.status??this.#o;return Ye(e,{status:n,headers:i??r})}newResponse=(...e)=>this.#s(...e);body=(e,t,r)=>this.#s(e,t,r);text=(e,t,r)=>!this.#a&&!this.#o&&!t&&!r&&!this.finalized?new Response(e):this.#s(e,t,mi(_p,r));json=(e,t,r)=>this.#s(JSON.stringify(e),t,mi("application/json",r));html=(e,t,r)=>{let i=(n)=>this.#s(n,t,mi("text/html; charset=UTF-8",r));return typeof e==="object"?pi(e,la.Stringify,!1,{}).then(i):i(e)};redirect=(e,t)=>{let r=String(e);return this.header("Location",!/[^\x00-\xFF]/.test(r)?r:encodeURI(r)),this.newResponse(null,t??302)};notFound=()=>(this.#l??=()=>Ye(),this.#l(this))};var fi=(e,t,r)=>(i,n)=>{let o=-1;return s(0);async function s(a){if(a<=o)throw Error("next() called multiple times");o=a;let c,d=!1,u;if(e[a])u=e[a][0][0],i.req.routeIndex=a;else u=a===e.length&&n||void 0;if(u)try{c=await u(i,()=>s(a+1))}catch(p){if(p instanceof Error&&t)i.error=p,c=await t(p,i),d=!0;else throw p}else if(i.finalized===!1&&r)c=await r(i);if(c&&(i.finalized===!1||d))i.res=c;return i}};var ua=["get","post","put","delete","options","patch","query"],Ht="Can not add a route since the matcher is already built.",Wt=class extends Error{};var hi="__COMPOSED_HANDLER";var Zp=(e)=>e.text("404 Not Found",404),pa=(e,t)=>{if("getResponse"in e){let r=e.getResponse();return t.newResponse(r.body,r)}return console.error(e),t.text("Internal Server Error",500)},ma=class e{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...ua,"all"].forEach((n)=>{this[n]=(o,...s)=>{let a=n.toUpperCase();if(typeof o==="string")this.#t=o;else this.#o(a,this.#t,o);return s.forEach((c)=>{this.#o(a,this.#t,c)}),this}}),this.on=(n,o,...s)=>{for(let a of[o].flat()){this.#t=a;for(let c of[n].flat()){let d=c.toUpperCase();for(let u of s)this.#o(d,this.#t,u)}}return this},this.use=(n,...o)=>{if(typeof n==="string")this.#t=n;else this.#t="*",o.unshift(n);return o.forEach((s)=>{this.#o("ALL",this.#t,s)}),this};let{strict:r,...i}=t;Object.assign(this,i),this.getPath=r??!0?t.getPath??ui:na}#e(){let t=new e({router:this.router,getPath:this.getPath});return t.errorHandler=this.errorHandler,t.#r=this.#r,t.routes=this.routes,t}#r=Zp;errorHandler=pa;route(t,r){let i=this.basePath(t);return r.routes.map((n)=>{let o;if(r.errorHandler===pa)o=n.handler;else o=async(s,a)=>(await fi([],r.errorHandler)(s,()=>n.handler(s,a))).res,o[hi]=n.handler;i.#o(n.method,n.path,o,n.basePath)}),this}basePath(t){let r=this.#e();return r._basePath=pe(this._basePath,t),r}onError=(t)=>(this.errorHandler=t,this);notFound=(t)=>(this.#r=t,this);mount(t,r,i){let n,o;if(i)if(typeof i==="function")o=i;else if(o=i.optionHandler,i.replaceRequest===!1)n=(c)=>c;else n=i.replaceRequest;let s=o?(c)=>{let d=o(c);return Array.isArray(d)?d:[d]}:(c)=>{let d=void 0;try{d=c.executionCtx}catch{}return[c.env,d]};n||=(()=>{let c=pe(this._basePath,t),d=c==="/"?0:c.length;return(u)=>{let p=new URL(u.url);return p.pathname=this.getPath(u).slice(d)||"/",new Request(p,u)}})();let a=async(c,d)=>{let u=await r(n(c.req.raw),...s(c));if(u)return u;await d()};return this.#o("ALL",pe(t,"*"),a),this}#o(t,r,i,n){r=pe(this._basePath,r);let o={basePath:n!==void 0?pe(this._basePath,n):this._basePath,path:r,method:t,handler:i};this.router.add(t,r,[i,o]),this.routes.push(o)}#i(t,r){if(t instanceof Error)return this.errorHandler(t,r);throw t}#n(t,r,i,n){if(n==="HEAD")return(async()=>new Response(null,await this.#n(t,r,i,"GET")))();let o=this.getPath(t,{env:i}),s=this.router.match(n,o),a=new gi(t,{path:o,matchResult:s,env:i,executionCtx:r,notFoundHandler:this.#r});if(s[0].length===1){let d;try{d=s[0][0][0][0](a,async()=>{a.res=await this.#r(a)})}catch(u){return this.#i(u,a)}return d instanceof Promise?d.then((u)=>u||(a.finalized?a.res:this.#r(a))).catch((u)=>this.#i(u,a)):d??this.#r(a)}let c=fi(s[0],this.errorHandler,this.#r);return(async()=>{try{let d=await c(a);if(!d.finalized)throw Error("Context is not finalized. Did you forget to return a Response object or `await next()`?");return d.res}catch(d){return this.#i(d,a)}})()}fetch=(t,...r)=>this.#n(t,r[1],r[0],t.method);request=(t,r,i,n)=>{if(t instanceof Request)return this.fetch(r?new Request(t,r):t,i,n);return t=t.toString(),this.fetch(new Request(/^https?:\/\//.test(t)?t:`http://localhost${pe("/",t)}`,r),i,n)};fire=()=>{addEventListener("fetch",(t)=>{t.respondWith(this.#n(t.request,t,void 0,t.request.method))})}};var j=()=>Object.create(null);var qt=[];function yi(e,t){let r=this.buildAllMatchers(),i=(n,o)=>{let s=r[n]||r.ALL,a=s[2][o];if(a)return a;let c=o.match(s[0]);if(!c)return[[],qt];let d=c.indexOf("",1);return[s[1][d],c]};return this.match=i,i(e,t)}var vi="[^/]+";var bi="(?:|/.*)",me=Symbol(),ga=new Set(".\\+*[^]$()");function Fp(e,t){if(e.length===1)return t.length===1?e<t?-1:1:-1;if(t.length===1)return 1;if(e===".*"||e==="(?:|/.*)")return t==="(?:|/.*)"?-1:1;else if(t===".*"||t==="(?:|/.*)")return-1;if(e==="[^/]+")return 1;else if(t==="[^/]+")return-1;return e.length===t.length?e<t?-1:1:t.length-e.length}var fa=class e{#t;#e;#r=j();insert(t,r,i,n,o){let s=this;for(let a=0,c=t.length;a<c;a++){let d=t[a],u=d.length===1?d==="*"?a===c-1?["","",".*"]:["","",vi]:null:d==="/*"?["","",bi]:d.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),p;if(u){let m=u[1],g=u[2]||"[^/]+";if(m&&u[2]){if(g===".*")throw me;if(g=g.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(g))throw me;if(g.length===1&&ga.has(g))throw me}if(p=s.#r[g],!p){if(g!==".*"&&g!=="(?:|/.*)"){for(let f in s.#r)if((g.length>1||f.length>1)&&f!==".*"&&f!=="(?:|/.*)")throw me}p=s.#r[g]=new e}if(m!=="")p.#e??=n.varIndex++,i.push([m,p.#e])}else if(p=s.#r[d],!p){for(let m in s.#r)if(m.length>1&&m!==".*"&&m!=="(?:|/.*)")throw me;p=s.#r[d]=new e}s=p}if(s.#t!==void 0)throw me;s.#t=o?-1:r}buildRegExpStr(){let t=Object.keys(this.#r).sort(Fp).map((r)=>{let i=this.#r[r],n=i.buildRegExpStr();return n===""?"":(typeof i.#e==="number"?`(${r})@${i.#e}`:ga.has(r)?`\\${r}`:r)+n}).filter(Boolean);if(typeof this.#t==="number"&&this.#t!==-1)t.unshift(`#${this.#t}`);if(t.length===0)return"";if(t.length===1)return t[0];return"(?:"+t.join("|")+")"}};var Si=class{#t={varIndex:0};#e=new fa;#r=0;paths=j();insert(e,t){if(t){this.#e.insert(e.split(""),0,[],this.#t,!0);return}let r=[],i=[],n=e;for(let s=0;;){let a=!1;if(n=n.replace(/\{[^}]+\}/g,(c)=>{let d=`@\\${s}`;return i[s]=[d,c],s++,a=!0,d}),!a)break}let o=n.match(/(?::[^\/]+)|(?:\/\*$)|./g)||[];for(let s=i.length-1;s>=0;s--){let[a]=i[s];for(let c=o.length-1;c>=0;c--)if(o[c].indexOf(a)!==-1){o[c]=o[c].replace(a,i[s][1]);break}}this.#e.insert(o,this.#r,r,this.#t,!1),this.paths[e]=[this.#r++,r]}buildRegExp(){let e=this.#e.buildRegExpStr();if(e==="")return[/^$/,[],[]];let t=0,r=[],i=[];return e=e.replace(/#(\d+)|@(\d+)|\.\*\$/g,(n,o,s)=>{if(o!==void 0)return r[++t]=Number(o),"$()";if(s!==void 0)return i[Number(s)]=++t,"";return""}),[new RegExp(`^${e}`),r,i]}};var ha=j();function ya(e){return ha[e]??=new RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(t,r)=>r?`\\${r}`:t==="/*"?bi:t==="*"?".*":`/:${vi}`)}$`)}function Jt(e,t){for(let r of Object.keys(e).sort((i,n)=>n.length-i.length))if(ya(r).test(t))return[...e[r]]}var Gt=class{name="RegExpRouter";#t;#e;#r;constructor(){this.#t={["ALL"]:j()},this.#e={["ALL"]:j()},this.#r={["ALL"]:new Si}}#o(e,t){try{this.#r[e].insert(t,!/\*|\/:/.test(t))}catch(r){throw r===me?new Wt(t):r}}add(e,t,r){let i=this.#t,n=this.#e;if(!i)throw Error(Ht);if(!i[e]){this.#r[e]=new Si;for(let a of[i,n]){a[e]=j();for(let c in a.ALL)a[e][c]=[...a.ALL[c]],this.#o(e,c)}}if(t==="/*")t="*";let o=e==="ALL"?Object.keys(i):[e];if(/\*$/.test(t)){let a=ya(t);for(let c of o)if(!i[c][t])this.#o(c,t),i[c][t]=Jt(i[c],t)||Jt(i.ALL,t)||[];for(let c of[i,n])for(let d of o)for(let u in c[d])a.test(u)&&c[d][u].push([r,t]);return}let s=Ft(t)||[t];for(let a of s)for(let c of o){if(!n[c][a])this.#o(c,a),n[c][a]=Jt(i[c],a)||Jt(i.ALL,a)||[];n[c][a].push([r,a])}}match=yi;buildAllMatchers(){let e=j();for(let t of Object.keys(this.#e))e[t]=this.#i(t);return this.#t=this.#e=this.#r=void 0,ha=j(),e}#i(e){let t=this.#t[e],r=this.#e[e],i=this.#r[e],n=j(),o=[],[s,a,c]=i.buildRegExp();for(let d of[t,r])for(let u in d){let p=d[u],m=i.paths[u];if(!m){n[u]=[p.map(([g])=>[g,j()]),qt];continue}o[m[0]]=p.map(([g,f])=>[g,i.paths[f][1].reduceRight((h,[v],y)=>(h[v]=c[m[1][y][1]],h),j())])}return[s,a.map((d)=>o[d]),n]}};var va=class{name="SmartRouter";#t=[];#e=[];constructor(e){this.#t=e.routers}add(e,t,r){if(!this.#e)throw Error(Ht);this.#e.push([e,t,r])}match(e,t){if(!this.#e)throw Error("Fatal error");let r=this.#t,i=this.#e,n=r.length,o=0,s;for(;o<n;o++){let a=r[o];try{for(let c=0,d=i.length;c<d;c++)a.add(...i[c]);s=a.match(e,t)}catch(c){if(c instanceof Wt)continue;throw c}this.match=a.match.bind(a),this.#t=[a],this.#e=void 0;break}if(o===n)throw Error("Fatal error");return this.name=`SmartRouter + ${this.activeRouter.name}`,s}get activeRouter(){if(this.#e||this.#t.length!==1)throw Error("No active router has been determined yet.");return this.#t[0]}};var Ri=j(),Np=0,ba=class e{#t=[];#e=j();#r=[];#o;#i=Ri;insert(t,r,i){let n=this,o=ta(r),s=new Set,a=0;for(let c of o){let d=o[++a],u=ra(c,d)||(d===void 0&&c&&c.indexOf("*")===c.length-1?c:null),p=Array.isArray(u),m=p?u[0]:u||c,g=n.#e[m]||=new e;if(u&&!g.#o)g.#o=u,n.#r.push(g);if(n=g,p)s.add(u[1])}n.#t.push({[t]:{handler:i,possibleKeys:[...s],score:++Np}})}#n(t,r,i,n,o){for(let s=0,a=r.#t.length;s<a;s++){let c=r.#t[s],d=c[i]||c.ALL;if(d){d.params=j(),t.push(d);for(let u=0,p=d.possibleKeys.length;u<p;u++){let m=d.possibleKeys[u];d.params[m]=o?.[m]&&!u?o[m]:n[m]??o?.[m]}}}}search(t,r){let i=[];this.#i=Ri;let n=[this],o=li(r),s=[],a=o.length,c=null;for(let d=0;d<a;d++){let u=o[d],p=d===a-1,m=[];for(let f=0,h=n.length;f<h;f++){let v=n[f],y=v.#e[u];if(y)if(y.#i=v.#i,p){if(y.#e["*"])this.#n(i,y.#e["*"],t,v.#i);this.#n(i,y,t,v.#i)}else m.push(y);for(let S of v.#r){let R=S.#o,w=v.#i===Ri?{}:{...v.#i};if(typeof R==="string"){if(R==="*"||u.startsWith(R.slice(0,-1))){if(this.#n(i,S,t,v.#i),R==="*")S.#i=w,m.push(S)}continue}let[,x,I]=R;if(!u&&I===!0)continue;if(I!==!0){if(!c){c=[];let U=r[0]==="/"?1:0;for(let _=0;_<a;_++)c[_]=U,U+=o[_].length+1}let M=r.slice(c[d]),re=I.exec(M);if(re){if(w[x]=re[0],this.#n(i,S,t,v.#i,w),re[0].length===M.length&&S.#e["*"])this.#n(i,S.#e["*"],t,v.#i,w);for(let U in S.#e){S.#i=w;let _=re[0].match(/\//g)?.length??0;(s[_]||=[]).push(S);break}continue}}if(I===!0||I.test(u))if(w[x]=u,p){if(this.#n(i,S,t,w,v.#i),S.#e["*"])this.#n(i,S.#e["*"],t,w,v.#i)}else S.#i=w,m.push(S)}}let g=s.shift();n=g?m.concat(g):m}if(i[1])i.sort((d,u)=>d.score-u.score);return[i.map(({handler:d,params:u})=>[d,u])]}};var wi=class{name="TrieRouter";#t=new ba;add(e,t,r){for(let i of Ft(t)||[t])this.#t.insert(e,i,r)}match(e,t){return this.#t.search(e,t)}};var Pi=class extends ma{constructor(e={}){super(e);this.router=e.router??new va({routers:[new Gt,new wi]})}};var Qt=(e)=>("server"in e.env)?e.env.server:e.env;var Oe=/^\s*(?:text\/(?!event-stream(?:[;\s]|$))[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|msgpack|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|vnd\.msgpack|wasm|x-httpd-php|x-javascript|x-msgpack|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml|msgpack))(?:[;\s]|$)/i;var Ci=(e,t=Hp)=>{let r=e.match(/\.([a-zA-Z0-9]+?)$/);if(!r)return;return t[r[1].toLowerCase()]};var Hp={aac:"audio/aac",avi:"video/x-msvideo",avif:"image/avif",av1:"video/av1",bin:"application/octet-stream",bmp:"image/bmp",css:"text/css; charset=utf-8",csv:"text/csv; charset=utf-8",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gif:"image/gif",gz:"application/gzip",htm:"text/html; charset=utf-8",html:"text/html; charset=utf-8",ico:"image/x-icon",ics:"text/calendar; charset=utf-8",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript; charset=utf-8",json:"application/json",jsonld:"application/ld+json",map:"application/json",mid:"audio/x-midi",midi:"audio/x-midi",mjs:"text/javascript; charset=utf-8",mp3:"audio/mpeg",mp4:"video/mp4",mpeg:"video/mpeg",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",opus:"audio/opus",otf:"font/otf",pdf:"application/pdf",png:"image/png",rtf:"application/rtf",svg:"image/svg+xml; charset=utf-8",tif:"image/tiff",tiff:"image/tiff",ts:"video/mp2t",ttf:"font/ttf",txt:"text/plain; charset=utf-8",wasm:"application/wasm",webm:"video/webm",weba:"audio/webm",webmanifest:"application/manifest+json",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml; charset=utf-8",xml:"application/xml; charset=utf-8",zip:"application/zip","3gp":"video/3gpp","3g2":"video/3gpp2",gltf:"model/gltf+json",glb:"model/gltf-binary"};var Sa=(...e)=>{let t=e.filter((n)=>n!=="").join("/");t=t.replace(/(?<=\/)\/+/g,"");let r=t.split("/"),i=[];for(let n of r)if(n===".."&&i.length>0&&i.at(-1)!=="..")i.pop();else if(n!==".")i.push(n);return i.join("/")||"."};var Ra={br:".br",zstd:".zst",gzip:".gz"},Wp=Object.keys(Ra),qp="index.html",wa=(e)=>{let t=e.root??"./",r=e.path,i=e.join??Sa;return async(n,o)=>{if(n.finalized)return o();let s;if(e.path)s=e.path;else try{if(!e.allowPercentInPath&&n.req.path.includes("%"))throw Error();if(s=di(n.req.path),/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}|\\/.test(s))throw Error()}catch{return await e.onNotFound?.(n.req.path,n),o()}let a=i(t,!r&&e.rewriteRequestPath?e.rewriteRequestPath(s):s);if(e.isDir&&await e.isDir(a))a=i(a,qp);let c=e.getContent,d=await c(a,n);if(d instanceof Response)return n.newResponse(d.body,d);if(d!=null){let u=e.mimes&&Ci(a,e.mimes)||Ci(a);if(n.header("Content-Type",u||"application/octet-stream"),e.precompressed&&(!u||Oe.test(u))){let p=new Set(n.req.header("Accept-Encoding")?.split(",").map((m)=>m.trim()));for(let m of Wp){if(!p.has(m))continue;let g=await c(a+Ra[m],n);if(g){d=g,n.header("Content-Encoding",m),n.header("Vary","Accept-Encoding",{append:!0});break}}}return await e.onFound?.(a,n),n.body(d)}await e.onNotFound?.(a,n),await o()}};import{stat as Jp}from"fs/promises";import{join as Gp}from"path";var xi=(e={})=>async function(r,i){return wa({...e,getContent:async(s)=>{let a=Bun.file(s);return await a.exists()?a:null},join:Gp,isDir:async(s)=>{let a;try{a=(await Jp(s)).isDirectory()}catch{}return a}})(r,i)};var Pa="x-hono-disable-ssg",ew=(()=>{try{return new Response("SSG is disabled",{status:404,headers:{[Pa]:"true"}})}catch{return null}})();var{write:Nw}=Bun;var Ca=(e)=>(...t)=>{if(typeof t[0]==="function"){let[r,i]=t;return async function(o,s){let a=await e(o,await r(o),i);if(a)return a;await s()}}else{let[r,i,n]=t;return(async()=>{let o=await e(r,i,n);if(!o)throw Error("Failed to upgrade WebSocket");return o})()}};var Yp=Ca((e,t)=>{let r=Qt(e);if(!r)throw TypeError("env has to include the 2nd argument of fetch.");if(r.upgrade(e.req.raw,{data:{events:t,url:new URL(e.req.url),protocol:e.req.header("sec-websocket-protocol")?.split(",")[0]?.trim()??""}}))return new Response(null)});var Ia=(e)=>e===32||e===9||e===10||e===13,Kt=(e,t)=>{while(t<e.length){if(!Ia(e.charCodeAt(t)))break;t++}return t},Xe=(e,t)=>{while(t>0){if(!Ia(e.charCodeAt(t-1)))break;t--}return t},xa=(e,t)=>{while(t<e.length){let r=e.charCodeAt(t);if(r===59)return[t+1,!0];if(r===44)return[t+1,!1];t++}return[t,!1]},Xp=(e,t)=>{let r=t,i=!1;while(r<e.length){let n=e.charCodeAt(r);if(i&&n===92)r++;else if(n===34)i=!i;else if(!i&&n===44)return r+1;r++}return r},em=(e,t)=>{t=Kt(e,t);let r=t,i,n,o=!1;while(r<e.length){let c=e.charCodeAt(r);if(c===61){i=e.slice(t,Xe(e,r)),r++;break}if(c===59)return[r+1,void 0,void 0,!0];if(c===44)return[r+1,void 0,void 0,!1];r++}if(i===void 0)return[r,void 0,void 0,!1];if(r=Kt(e,r),e.charCodeAt(r)===61){let c=xa(e,r+1);return[c[0],i,void 0,c[1]]}let s=!1,a=r;while(r<e.length){let c=e.charCodeAt(r);if(s&&c===92)r++;else if(c===34){if(s){let d=Kt(e,r+1),u=e.charCodeAt(d);if(d<e.length&&!(u===59||u===44)){let p=xa(e,d);return[p[0],i,void 0,p[1]]}if(n=e.slice(a+1,r),n.includes("\\"))n=n.replace(/\\(.)/g,"$1");if(u===44)return[d+1,i,n,!1];if(u===59)o=!0,d++;r=d;break}s=!0}else if(!s&&(c===59||c===44)){if(n=e.slice(a,Xe(e,r)),c===59)o=!0;r++;break}r++}return[r,i,n??e.slice(a,Xe(e,r)),o]},tm=(e,t)=>{let r={type:"",params:Object.create(null),q:1};t=Kt(e,t);let i=t;while(i<e.length){let a=e.charCodeAt(i);if(a===59||a===44){if(r.type=e.slice(t,Xe(e,i)),i++,a===44)return[i,r.type?r:void 0];if(!r.type)return[Xp(e,i),void 0];break}i++}if(!r.type)return r.type=e.slice(t,Xe(e,e.length)),[e.length,r.type?r:void 0];let n,o,s;while(i<e.length){if([i,n,o,s]=em(e,i),n&&o)r.params[n]=o;if(!s)break}return[i,r]},Ta=(e)=>{if(!e)return[];let t=[],r=0,i,n=!1,o;while(r<e.length)if([r,i]=tm(e,r),i){if(i.q=rm(i.params.q??i.params.Q),t.push(i),o&&o.q<i.q)n=!0;o=i}if(n)t.sort((s,a)=>a.q-s.q);return t},rm=(e)=>{if(e===void 0)return 1;if(e==="")return 1;if(e==="NaN")return 0;let t=Number(e);if(Number.isNaN(t))return 1;if(t<0)return 0;if(t>1)return 1;return t};var im=["gzip","deflate"],nm=/(?:^|,)\s*?no-transform\s*?(?:,|$)/i,om=(e,t)=>{if(e===void 0)return;let r=Ta(e),i=r.find((o)=>o.type==="*")?.q,n;for(let o of t){let s=r.find((c)=>c.type.toLowerCase()===o),a=s?s.q:i??0;if(a===1)return o;else if(a>0&&(!n||a>n.q))n={encoding:o,q:a}}return n?.encoding},sm=/(?:^|,)\s*accept-encoding\s*(?:,|$)/i,Ea=(e)=>{let t=e?.threshold??1024,r=e?.encoding?[e.encoding]:im,i=e?.contentTypeFilter??Oe,n=typeof i==="function"?(o)=>{let s=o.headers.get("Content-Type");return s&&i(s)}:(o)=>{let s=o.headers.get("Content-Type");return s&&i.test(s)};return async function(s,a){await a();let c=s.res.headers.get("Content-Length");if(s.res.status===206||s.res.headers.has("Content-Encoding")||s.res.headers.has("Transfer-Encoding")||s.req.method==="HEAD"||c&&Number(c)<t||!n(s.res)||!am(s.res))return;let d=s.res.headers.get("Vary");if(d!=="*"&&!(d&&sm.test(d)))s.header("Vary",d?`${d}, Accept-Encoding`:"Accept-Encoding");let u=s.req.header("Accept-Encoding"),p=om(u,r);if(!p||!s.res.body)return;let m=new CompressionStream(p);s.res=new Response(s.res.body.pipeThrough(m),s.res),s.res.headers.delete("Content-Length"),s.res.headers.set("Content-Encoding",p);let g=s.res.headers.get("ETag");if(g&&!g.startsWith("W/"))s.res.headers.set("ETag",`W/${g}`)}},am=(e)=>{let t=e.headers.get("Cache-Control");return!t||!nm.test(t)};import{Readable as ka}from"stream";import{createDeflate as cm,createGzip as lm}from"zlib";var dm=["gzip","deflate"],um=/(?:^|,)\s*?no-transform\s*?(?:,|$)/i,Aa=(e)=>{if(typeof CompressionStream<"u")return Ea(e);let t=e?.threshold??1024;return async function(i,n){await n();let o=i.res.headers.get("Content-Length");if(i.res.headers.has("Content-Encoding")||i.res.headers.has("Transfer-Encoding")||i.req.method==="HEAD"||o&&Number(o)<t||!pm(i.res)||!mm(i.res))return;let s=i.req.header("Accept-Encoding"),a=e?.encoding??dm.find((c)=>s?.includes(c));if(!a||!i.res.body)return;try{let c=a==="gzip"?lm():cm(),d=ka.fromWeb(i.res.body).pipe(c),u=ka.toWeb(d);i.res=new Response(u,i.res),i.res.headers.delete("Content-Length"),i.res.headers.set("Content-Encoding",a)}catch(c){console.error("Compression error:",c)}}},pm=(e)=>{let t=e.headers.get("Content-Type");return t&&Oe.test(t)},mm=(e)=>{let t=e.headers.get("Cache-Control");return!t||!um.test(t)};var gm=(e,t)=>{if(!e)return t;let r=new Uint8Array(new ArrayBuffer(e.byteLength+t.byteLength));return r.set(new Uint8Array(e),0),r.set(t,e.byteLength),r};var ja=async(e,t)=>{if(!e)return null;let r=void 0,i,n=0,o=async(a)=>{r=await t(gm(r,a))},s=e.getReader();for(;;){let{value:a,done:c}=await s.read();if(c)break;let d=0;while(d<a.byteLength){let u=a.byteLength-d;if(n===0&&u>=262144){await o(a.subarray(d,d+262144)),d+=262144;continue}let p=n+u;if(p<262144){if(!i)i=a.slice(d);else{if(i.byteLength<p){let g=new Uint8Array(new ArrayBuffer(Math.min(262144,Math.max(p,i.byteLength*2))));g.set(i.subarray(0,n)),i=g}i.set(a.subarray(d),n)}n=p;break}let m=262144-n;if(i?.byteLength!==262144){let g=new Uint8Array(new ArrayBuffer(262144));if(i)g.set(i.subarray(0,n));i=g}i.set(a.subarray(d,d+m),n),await o(i),n=0,d+=m}}if(i&&n>0)await o(i.subarray(0,n));if(!r)return null;return Array.prototype.map.call(new Uint8Array(r),(a)=>a.toString(16).padStart(2,"0")).join("")};var fm=["cache-control","content-location","date","etag","expires","vary"],Da=(e)=>e.replace(/^W\//,"");function hm(e,t){return t!=null&&t.split(",").some((r)=>Da(r.trim())===Da(e))}function ym(e){if(!e){if(crypto&&crypto.subtle)e=(t)=>crypto.subtle.digest({name:"SHA-1"},t)}return e}var za=(e)=>{let t=new Set((e?.retainedHeaders??fm).map((n)=>n.toLowerCase())),r=e?.weak??!1,i=ym(e?.generateDigest);return async function(o,s){let a=o.req.header("If-None-Match")??null;if(await s(),!(o.req.method==="GET"||o.req.method==="HEAD"||o.req.method==="QUERY")||!o.res.ok)return;let c=o.res,d=c.headers.get("ETag");if(!d){if(!i)return;let u=await ja(c.clone().body,i);if(u===null)return;d=r?`W/"${u}"`:`"${u}"`}if(a==="*"||hm(d,a)){o.res=new Response(null,{status:304,statusText:"Not Modified",headers:{ETag:d}});for(let u of Array.from(o.res.headers.keys()))if(!t.has(u.toLowerCase()))o.res.headers.delete(u)}else o.res.headers.set("ETag",d)}};function Ii(e,t){return async(r)=>{let i=r.req.raw,n=i.headers.get("content-type")??"",o=i.headers.get("accept")?.includes("application/json"),s={};if(n.includes("application/json"))s=await i.json();else if(n.includes("form")){let m=await i.formData();for(let[g,f]of m.entries())s[g]=f}let a=await t(e,s),c=typeof a==="object"&&a!==null&&"data"in a?a.data:a,d=Oa.safeParse(c),u=d.success?d.data:c,p=d.success&&d.data.success===!0;if(o)return r.json(u,p?200:400);if(p&&e.definition.successRedirect)return r.redirect(e.definition.successRedirect);if(!p&&e.definition.errorRedirect)return r.redirect(e.definition.errorRedirect);return r.json(u,p?200:400)}}function et(e,t){return e===t||e.startsWith(t+bm)}var Ma="public, max-age=31536000, immutable";function Sm(e){return e.getRoutes?.()??[]}var Rm=255;class Yt{logger;options;routes=Object.freeze([]);productionServer=null;transport=new WeakMap;async fillSitePage(e,t,r){let i=r.slot;if(!i)return;let n=H(e,`.${t}`,"index.html");if(!et(n,H(e)))return;let o=Bun.file(n);if(!await o.exists())return;let s=`<div ${$a}="${i.name}"></div>`,a=await o.text();if(!a.includes(s))return;let c=new Headers(r.headers);return c.delete("Content-Length"),c.delete("Content-Encoding"),c.delete("ETag"),c.set("Content-Type","text/html; charset=utf-8"),new Response(a.replace(s,()=>i.html),{status:r.status,headers:c})}isPreviewHost(e){if(!e)return!1;let t=e.replace(/:\d+$/,"").toLowerCase();return/^(?:preview\..+|.+-preview\..+)$/.test(t)}constructor(e){this.logger=e.logger,this.options={...e,productionDistDir:H(process.cwd(),e.productionDistDir),sharedImagesDir:H(process.cwd(),e.sharedImagesDir),...e.previewDistDir&&{previewDistDir:H(process.cwd(),e.previewDistDir)}}}async start(){if(this.productionServer){this.logger.warn("Webserver already running");return}this.routes=Object.freeze([...Sm(this.options)]);let e=this.createApp({distDir:this.options.productionDistDir,compress:!0,defaultCache:"public, max-age=3600",immutableExtensions:/\.(jpg|jpeg|png|gif|ico|webp|svg|woff|woff2)$/,revalidateExtensions:/\.(js|css)$/,healthEndpoint:!0}),t=this.options.previewDistDir?this.createApp({distDir:this.options.previewDistDir,compress:!1,defaultCache:"no-cache",immutableExtensions:/\.(jpg|jpeg|png|gif|ico|webp|svg|woff|woff2)$/,healthEndpoint:!1}):void 0,r=this.options.serve??Bun.serve;try{this.productionServer=r({...this.options.hostname?{hostname:this.options.hostname}:{},port:this.options.productionPort,idleTimeout:this.options.idleTimeout??Rm,fetch:async(i,n)=>{let o=n?.requestIP(i)?.address;this.transport.set(i,Object.freeze({...o?{remoteAddress:o}:{}}));let s=await this.serveImageFastPath(i);if(s)return s;let a=new URL(i.url).pathname;if(a==="/health"||a.startsWith("/health/"))return e.fetch(i);if(t&&this.isPreviewHost(i.headers.get("host")))return t.fetch(i);return e.fetch(i)}})}catch(i){let n=String(i);if(n.includes("EADDRINUSE")||n.includes("address already in use")||/Is port \d+ in use\?/.test(n))throw Error(`Port ${this.options.productionPort} is already in use. Another brain may be running \u2014 stop it first or configure a different port.`,{cause:i});throw i}this.logger.info(`Production server listening on http://localhost:${this.productionServer.port}`)}async stop(){if(this.productionServer)await this.productionServer.stop(),this.productionServer=null;this.logger.debug("Webserver stopped")}getStatus(){return{running:this.productionServer!==null,productionUrl:this.productionServer?`http://localhost:${this.productionServer.port}`:void 0,previewUrl:this.productionServer&&this.options.previewDistDir?`http://localhost:${this.productionServer.port}`:void 0}}createApp(e){let t=new Pi;if(e.healthEndpoint)t.all("/health",(r)=>r.notFound()),t.get("/health/live",(r)=>r.json({status:"alive",uptime:Math.floor(process.uptime()),checkedAt:new Date().toISOString()},200)),t.get("/health/ready",async(r)=>{let i=await this.getReadinessData();return r.json(i,i.status==="ready"?200:503)}),t.get("/health/operate",async(r)=>{let i=await this.getReadinessData(),n;if(this.options.getOperationalInfo)try{n=await this.options.getOperationalInfo()}catch(o){i={...i,operationalStatus:"degraded",checks:[...i.checks,{name:"app-info",status:"unhealthy",message:C(o)}]}}return r.json({...i,...n&&{app:n}},i.operationalStatus==="operational"?200:503)});if(t.use("/*",async(r,i)=>{let n=await this.handleDynamicRoute(r,e);if(n)return n;return i()}),e.compress)t.use("/*",Aa());return t.use("/*",za()),t.use("/*",async(r,i)=>{if(await i(),r.res.status>=400)r.header("Cache-Control","no-cache");else if(r.res.headers.has("Cache-Control"))return;else if(e.revalidateExtensions?.test(r.req.path))r.header("Cache-Control","no-cache");else if(e.immutableExtensions.test(r.req.path))r.header("Cache-Control",Ma);else r.header("Cache-Control",e.defaultCache)}),t.use("/*",async(r,i)=>{if(r.req.path===Vt)return r.notFound();return i()}),t.use("/*",this.createCleanUrlMiddleware(e.distDir)),t.use("/*",xi({root:e.distDir})),t.get(La,(r)=>r.body(Ua,200,{"Content-Type":"image/svg+xml; charset=utf-8","Cache-Control":"public, max-age=86400"})),t.notFound(async(r)=>{let i=Bun.file(vm(e.distDir,"404.html"));if(await i.exists())return r.html(await i.text(),404);return r.text("Not Found",404)}),t}async getReadinessData(){if(!this.options.getReadinessData)return{status:"ready",operationalStatus:"degraded",checkedAt:new Date().toISOString(),checks:[],resources:this.getUnavailableResourceSignals()};try{return await this.options.getReadinessData()}catch(e){return{status:"not_ready",operationalStatus:"degraded",checkedAt:new Date().toISOString(),checks:[{name:"runtime-readiness",status:"unhealthy",message:C(e)}],resources:this.getUnavailableResourceSignals()}}}getUnavailableResourceSignals(){let e=process.memoryUsage();return{memory:{rssBytes:e.rss,heapUsedBytes:e.heapUsed,heapTotalBytes:e.heapTotal},fileDescriptors:null,processes:{total:null,zombies:null},queue:null,projection:{initialized:!1,trackedRoots:0,openCircuits:[]},worker:{total:0,active:0,stale:0,latestHeartbeatAgeMs:null}}}async handleDynamicRoute(e,t){let r=e.req.method.toUpperCase(),i=e.req.path,n=Qs(this.routes,r,i);if(n){if(!t.healthEndpoint&&n.preview!==!0)return null;if(n.sharedHostAdmission==="deny")return e.text("Unauthorized",401);let s=await n.handler(e.req.raw,this.transport.get(e.req.raw));if(s instanceof Ti&&s.slot)return await this.fillSitePage(t.distDir,i,s)??s;if(r==="GET"&&s instanceof Ti&&s.status===200){let a=H(t.distDir,`.${i}`,"index.html");if(et(a,H(t.distDir))){let c=Bun.file(a);if(await c.exists()){let d=new Headers(s.headers);return d.delete("Content-Length"),d.delete("Content-Encoding"),d.delete("ETag"),d.set("Content-Type","text/html; charset=utf-8"),new Response(c,{headers:d})}}}return s}if(!t.healthEndpoint)return null;let o=this.routes.find((s)=>s.kind==="tool"&&s.fullPath===i&&s.method===r);if(o){if(o.sharedHostAdmission==="deny")return e.text("Unauthorized",401);if(!this.options.executeTool)return e.text("HTTP tool route unavailable",500);return Ii({pluginId:o.ownerPluginId,fullPath:o.fullPath,definition:o.definition},this.options.executeTool)(e)}return null}async serveImageFastPath(e){let t;try{t=new URL(e.url)}catch{return null}if(!t.pathname.startsWith("/images/"))return null;let r=t.pathname.slice(8),i=H(this.options.sharedImagesDir,r);if(!et(i,this.options.sharedImagesDir))return null;let n=Bun.file(i);if(!await n.exists())return null;return new Response(n,{headers:{"Cache-Control":Ma}})}createCleanUrlMiddleware(e){return async(t,r)=>{let i=t.req.path;if(i.includes(".")||i==="/"){await r();return}let n=H(e,`.${i}`,"index.html");if(!et(n,e)){await r();return}let o=Bun.file(n);if(await o.exists())return t.html(await o.text());let s=H(e,`.${i}.html`);if(et(s,e)){let a=Bun.file(s);if(await a.exists())return t.html(await a.text())}await r()}}}function Ei(e,t){return(r,i)=>e.send({type:Xt.toolExecute(r.pluginId),payload:{toolName:r.definition.tool.includes("_")?r.definition.tool:`${r.pluginId}_${r.definition.tool}`,args:i,interfaceType:t,actor:{kind:"external",externalActorId:Ba(t,"anonymous")}},sender:t})}var ki=`<!DOCTYPE html>
11
11
  <html lang="en">
12
12
  <head>
13
13
  <meta charset="UTF-8">
@@ -74,33 +74,33 @@ ${JSON.stringify(e.data,null,2)}`);if(e.prompt)r.push(`Additional instructions:
74
74
  <p>Once built, this page will be replaced with your actual website.</p>
75
75
  </div>
76
76
  </body>
77
- </html>`;var Ba=l.strictObject({productionOutputDir:l.string().min(1),previewOutputDir:l.string().min(1),sharedImagesDir:l.string().min(1)});var W="webserver",Y=`${W}:${W}`,Im="./dist/site-production",Tm="./dist/site-preview",Em="./dist/images";function km(e){return[...e].flatMap((t)=>{let r=t.getStaticSiteOutput?.();return r?[{...Ba.parse(r),ownerPluginId:t.id}]:[]})}function Am(e,t){let[r,i]=t;if(r&&i)throw Error(`Two plugins write the site the HTTP host serves: "${r.ownerPluginId}" and "${i.ownerPluginId}"`);let n=(o,s,a,c)=>{let d=e[o];if(r&&s!==void 0&&d!==void 0&&_a(d)!==_a(s))throw Error(`http.${o} "${d}" is not where "${r.ownerPluginId}" writes the ${a} ("${s}"); remove it or set it to the same directory`);return s??d??c};return{productionDistDir:n("productionDistDir",r?.productionOutputDir,"production site",Im),previewDistDir:n("previewDistDir",r?.previewOutputDir,"preview site",Tm),sharedImagesDir:n("sharedImagesDir",r?.sharedImagesDir,"shared images",Em)}}async function jm(e,t,r){let i=[e.productionDistDir,...t?[e.previewDistDir]:[]];for(let n of i){if(wm(n))continue;await Pm(n,{recursive:!0}),await Cm(xm(n,"index.html"),ki),r.debug(`Created site directory at ${n}`)}}function Fa(e){return e?{siteUrl:`https://${e}`,previewUrl:`https://${Za(e)}`}:{siteUrl:void 0,previewUrl:void 0}}function Na(e){let{config:t,logger:r}=e,{siteUrl:i,previewUrl:n}=Fa(e.domain),o;return{start:async()=>{let s=Am(t,km(e.getPlugins()));await jm(s,t.preview,r),o??=new Yt({logger:r,productionDistDir:s.productionDistDir,sharedImagesDir:s.sharedImagesDir,productionPort:t.port,...t.hostname?{hostname:t.hostname}:{},...t.preview&&{previewDistDir:s.previewDistDir},getOperationalInfo:e.getOperationalInfo,getReadinessData:e.getReadinessData,getRoutes:e.getRoutes,executeTool:Ei(e.messageBus,W)}),await o.start()},stop:async()=>{await o?.stop()},healthCheck:async()=>{let s=o?.getStatus(),a=s?.running??!1,c=i??s?.productionUrl??`http://localhost:${t.port}`,d=n??s?.previewUrl??`http://localhost:${t.port}`,u=[];if(a){if(u.push(`Production: ${c}`),s?.previewUrl)u.push(`Preview: ${d}`)}return{status:a?"healthy":"error",message:a?u.join(", "):"Webserver not running",lastCheck:new Date,details:{preview:!!s?.previewUrl,production:a,previewUrl:s?.previewUrl?d:void 0,productionUrl:a?c:void 0}}}}}function Ha(e,t){let{siteUrl:r,previewUrl:i}=Fa(t);if(!r)return{endpoints:[],interactions:[]};let n=e.preview&&i?i:void 0;return{endpoints:[{pluginId:W,label:"Site",url:r,priority:10},...n?[{pluginId:W,label:"Preview",url:n,priority:20,visibility:"admin"}]:[]],interactions:[{pluginId:W,id:"site",label:"Public site",description:"Visit the published public site for this brain.",href:r,kind:"human",priority:10},...n?[{pluginId:W,id:"preview",label:"Preview site",description:"Open the private preview build.",href:n,kind:"admin",priority:20,visibility:"admin"}]:[]]}}var Dm=250,zm=l.object({projectionBatch:l.object({operationId:l.string().min(1),childKey:l.string().min(1)})});class Ai{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=ke(n),this.hooks=o}async boot(e){this.services.logger.debug("Starting Shell boot");let t=this.initializer;await er([()=>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 Js({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)=>{let s=await Ge(this.services.messageBus,Wa,o,"shell");if(s.status==="unavailable")return;if(s.failures.length>0||s.answers.length===0)throw Error(`Projection wave ${o.waveId} completion was not acknowledged`)},logger:this.services.logger,createWaveId:qa,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,s)=>(await this.services.jobQueueService.getJobsByRootJobId(o)).flatMap((c)=>{let d=zm.safeParse(JSON.parse(c.data));if(!d.success||d.data.projectionBatch.operationId!==s)return[];return[{jobId:c.id,childKey:d.data.projectionBatch.childKey,status:c.status,terminalAt:c.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.startHttpHost(),await this.services.entityService.reprojectRegisteredGroupings();let n=await this.services.entityService.rewriteRetiredFields();if(n.rewritten>0)this.services.logger.info("Rewrote entities carrying retired fields",{rewritten:n.rewritten});let o=await this.services.entityService.reconcileDeclaredMetadata();if(o.reconciled>0)this.services.logger.info("Re-derived declared entity metadata",{reconciled:o.reconciled});let s=Va();if(this.services.disposables.push(this.services.messageBus.subscribe(Qe.initialSyncCompleted,async(c)=>(s.resolve(Qa.safeParse(c.payload).data?.success===!0),{success:!0}))),await this.emitPluginsRegistered())i=s.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 startHttpHost(){if(!this.services.daemonRegistry.has(Y))return;await this.services.daemonRegistry.start(Y),this.services.logger.debug("Started the HTTP host before initial sync")}async emitPluginsRegistered(){let e=await this.services.messageBus.collect({type:Qe.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)&&Ga.safeParse(t.data).data?.initialSyncPending===!0)}async settleStartupContent(){await this.prepareReadyState(),await je(this.services.messageBus,Ka,{timestamp:new Date().toISOString()},"shell"),this.services.logger.debug("Emitted startup content settled event")}async loadIdentityServices(){await er([()=>this.services.identityService.refreshCache(),()=>this.services.profileService.refreshCache(),()=>this.services.canonicalIdentityService.refreshCache()]),this.services.logger.debug("Identity services loaded")}async initializeIdentityServices(){await er([()=>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 Ja(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.retitled.length>0)e.info("Corrected generated prompt titles",{targets:t.retitled});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});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 b.tryPromise({try:()=>e.backfillMissingEmbeddings(),catch:(i)=>i}).pipe(b.tap((i)=>b.sync(()=>{t.debug("Queued missing embedding backfill jobs",i)})),b.catch((i)=>b.sync(()=>{t.warn("Embedding backfill failed",i)}))).pipe(b.andThen(b.tryPromise({try:(i)=>e.awaitIndexReady({intervalMs:Dm,signal:i}),catch:(i)=>i}).pipe(b.tap((i)=>b.sync(()=>{if(i.degraded)t.warn("Semantic index ready with degraded embeddings",i);else t.debug("Semantic index ready",i)})),b.catch((i)=>b.sync(()=>{t.warn("Semantic index readiness monitor stopped",i)})))))}}var Om=l.object({}),Ya=l.string().regex(/^\d{4}-(0[1-9]|1[0-2])$/,"Expected YYYY-MM"),ec=l.array(l.string().min(1)).min(1).optional().describe("Only these entity types"),Mm=l.object({entityTypes:ec,from:Ya.optional().describe("First month, YYYY-MM"),to:Ya.optional().describe("Last month, YYYY-MM")}),Lm=l.object({staleDays:l.number().int().min(1).max(3650).default(90).describe("Days without an update before content counts as stale"),entityTypes:ec});function tc(e){let t=new Xa;return t.register(tr({type:"overview",description:"Entity counts by type, recent activity, and draft and published totals.",params:Om,handler:async(r,{entityService:i,visibilityScope:n})=>Um(i,n)})),t.register(tr({type:"publishing-cadence",description:"Pieces per month, by type: counted in the month they were published, or created when never published.",params:Mm,handler:async(r,{entityService:i,visibilityScope:n})=>Bm(i,n,r)})),t.register(tr({type:"content-health",description:"Drafts and content not updated for a long time.",params:Lm,handler:async(r,{entityService:i,visibilityScope:n})=>_m(i,n,e,r)})),t}async function Um(e,t){let r=await e.getEntityCounts(t),i={},n=0;for(let{entityType:g,count:f}of r)i[g]=f,n+=f;let o=await ji(e,t),s=Date.now(),a=s-604800000,c=s-2592000000,d=0,u=0;for(let g of o){let f=new Date(g.created).getTime();if(f>=a)d++;if(f>=c)u++}let p=ic(o),m=o.filter((g)=>g.metadata.status==="published");return{entityCounts:i,totalEntities:n,recentActivity:{last7days:d,last30days:u},contentHealth:{drafts:p.length,published:m.length}}}function $m(e){let t=e.metadata.publishedAt;return new Date(typeof t==="string"&&t?t:e.created)}function rc(e,t){return t?e.filter((r)=>t.includes(r.entityType)):e}async function Bm(e,t,r){let i=rc(await ji(e,t),r.entityTypes),n=new Map;for(let s of i){let a=$m(s);if(isNaN(a.getTime()))continue;let c=`${a.getUTCFullYear()}-${String(a.getUTCMonth()+1).padStart(2,"0")}`;if(r.from&&c<r.from||r.to&&c>r.to)continue;let d=n.get(c);if(!d)d={},n.set(c,d);d[s.entityType]=(d[s.entityType]??0)+1}return{months:Array.from(n.entries()).sort((s,a)=>a[0].localeCompare(s[0])).map(([s,a])=>{let c=0;for(let d of Object.values(a))c+=d;return{month:s,counts:a,total:c}})}}async function _m(e,t,r,i){let n=rc(await ji(e,t),i.entityTypes),o=ic(n).map((d)=>({id:d.id,entityType:d.entityType,title:typeof d.metadata.title==="string"?d.metadata.title:d.id,created:d.created})),s=Date.now(),a=s-i.staleDays*24*60*60*1000,c=n.filter((d)=>{if(r.getEntityTypeConfig(d.entityType).binaryStorage)return!1;let u=new Date(d.updated).getTime();return!isNaN(u)&&u<a}).map((d)=>({id:d.id,entityType:d.entityType,title:typeof d.metadata.title==="string"?d.metadata.title:d.id,updated:d.updated,daysSinceUpdate:Math.floor((s-new Date(d.updated).getTime())/86400000)}));return{drafts:o,stale:c}}function ic(e){return e.filter((t)=>t.metadata.status==="draft")}async function ji(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 tt{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 Di extends tt{constructor(){super((e)=>nc.parse(e),(e)=>e.url)}}class zi extends tt{constructor(){super((e)=>oc.parse(e),(e)=>e.id)}}function sc(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 Zm=["/health","/images"],Fm=new Set([Vt]),Nm=new Set(ac),Hm=new Set(["GET","POST","PUT","DELETE"]);function cc(e){let t=[];for(let[r,{plugin:i}]of e.getAllPlugins()){let n,o;try{n=i.getWebRoutes?.()??[],o=i.getApiRoutes?.()??[]}catch(s){throw Error(`Failed to collect HTTP route declarations from plugin "${r}"`,{cause:s})}t.push({pluginId:r,webRoutes:n,apiRoutes:o})}return t}function lc(e){return Fm.has(e)||Zm.some((t)=>e===t||e.startsWith(`${t}/`))}function Oi(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&&lc(e))throw Error(`Invalid HTTP route path "${e}" declared by plugin "${t}"`)}function dc(e,t,r){if(!e.has(t))throw Error(`Invalid HTTP route method "${t}" declared by plugin "${r}"`)}function Wm(e,t,r){let i=e==="claim";if(!["exact","prefix","claim"].includes(e)||i!==(typeof t==="function")||!i&&t!==void 0)throw Error(`Invalid HTTP route match "${e}" declared by plugin "${r}"`)}function qm(e,t){Oi(t.path,e.pluginId);let r=t.method??"GET";dc(Nm,r,e.pluginId);let i=t.match??"exact";Wm(i,t.claims,e.pluginId);let n=t.claims;if(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}:{},...n?{claims:(o)=>!lc(o)&&n(o)}:{},handler:t.handler})}function Jm(e,t){Oi(t.path,e.pluginId,!1);let r=`/api/${e.pluginId}${t.path}`;if(Oi(r,e.pluginId),dc(Hm,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 Gm(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 Qm(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 rr{routes;manifest;apiRoutes;webRoutes;static createFresh(){return new rr}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(qm(n,o)),r.push(Object.freeze({pluginId:n.pluginId,fullPath:o.path,definition:Object.freeze({...o})}));for(let o of n.apiRoutes){let s=Jm(n,o);t.push(s),i.push(Object.freeze({pluginId:n.pluginId,fullPath:s.fullPath,definition:s.definition}))}}return Gm(t),this.routes=Object.freeze(t),this.manifest=Qm(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 uc(e,t){e.addFinalizer(()=>t.pluginManager.shutdownPlugins()),e.addFinalizer(async()=>{if(t.daemonRegistry.has(Y))await t.daemonRegistry.unregister(Y)}),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 Km=l.discriminatedUnion("kind",[l.object({kind:l.literal("all")}).strict().describe("Search across all entity types"),l.object({kind:l.literal("type"),entityType:l.string().min(1).describe("Entity type to search")}).strict().describe("Search within one entity type")]),mc=l.object({query:l.string().describe("Search term"),scope:Km.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:l.number().optional().describe("Maximum number of results"),minScore:l.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:l.boolean().optional().describe("Include queued/failed generation stubs in results")}),gc=l.object({entityType:l.string().describe("Entity type"),id:l.string().describe("Entity ID, slug, or title"),part:l.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.")}),fc=l.object({entityType:l.string().describe("Entity type to list"),status:l.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:l.number().optional().describe("Maximum number of results (default: 20)")}),hc=l.string().min(1).describe("Upload id from the conversation's upload refs"),yc=l.object({kind:l.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:l.string().optional().describe("Stored user message ID in this conversation; omit for the latest user message."),boundaryMode:l.enum(["literal","lines","frontmatter"]).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. Use frontmatter when the pasted text opens with a --- frontmatter block: the saved text starts at its opening fence, so no startAfter is needed."),startAfter:l.string().optional().describe("Exact unique opening boundary, excluded from saved text; never a --- fence (use boundaryMode frontmatter). 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:l.string().optional().describe("Omit when the content runs to the end of the message. Otherwise the exact unique closing boundary, excluded from saved text; never a --- fence (use boundaryMode frontmatter). 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."),contentHash:l.string().optional().describe("Internal source hash returned with the confirmation; omit on the initial request.")}).strict(),vc=l.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."),it=l.object({kind:l.literal("uploads").describe("Keep several uploaded files from one request: one call listing every attached file, never one call per file; entityType names the note type for extract-markdown files, or another type such as post."),items:l.array(l.strictObject({id:hc,transform:vc,title:l.string().optional().describe("Only a title the user named for this file."),fields:l.record(l.string(),l.unknown()).optional().describe("Frontmatter the user stated for this file alone, such as the date and address it was first published at: { publishedAt, canonicalUrl }; facts shared by every file go in the top-level fields.")},{error:(e)=>e.code==="unrecognized_keys"&&e.keys.includes("upload")?"Each file is `{ id, transform }`; its `upload` object was removed.":void 0})).min(2).max(20)}).strict(),Mi=l.discriminatedUnion("kind",[l.object({kind:l.literal("text").describe("Store exact/direct user-provided content without generation"),content:l.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(),yc,l.object({kind:l.literal("url").describe("Create URL/domain-backed entities such as links"),url:l.string().min(1).describe("URL or domain to create from; preserve a bare domain as provided instead of adding a scheme.")}).strict(),l.strictObject({kind:l.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."),id:hc,transform:vc},{error:(e)=>e.code==="unrecognized_keys"&&e.keys.includes("upload")?'The upload id goes in `source.id`: `{ kind: "upload", id, transform }`; `source.upload` was removed.':void 0}),it,l.object({kind:l.literal("prior-response").describe("Save a previous assistant response as durable content, especially an assistant summary or answer about an upload."),messageId:l.string().min(1).optional().describe("Stored assistant message ID; omit for latest savable")}).strict(),l.object({kind:l.literal("entity").describe("Reuse an existing entity's text verbatim, without its frontmatter, as a new entity of another type ('turn my note X into a post'). For new text written from a source, use system_generate prompt-from-source."),entityType:l.string().min(1).describe("Source entity type, such as note"),entityId:l.string().min(1).describe("Source entity ID, slug, or exact title copied from the user's request or a prior tool result")}).strict()]),Vm=l.discriminatedUnion("kind",[l.object({kind:l.literal("prompt").describe("A new non-image entity from a broad prompt; this branch has no source field."),entityType:l.string().min(1).describe("Entity type to generate from the prompt. Do not use image here; use standalone-image or cover-image."),title:l.string().optional().describe("Title for the generated entity"),prompt:l.string().min(1).describe("Prompt for creating new generated content, written from the user's request without added voice, tone or engagement directions; the style guide supplies the voice.")}).strict(),l.object({kind:l.literal("prompt-from-source").describe("A new non-image entity grounded in a resolved existing entity, such as a newsletter from a blog post."),entityType:l.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:l.string().optional().describe("Title for the generated entity"),source:l.object({entityType:l.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:l.string().min(1).describe("Resolved source entity ID from a prior tool result or typed entity ref.")}).strict().describe("The resolved existing entity that grounds this generation."),prompt:l.string().min(1).describe("Prompt for creating new generated content from the resolved source, written from the user's request without added voice, tone or engagement directions; the style guide supplies the voice.")}).strict(),l.object({kind:l.literal("standalone-image").describe("An unattached image; never a substitute for a requested cover."),title:l.string().optional().describe("Title for the generated image"),prompt:l.string().min(1).describe("Prompt for creating an unattached image. Not for cover images requested for a generated post/entity.")}).strict(),l.object({kind:l.literal("cover-image").describe("An image attached as coverImageId to an existing entity whose real id is known."),target:l.object({entityType:l.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:l.string().min(1).describe("Existing target entity ID from a prior tool result or typed entity ref")}).strict().describe("Existing entity that should receive the generated coverImageId"),title:l.string().optional().describe("Title for the generated image"),prompt:l.string().min(1).describe("Prompt for creating the cover image")}).strict(),l.object({kind:l.literal("attachment").describe("Generate a deterministic durable artifact from an existing entity attachment provider"),source:l.object({entityType:l.string().min(1).describe("Source entity type"),entityId:l.string().min(1).describe("Canonical source entity ID from a prior tool result or typed entity ref")}).strict().describe("The resolved existing entity whose attachment provider renders the artifact."),attachmentType:l.string().min(1).describe('Source artifact type such as "carousel", "printable", or "og-image"'),title:l.string().optional().describe("Title for the generated artifact"),replace:l.boolean().optional().describe("Set true for regenerate, replace, refresh, or update requests so a deterministic artifact is regenerated instead of reused")}).strict()]),ir=l.object({entityType:l.string().describe("Entity type to create. Use wish for explicitly saved or tracked unmet requested capabilities or outcomes."),title:l.string().optional().describe("Title for a new entity. Leave it out when saving several uploads: each item in source.items takes its own title."),visibility:pc.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:Mi.describe("Concrete source selector. Use exactly one source branch. For AI generation or source-derived artifacts, use system_generate instead."),fields:l.record(l.string(),l.unknown()).optional().describe("Frontmatter for facts the user states outside the source text, e.g. a post first published elsewhere: { status: 'published', publishedAt: '2025-03-12', canonicalUrl }; the section a doc goes in, named exactly as the user names it: { section }; the year a project began: { year }. Never copy values from the text or its frontmatter; omit when nothing extra is stated."),replace:l.boolean().optional().describe("Create a new copy intentionally"),confirmed:l.literal(!0).optional().describe("Confirm the creation"),confirmationToken:l.string().optional().describe("Internal confirmation token returned by the confirmation flow")}).strict(),bc=l.object({operation:Vm.describe("Exactly one generation operation."),confirmed:l.literal(!0).optional().describe("Confirm generation"),confirmationToken:l.string().optional().describe("Internal confirmation token returned by the confirmation flow")}).strict(),Ym=l.object({oldText:l.string().min(1).describe("Exact text occurring once in the original stored Markdown. Include enough context to be unique."),newText:l.string().describe("Literal replacement text; empty string deletes oldText.")}).strict(),rt="An update operation is exactly one of `fields`, `content`, `edits` or `source`.",Li=l.strictObject({fields:l.record(l.string(),l.unknown()).optional().describe("Update partial frontmatter or metadata fields. 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."),content:l.string().optional().describe("Replace the stored Markdown. 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."),edits:l.array(Ym).min(1).max(50).optional().describe("Apply exact text replacements to the stored Markdown. 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; an upload ref marked saved already holds its text, so edit that note without fetching it. Unchanged text is preserved without regeneration."),source:yc.optional().describe("Replace the stored Markdown with user-supplied text. 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.")},{error:(e)=>{if(e.code!=="unrecognized_keys")return;if(e.keys.includes("kind"))return ae(e.input)&&e.input.kind==="user-message"?'A user-message source is the source operation: put it under `source`, as in `{ source: { kind: "user-message", ... } }`.':"An update operation has no `kind`: name it by its field, as in `{ edits: [...] }`.";return`Unrecognized key ${e.keys.map((t)=>`"${t}"`).join(", ")}: ${rt}`}}).refine((e)=>[e.fields,e.content,e.edits,e.source].filter((t)=>t!==void 0).length===1,{message:rt}).describe(rt),nr=l.object({entityType:l.string().describe("Entity type"),id:l.string().describe("Entity ID, slug, or title"),operation:Li.describe("Exactly one update operation"),confirmed:l.literal(!0).optional().describe("Confirm the update"),confirmationToken:l.string().optional().describe("Internal confirmation token returned by the confirmation flow"),contentHash:l.string().optional().describe("Content hash for optimistic concurrency")}).strict(),Sc=l.object({entityType:l.string().describe("Entity type"),id:l.string().describe("Entity ID"),confirmed:l.literal(!0).optional().describe("Confirm the deletion"),confirmationToken:l.string().optional().describe("Internal confirmation token returned by the confirmation flow")}),IC=l.object({entityType:l.string().describe("Entity type to extract"),source:l.string().optional().describe("Source entity ID \u2014 omit for batch"),mode:l.enum(["derive","rebuild"]).optional().describe("Batch mode: project incrementally or rebuild from scratch"),confirmed:l.literal(!0).optional().describe("Confirm destructive rebuild"),confirmationToken:l.string().optional().describe("Internal confirmation token returned by the confirmation flow")}),Rc=l.object({batchId:l.string().optional().describe("Specific batch ID to check"),jobTypes:l.array(l.string()).optional().describe("Filter by job types")}),Xm=l.object({entityType:l.string().optional(),entityId:l.string().optional(),attachmentType:l.string().optional()}),eg=l.object({mediaType:l.string(),url:l.string(),downloadUrl:l.string().optional(),previewUrl:l.string().optional(),filename:l.string().optional(),sizeBytes:l.number().optional(),source:Xm.optional()}),TC=l.object({entityId:l.string().optional(),status:l.enum(["created","generating"]),jobId:l.string().optional(),attachment:eg.optional()}),EC=l.object({status:l.literal("extracting"),jobId:l.string(),entityType:l.string(),source:l.string().optional(),mode:l.enum(["derive","rebuild"]).optional()});function Cc(e,t,r){return r==="create"?e.getCreateFieldsSchema(t):e.getEditableFieldsSchema(t)}function xc(e){if(e instanceof l.ZodOptional||e instanceof l.ZodNullable||e instanceof l.ZodDefault)return xc(e.unwrap());return e instanceof l.ZodType?e:void 0}function wc(e){try{let{$schema:t,...r}=l.toJSONSchema(e,{target:"draft-7",io:"input"});return r}catch{return}}function tg(e){return Pc({type:"object",properties:{value:e},required:["value"]})!==void 0}function Ic(e,t){let r=new Map,i=new Map,n=e.getAllEntityTypes();for(let d of n){let u=Cc(e,d,t.on);for(let[p,m]of Object.entries(u?.shape??{})){if(t.omit?.includes(p))continue;let g=xc(m),f=g&&wc(g);if(!g||!f||!tg(f))continue;let h=r.get(p)??new Map;h.set(JSON.stringify(f),g),r.set(p,h),i.set(p,[...i.get(p)??[],d])}}let o=new Map;for(let[d,u]of r){let[p,...m]=[...u.values()];if(!p)continue;let g=m.length>0?l.union([p,...m]):p,f=JSON.stringify(wc(g)),h=o.get(f)??{value:g,names:[]};h.names.push(d),o.set(f,h)}let s=[...o.values()].map(({value:d,names:u})=>{let[p,...m]=u,g=u.map((f)=>{let h=i.get(f)??[];return`${f} (${h.length===n.length?"every type":h.join(", ")})`}).join("; ");return l.strictObject({name:(m.length>0&&p!==void 0?l.enum([p,...m]):l.literal(p??"")).describe(`The field, set only on the entity types named: ${g}.`),value:t.on==="update"?d.nullable():d})}),[a,...c]=s;return l.array(a?c.length>0?l.union([a,...c]):a:l.never())}function rg(e){return Object.fromEntries((Array.isArray(e)?e:[]).flatMap((t)=>X(t)&&typeof t.name==="string"?[[t.name,t.value]]:[]))}function or(e,t,r,i){if(!r)return;let{allow:n}=i,o=new Set(Object.keys(Cc(e,t,i.on)?.shape??{})),s=Object.keys(r).filter((d)=>!o.has(d)&&!n.includes(d));if(s.length===0)return;let a=s.map((d)=>`"${d}"`).join(", "),c=[...o].join(", ")||"none";return`A ${t} has no ${s.length>1?"fields":"field"} ${a} a caller can set; its fields are ${c}.`}function $i(e){return"fields"in e&&e.fields!==void 0?{...e,fields:rg(e.fields)}:e}function Tc(e){return{prepare:()=>e.ensureGroupingsCurrent(),inputSchema:()=>{let t=Ic(e,{on:"create",omit:["visibility"]}),r=it.shape.items.element,i=it.extend({items:l.array(r.extend({fields:t.optional().describe("Field changes the user stated for this file alone, one { name, value } per field, such as the date and address it was first published at: [{ name: 'publishedAt', value }, { name: 'canonicalUrl', value }]; facts shared by every file go in the top-level fields.")})).min(2).max(20)}),[n,...o]=Mi.options.map((s)=>s===it?i:s);if(!n)throw Error("system_create has no source branches");return{...ir.shape,source:l.discriminatedUnion("kind",[n,...o]).describe("Concrete source selector. Use exactly one source branch. For AI generation or source-derived artifacts, use system_generate instead."),fields:t.optional().describe("Field changes for facts the user states outside the source text, one { name, value } per field, e.g. a post first published elsewhere: [{ name: 'status', value: 'published' }, { name: 'publishedAt', value: '2025-03-12' }, { name: 'canonicalUrl', value }]; the section a doc goes in, named exactly as the user names it: [{ name: 'section', value }]; the year a project began: [{ name: 'year', value }]. Never copy values from the text or its frontmatter; omit when nothing extra is stated.")}},toToolInput:(t)=>{let r=t.source;return $i({...t,...X(r)&&Array.isArray(r.items)&&{source:{...r,items:r.items.map((i)=>X(i)?$i(i):i)}}})}}}function Ui(e){let t=e.unwrap();return e.description?t.describe(e.description):t}function Ec(e){let{content:t,edits:r,source:i}=Li.shape;return{prepare:()=>e.ensureGroupingsCurrent(),inputSchema:()=>({...nr.shape,operation:l.union([l.strictObject({fields:Ic(e,{on:"update"}).describe("Change frontmatter or metadata fields, one { name, value } per field changed. Use this for status, title, coverImageId, ogImageId, and metadata changes such as approving an agent. To set an existing image as an entity cover, change coverImageId to that image id. To remove a field, such as a cover image, give it the value null, not an empty string. Do not use fields for anchor-profile; anchor-profile updates require the content operation.")}),l.strictObject({content:Ui(t)}),l.strictObject({edits:Ui(r)}),l.strictObject({source:Ui(i)})]).describe("Exactly one update operation")}),toToolInput:(n)=>{let o=n.operation;return X(o)?{...n,operation:$i(o)}:n}}}function F(e,t,r,i){try{e.permissionService.assertEntityActionAllowed(t,r,i.userPermissionLevel);return}catch(n){if(n instanceof kc||n instanceof Error)return{success:!1,error:n.message};throw n}}async function ar(e,t,r,{confirmed:i}){let n=r.conversationId??r.channelId;if(!n)return{success:!1,error:"Conversation message is not accessible in this conversation or does not exist."};let o=await e.conversationService.getMessages(n,{limit:100}),s=t.kind==="user-message",a=s?o.filter((y)=>{if(y.role!=="user")return!1;let S=r.userPermissionLevel??"public";if(S==="admin")return!0;let R=sr(y.metadata)?.userPermissionLevel;return(R==="public"||R==="trusted"||R==="admin")&&e.permissionService.hasPermission(S,R)}):o.filter(Ac),c=t.messageId?a.find((y)=>y.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(!s)return{success:!0,messageId:c.id,content:c.content};let d=sg(og(t,c.content),c.content),u=(y,S,R,w)=>{if(!S)return{offset:R};let x=`${y} ${JSON.stringify(S)}`;if(d.boundaryMode==="lines"&&/[\r\n]/.test(S))return{problem:`${x} contains a newline; in lines mode give the marker line's text only`};let I=ig(c.content,S,d.boundaryMode==="lines"?"lines":"literal",w),[M]=I;if(I.length===1&&M!==void 0)return{offset:M};return{problem:I.length===0?`${x} does not occur in the message`:`${x} occurs ${I.length} times in the message`}},p=u("startAfter",d.startAfter,0,!0),m=d.boundaryMode==="frontmatter"&&"offset"in p?cg(c.content,p.offset):p,g=u("endBefore",d.endBefore,c.content.length,!1),f=[m,g].flatMap((y)=>("problem"in y)?[y.problem]:[]);if(f.length===0&&"offset"in m&&"offset"in g&&m.offset>=g.offset)f.push("startAfter must come before endBefore with content between them");if(!("offset"in m)||!("offset"in g)||f.length>0)return{success:!1,error:`User-message boundary ${f.join("; ")}; each boundary must occur exactly once. ${ag(c.content)}`};let h=c.content.slice(m.offset,g.offset).replace(/^(?:[ \t]*\r?\n)+(?=---\r?\n)/,""),v=i?t.contentHash:void 0;if(v&&v!==le(h))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:h,source:d}}function cr(e,t){let{startAfter:r,endBefore:i,...n}=t.source??e;return{...n,...r?{startAfter:r}:{},...i?{endBefore:i}:{},messageId:t.messageId,contentHash:le(t.content)}}function ig(e,t,r,i){if(r==="lines"){let o=Bi(e,t,i);return o.length>0||!t.trim()?o:Bi(e,t,i,ng)}let n=jc(e,t,i);return n.length>0?n:lg(e,t,i)}function ng(e){return e.trim().replace(/\s+/g," ")}function og(e,t){let r=(a)=>a?.trim()==="---";if(!r(e.startAfter)&&!r(e.endBefore))return e;if((t.match(/^---\r?$/gm)?.length??0)!==2||_i(t,0).length!==1)return e;let{startAfter:n,endBefore:o,...s}=e;return{...s,boundaryMode:"frontmatter",...r(n)?{}:{startAfter:n},...r(o)?{}:{endBefore:o}}}function sg(e,t){let{startAfter:r,endBefore:i}=e;if(e.boundaryMode!==void 0||!r||!i)return e;let n=(o)=>!/[\r\n]/.test(o)&&Bi(t,o,!0).length===1;return n(r)&&n(i)?{...e,boundaryMode:"lines"}:e}function ag(e){return _i(e,0).length===1?'--- fences frontmatter, which is part of the content: retry with boundaryMode "frontmatter" and no startAfter or endBefore.':"To select everything after an instruction, use boundaryMode literal with startAfter set to the instruction's exact text and omit endBefore."}function cg(e,t){let r=_i(e,t),[i]=r;if(r.length===1&&i!==void 0)return{offset:i};return{problem:r.length===0?"boundaryMode frontmatter finds no --- frontmatter block":`boundaryMode frontmatter finds ${r.length} --- frontmatter blocks`}}function _i(e,t){return Array.from(e.slice(t).matchAll(/^---\r?\n["']?[A-Za-z_][\w-]*["']?[ \t]*:.*\r?\n(?:.*\r?\n)*?---\r?$/gm),(r)=>t+r.index)}function Bi(e,t,r,i=(n)=>n){let n=i(t);return e.split(/(?<=\n)/).reduce((o,s)=>({offset:o.offset+s.length,matches:i(s.replace(/\r?\n$/,""))===n?[...o.matches,o.offset+(r?s.length:0)]:o.matches}),{offset:0,matches:[]}).matches}function lg(e,t,r){let i=t.trim().split(/\s+/);if(i.join("")===""||!/\s/.test(t))return[];let n=(s)=>s?"\\s*":"",o=new RegExp(n(/^\s/.test(t))+i.map(dg).join("\\s+")+n(/\s$/.test(t)),"g");return Array.from(e.matchAll(o),(s)=>s.index+(r?s[0].length:0))}function dg(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function jc(e,t,r,i=0){let n=e.indexOf(t,i);if(n<0)return[];return[n+(r?t.length:0),...jc(e,t,r,n+1)]}var ug=/^[ \t]*---[ \t]*$/gm;function Dc(e){return e.replace(/\s+/g," ").trim()}function pg(e){return e.kind==="user-message"?e.messageId:void 0}class Zi{pins=new Map;now;constructor(e=Date.now){this.now=e}pin(e,t){this.pins.set(e,{...t,expiresAt:this.now()+1800000})}clear(e){this.pins.delete(e)}live(e){let t=this.pins.get(e);if(t&&t.expiresAt<this.now()){this.pins.delete(e);return}return t}resolveUnresolvable(e,t){let r=this.live(e);if(!r||t.kind!=="user-message"||t.messageId)return;return{kind:"pinned",source:r.source,content:r.content}}resolve(e,t){let r=this.live(e);if(!r)return{kind:"as-given"};let i=pg(r.source),n={kind:"pinned",source:r.source,content:r.content};if(t.source.kind==="user-message"&&t.source.messageId){if(t.source.messageId!==i)this.pins.delete(e);return{kind:"as-given"}}if(t.content===void 0)return{kind:"as-given"};if(r.question==="slide-breaks"&&t.content!==r.content&&Dc(t.content.replace(ug,""))===Dc(r.content))return{kind:"as-given"};if(t.source.kind==="text")return n;if(t.source.kind==="user-message"&&t.resolvedMessageId!==i){if(t.content.length*2<r.content.length)return n;this.pins.delete(e)}return{kind:"as-given"}}}function Fi(e,t){return e?`${e}\x00${t}`:void 0}function zc(e){if(e.kind!=="user-message")return e;let{contentHash:t,...r}=e;return r}var mg="system";function q(e,t,r,i,n={}){let{visibility:o="admin",sideEffects:s}=n;return{name:`${mg}_${e}`,description:t,inputSchema:r.shape,handler:async(a,c)=>{let d=r.safeParse(a);if(!d.success)return{success:!1,error:`Invalid input: ${d.error.issues.map((u)=>`${u.path.join(".")}: ${u.message}`).join(", ")}`};try{return await i(d.data,c)}catch(u){return{success:!1,error:C(u)}}},visibility:o,...s?{sideEffects:s}:{}}}function lr(e){return{interfaceType:e.interfaceType,actor:e.actor,userPermissionLevel:e.userPermissionLevel??"public",...e.channelId&&{channelId:e.channelId},...e.channelName&&{channelName:e.channelName}}}async function dr(e,t,r,i){let n=await t(r,lr(i));if(n.kind==="handled")return{kind:"handled",result:n.result};let o=n.input;if(o.visibility!==r.visibility)return{kind:"error",result:{success:!1,error:"Create interceptor changed or dropped the requested entity visibility."}};let s=F(e,o.entityType,"create",i);if(s)return{kind:"error",result:s};return{kind:"continue",createInput:o}}function we(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 Me(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 Ni(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 Pe(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var gg={base:"note"};function Oc(e){return gg[e]??e.replaceAll("-"," ")}function ur(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 Mc(e){return!!e&&Object.keys(e.shape).length>0}async function Lc(e,t,r){if(!r)return!1;let i=await e.conversationService.getMessages(r,{limit:100});for(let n of i){let s=sr(n.metadata)?.attachments;if(!Array.isArray(s))continue;for(let a of s){if(!ae(a))continue;let c=a.source;if(!ae(c))continue;if(c.kind===t.kind&&c.id===t.id)return!0}}return!1}async function pr(e,t,r){if(t.replace||!t.candidateId)return{kind:"ok",value:void 0};let i=await e.entityService.getEntity({entityType:t.entityType,id:t.candidateId,visibilityScope:A(r.userPermissionLevel)});if(!i)return{kind:"ok",value:void 0};if(i.metadata.status==="failed"&&r.userPermissionLevel==="admin"&&!F(e,t.entityType,"delete",r))return{kind:"ok",value:{entityType:i.entityType,id:i.id}};return{kind:"error",result:{success:!1,error:`A ${t.entityType} already exists for "${t.candidateId}". To change it, use system_update on that ${t.entityType} in this turn, without asking first; pass replace:true to ${t.copyHint}.`}}}function mr(e){return`Replaces: failed ${e.entityType} "${e.id}"`}async function gr(e,t){if(!t)return;try{await e.entityService.deleteEntity(t);return}catch(r){return{success:!1,error:C(r,"Failed to replace the failed entity")}}}function Hi(e){return`${e.entityType} "${e.title}"`}function fg(e){return Object.entries(e).map(([t,r])=>`${t}: ${typeof r==="string"?r:JSON.stringify(r)}`).join(", ")}function Uc(e){return"error"in e?e.error:"the save was not completed"}function hg(e){let t=new Map;for(let r of e){let i=`${r.entityType}:${te(r.title)}`,n=t.get(i);if(n)return`${n.filename} and ${r.filename} would both be saved as ${Hi(r)}. Give them different titles in source.items.`;t.set(i,r)}return}function yg(e,t){return{summary:`Save ${e.length} uploaded files?`,completionSummary:`Saved ${e.length} uploaded files: ${e.map(Hi).join(", ")}.`,preview:[...e.map((r,i)=>[`${i+1}. ${r.filename} \u2192 ${Hi(r)}`,...r.fields?[` ${fg(r.fields)}`]:[],...r.replacesFailed?[` Replaces failed ${r.replacesFailed}`]:[]].join(`
77
+ </html>`;var _a=l.strictObject({productionOutputDir:l.string().min(1),previewOutputDir:l.string().min(1),sharedImagesDir:l.string().min(1)});var W="webserver",Y=`${W}:${W}`,Im="./dist/site-production",Tm="./dist/site-preview",Em="./dist/images";function km(e){return[...e].flatMap((t)=>{let r=t.getStaticSiteOutput?.();return r?[{..._a.parse(r),ownerPluginId:t.id}]:[]})}function Am(e,t){let[r,i]=t;if(r&&i)throw Error(`Two plugins write the site the HTTP host serves: "${r.ownerPluginId}" and "${i.ownerPluginId}"`);let n=(o,s,a,c)=>{let d=e[o];if(r&&s!==void 0&&d!==void 0&&Za(d)!==Za(s))throw Error(`http.${o} "${d}" is not where "${r.ownerPluginId}" writes the ${a} ("${s}"); remove it or set it to the same directory`);return s??d??c};return{productionDistDir:n("productionDistDir",r?.productionOutputDir,"production site",Im),previewDistDir:n("previewDistDir",r?.previewOutputDir,"preview site",Tm),sharedImagesDir:n("sharedImagesDir",r?.sharedImagesDir,"shared images",Em)}}async function jm(e,t,r){let i=[e.productionDistDir,...t?[e.previewDistDir]:[]];for(let n of i){if(wm(n))continue;await Pm(n,{recursive:!0}),await Cm(xm(n,"index.html"),ki),r.debug(`Created site directory at ${n}`)}}function Na(e){return e?{siteUrl:`https://${e}`,previewUrl:`https://${Fa(e)}`}:{siteUrl:void 0,previewUrl:void 0}}function Ha(e){let{config:t,logger:r}=e,{siteUrl:i,previewUrl:n}=Na(e.domain),o;return{start:async()=>{let s=Am(t,km(e.getPlugins()));await jm(s,t.preview,r),o??=new Yt({logger:r,productionDistDir:s.productionDistDir,sharedImagesDir:s.sharedImagesDir,productionPort:t.port,...t.hostname?{hostname:t.hostname}:{},...t.preview&&{previewDistDir:s.previewDistDir},getOperationalInfo:e.getOperationalInfo,getReadinessData:e.getReadinessData,getRoutes:e.getRoutes,executeTool:Ei(e.messageBus,W)}),await o.start()},stop:async()=>{await o?.stop()},healthCheck:async()=>{let s=o?.getStatus(),a=s?.running??!1,c=i??s?.productionUrl??`http://localhost:${t.port}`,d=n??s?.previewUrl??`http://localhost:${t.port}`,u=[];if(a){if(u.push(`Production: ${c}`),s?.previewUrl)u.push(`Preview: ${d}`)}return{status:a?"healthy":"error",message:a?u.join(", "):"Webserver not running",lastCheck:new Date,details:{preview:!!s?.previewUrl,production:a,previewUrl:s?.previewUrl?d:void 0,productionUrl:a?c:void 0}}}}}function Wa(e,t){let{siteUrl:r,previewUrl:i}=Na(t);if(!r)return{endpoints:[],interactions:[]};let n=e.preview&&i?i:void 0;return{endpoints:[{pluginId:W,label:"Site",url:r,priority:10},...n?[{pluginId:W,label:"Preview",url:n,priority:20,visibility:"admin"}]:[]],interactions:[{pluginId:W,id:"site",label:"Public site",description:"Visit the published public site for this brain.",href:r,kind:"human",priority:10},...n?[{pluginId:W,id:"preview",label:"Preview site",description:"Open the private preview build.",href:n,kind:"admin",priority:20,visibility:"admin"}]:[]]}}var Dm=250,zm=l.object({projectionBatch:l.object({operationId:l.string().min(1),childKey:l.string().min(1)})});class Ai{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=ke(n),this.hooks=o}async boot(e){this.services.logger.debug("Starting Shell boot");let t=this.initializer;await er([()=>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 Gs({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)=>{let s=await Ge(this.services.messageBus,qa,o,"shell");if(s.status==="unavailable")return;if(s.failures.length>0||s.answers.length===0)throw Error(`Projection wave ${o.waveId} completion was not acknowledged`)},logger:this.services.logger,createWaveId:Ja,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,s)=>(await this.services.jobQueueService.getJobsByRootJobId(o)).flatMap((c)=>{let d=zm.safeParse(JSON.parse(c.data));if(!d.success||d.data.projectionBatch.operationId!==s)return[];return[{jobId:c.id,childKey:d.data.projectionBatch.childKey,status:c.status,terminalAt:c.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.startHttpHost(),await this.services.entityService.reprojectRegisteredGroupings();let n=await this.services.entityService.rewriteRetiredFields();if(n.rewritten>0)this.services.logger.info("Rewrote entities carrying retired fields",{rewritten:n.rewritten});let o=await this.services.entityService.reconcileDeclaredMetadata();if(o.reconciled>0)this.services.logger.info("Re-derived declared entity metadata",{reconciled:o.reconciled});let s=Ya();if(this.services.disposables.push(this.services.messageBus.subscribe(Qe.initialSyncCompleted,async(c)=>(s.resolve(Ka.safeParse(c.payload).data?.success===!0),{success:!0}))),await this.emitPluginsRegistered())i=s.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 startHttpHost(){if(!this.services.daemonRegistry.has(Y))return;await this.services.daemonRegistry.start(Y),this.services.logger.debug("Started the HTTP host before initial sync")}async emitPluginsRegistered(){let e=await this.services.messageBus.collect({type:Qe.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)&&Qa.safeParse(t.data).data?.initialSyncPending===!0)}async settleStartupContent(){await this.prepareReadyState(),await je(this.services.messageBus,Va,{timestamp:new Date().toISOString()},"shell"),this.services.logger.debug("Emitted startup content settled event")}async loadIdentityServices(){await er([()=>this.services.identityService.refreshCache(),()=>this.services.profileService.refreshCache(),()=>this.services.canonicalIdentityService.refreshCache()]),this.services.logger.debug("Identity services loaded")}async initializeIdentityServices(){await er([()=>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 Ga(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.retitled.length>0)e.info("Corrected generated prompt titles",{targets:t.retitled});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});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 b.tryPromise({try:()=>e.backfillMissingEmbeddings(),catch:(i)=>i}).pipe(b.tap((i)=>b.sync(()=>{t.debug("Queued missing embedding backfill jobs",i)})),b.catch((i)=>b.sync(()=>{t.warn("Embedding backfill failed",i)}))).pipe(b.andThen(b.tryPromise({try:(i)=>e.awaitIndexReady({intervalMs:Dm,signal:i}),catch:(i)=>i}).pipe(b.tap((i)=>b.sync(()=>{if(i.degraded)t.warn("Semantic index ready with degraded embeddings",i);else t.debug("Semantic index ready",i)})),b.catch((i)=>b.sync(()=>{t.warn("Semantic index readiness monitor stopped",i)})))))}}var Om=l.object({}),Xa=l.string().regex(/^\d{4}-(0[1-9]|1[0-2])$/,"Expected YYYY-MM"),tc=l.array(l.string().min(1)).min(1).optional().describe("Only these entity types"),Mm=l.object({entityTypes:tc,from:Xa.optional().describe("First month, YYYY-MM"),to:Xa.optional().describe("Last month, YYYY-MM")}),Lm=l.object({staleDays:l.number().int().min(1).max(3650).default(90).describe("Days without an update before content counts as stale"),entityTypes:tc});function rc(e){let t=new ec;return t.register(tr({type:"overview",description:"Entity counts by type, recent activity, and draft and published totals.",params:Om,handler:async(r,{entityService:i,visibilityScope:n})=>Um(i,n)})),t.register(tr({type:"publishing-cadence",description:"Pieces per month, by type: counted in the month they were published, or created when never published.",params:Mm,handler:async(r,{entityService:i,visibilityScope:n})=>Bm(i,n,r)})),t.register(tr({type:"content-health",description:"Drafts and content not updated for a long time.",params:Lm,handler:async(r,{entityService:i,visibilityScope:n})=>_m(i,n,e,r)})),t}async function Um(e,t){let r=await e.getEntityCounts(t),i={},n=0;for(let{entityType:g,count:f}of r)i[g]=f,n+=f;let o=await ji(e,t),s=Date.now(),a=s-604800000,c=s-2592000000,d=0,u=0;for(let g of o){let f=new Date(g.created).getTime();if(f>=a)d++;if(f>=c)u++}let p=nc(o),m=o.filter((g)=>g.metadata.status==="published");return{entityCounts:i,totalEntities:n,recentActivity:{last7days:d,last30days:u},contentHealth:{drafts:p.length,published:m.length}}}function $m(e){let t=e.metadata.publishedAt;return new Date(typeof t==="string"&&t?t:e.created)}function ic(e,t){return t?e.filter((r)=>t.includes(r.entityType)):e}async function Bm(e,t,r){let i=ic(await ji(e,t),r.entityTypes),n=new Map;for(let s of i){let a=$m(s);if(isNaN(a.getTime()))continue;let c=`${a.getUTCFullYear()}-${String(a.getUTCMonth()+1).padStart(2,"0")}`;if(r.from&&c<r.from||r.to&&c>r.to)continue;let d=n.get(c);if(!d)d={},n.set(c,d);d[s.entityType]=(d[s.entityType]??0)+1}return{months:Array.from(n.entries()).sort((s,a)=>a[0].localeCompare(s[0])).map(([s,a])=>{let c=0;for(let d of Object.values(a))c+=d;return{month:s,counts:a,total:c}})}}async function _m(e,t,r,i){let n=ic(await ji(e,t),i.entityTypes),o=nc(n).map((d)=>({id:d.id,entityType:d.entityType,title:typeof d.metadata.title==="string"?d.metadata.title:d.id,created:d.created})),s=Date.now(),a=s-i.staleDays*24*60*60*1000,c=n.filter((d)=>{if(r.getEntityTypeConfig(d.entityType).binaryStorage)return!1;let u=new Date(d.updated).getTime();return!isNaN(u)&&u<a}).map((d)=>({id:d.id,entityType:d.entityType,title:typeof d.metadata.title==="string"?d.metadata.title:d.id,updated:d.updated,daysSinceUpdate:Math.floor((s-new Date(d.updated).getTime())/86400000)}));return{drafts:o,stale:c}}function nc(e){return e.filter((t)=>t.metadata.status==="draft")}async function ji(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 tt{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 Di extends tt{constructor(){super((e)=>oc.parse(e),(e)=>e.url)}}class zi extends tt{constructor(){super((e)=>sc.parse(e),(e)=>e.id)}}function ac(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 Zm=["/health","/images"],Fm=new Set([Vt]),Nm=new Set(cc),Hm=new Set(["GET","POST","PUT","DELETE"]);function lc(e){let t=[];for(let[r,{plugin:i}]of e.getAllPlugins()){let n,o;try{n=i.getWebRoutes?.()??[],o=i.getApiRoutes?.()??[]}catch(s){throw Error(`Failed to collect HTTP route declarations from plugin "${r}"`,{cause:s})}t.push({pluginId:r,webRoutes:n,apiRoutes:o})}return t}function dc(e){return Fm.has(e)||Zm.some((t)=>e===t||e.startsWith(`${t}/`))}function Oi(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&&dc(e))throw Error(`Invalid HTTP route path "${e}" declared by plugin "${t}"`)}function uc(e,t,r){if(!e.has(t))throw Error(`Invalid HTTP route method "${t}" declared by plugin "${r}"`)}function Wm(e,t,r){let i=e==="claim";if(!["exact","prefix","claim"].includes(e)||i!==(typeof t==="function")||!i&&t!==void 0)throw Error(`Invalid HTTP route match "${e}" declared by plugin "${r}"`)}function qm(e,t){Oi(t.path,e.pluginId);let r=t.method??"GET";uc(Nm,r,e.pluginId);let i=t.match??"exact";Wm(i,t.claims,e.pluginId);let n=t.claims;if(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}:{},...n?{claims:(o)=>!dc(o)&&n(o)}:{},handler:t.handler})}function Jm(e,t){Oi(t.path,e.pluginId,!1);let r=`/api/${e.pluginId}${t.path}`;if(Oi(r,e.pluginId),uc(Hm,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 Gm(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 Qm(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 rr{routes;manifest;apiRoutes;webRoutes;static createFresh(){return new rr}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(qm(n,o)),r.push(Object.freeze({pluginId:n.pluginId,fullPath:o.path,definition:Object.freeze({...o})}));for(let o of n.apiRoutes){let s=Jm(n,o);t.push(s),i.push(Object.freeze({pluginId:n.pluginId,fullPath:s.fullPath,definition:s.definition}))}}return Gm(t),this.routes=Object.freeze(t),this.manifest=Qm(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 pc(e,t){e.addFinalizer(()=>t.pluginManager.shutdownPlugins()),e.addFinalizer(async()=>{if(t.daemonRegistry.has(Y))await t.daemonRegistry.unregister(Y)}),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 Km=l.discriminatedUnion("kind",[l.object({kind:l.literal("all")}).strict().describe("Search across all entity types"),l.object({kind:l.literal("type"),entityType:l.string().min(1).describe("Entity type to search")}).strict().describe("Search within one entity type")]),gc=l.object({query:l.string().describe("Search term"),scope:Km.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:l.number().optional().describe("Maximum number of results"),minScore:l.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:l.boolean().optional().describe("Include queued/failed generation stubs in results")}),fc=l.object({entityType:l.string().describe("Entity type"),id:l.string().describe("Entity ID, slug, or title"),part:l.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.")}),hc=l.object({entityType:l.string().describe("Entity type to list"),status:l.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:l.number().optional().describe("Maximum number of results (default: 20)")}),yc=l.string().min(1).describe("Upload id from the conversation's upload refs"),vc=l.object({kind:l.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:l.string().optional().describe("Stored user message ID in this conversation; omit for the latest user message."),boundaryMode:l.enum(["literal","lines","frontmatter"]).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. Use frontmatter when the pasted text opens with a --- frontmatter block: the saved text starts at its opening fence, so no startAfter is needed."),startAfter:l.string().optional().describe("Exact unique opening boundary, excluded from saved text; never a --- fence (use boundaryMode frontmatter). 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:l.string().optional().describe("Omit when the content runs to the end of the message. Otherwise the exact unique closing boundary, excluded from saved text; never a --- fence (use boundaryMode frontmatter). 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."),contentHash:l.string().optional().describe("Internal source hash returned with the confirmation; omit on the initial request.")}).strict(),bc=l.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."),it=l.object({kind:l.literal("uploads").describe("Keep several uploaded files from one request: one call listing every attached file, never one call per file; entityType names the note type for extract-markdown files, or another type such as post."),items:l.array(l.strictObject({id:yc,transform:bc,title:l.string().optional().describe("Only a title the user named for this file."),fields:l.record(l.string(),l.unknown()).optional().describe("Frontmatter the user stated for this file alone, such as the date and address it was first published at: { publishedAt, canonicalUrl }; facts shared by every file go in the top-level fields.")},{error:(e)=>e.code==="unrecognized_keys"&&e.keys.includes("upload")?"Each file is `{ id, transform }`; its `upload` object was removed.":void 0})).min(2).max(20)}).strict(),Mi=l.discriminatedUnion("kind",[l.object({kind:l.literal("text").describe("Store exact/direct user-provided content without generation"),content:l.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(),vc,l.object({kind:l.literal("url").describe("Create URL/domain-backed entities such as links"),url:l.string().min(1).describe("URL or domain to create from; preserve a bare domain as provided instead of adding a scheme.")}).strict(),l.strictObject({kind:l.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."),id:yc,transform:bc},{error:(e)=>e.code==="unrecognized_keys"&&e.keys.includes("upload")?'The upload id goes in `source.id`: `{ kind: "upload", id, transform }`; `source.upload` was removed.':void 0}),it,l.object({kind:l.literal("prior-response").describe("Save a previous assistant response as durable content, especially an assistant summary or answer about an upload."),messageId:l.string().min(1).optional().describe("Stored assistant message ID; omit for latest savable")}).strict(),l.object({kind:l.literal("entity").describe("Reuse an existing entity's text verbatim, without its frontmatter, as a new entity of another type ('turn my note X into a post'). For new text written from a source, use system_generate prompt-from-source."),entityType:l.string().min(1).describe("Source entity type, such as note"),entityId:l.string().min(1).describe("Source entity ID, slug, or exact title copied from the user's request or a prior tool result")}).strict()]),Vm=l.discriminatedUnion("kind",[l.object({kind:l.literal("prompt").describe("A new non-image entity from a broad prompt; this branch has no source field."),entityType:l.string().min(1).describe("Entity type to generate from the prompt. Do not use image here; use standalone-image or cover-image."),title:l.string().optional().describe("Title for the generated entity"),prompt:l.string().min(1).describe("Prompt for creating new generated content, written from the user's request without added voice, tone or engagement directions; the style guide supplies the voice.")}).strict(),l.object({kind:l.literal("prompt-from-source").describe("A new non-image entity grounded in a resolved existing entity, such as a newsletter from a blog post."),entityType:l.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:l.string().optional().describe("Title for the generated entity"),source:l.object({entityType:l.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:l.string().min(1).describe("Resolved source entity ID from a prior tool result or typed entity ref.")}).strict().describe("The resolved existing entity that grounds this generation."),prompt:l.string().min(1).describe("Prompt for creating new generated content from the resolved source, written from the user's request without added voice, tone or engagement directions; the style guide supplies the voice.")}).strict(),l.object({kind:l.literal("standalone-image").describe("An unattached image; never a substitute for a requested cover."),title:l.string().optional().describe("Title for the generated image"),prompt:l.string().min(1).describe("Prompt for creating an unattached image. Not for cover images requested for a generated post/entity.")}).strict(),l.object({kind:l.literal("cover-image").describe("An image attached as coverImageId to an existing entity whose real id is known."),target:l.object({entityType:l.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:l.string().min(1).describe("Existing target entity ID from a prior tool result or typed entity ref")}).strict().describe("Existing entity that should receive the generated coverImageId"),title:l.string().optional().describe("Title for the generated image"),prompt:l.string().min(1).describe("Prompt for creating the cover image")}).strict(),l.object({kind:l.literal("attachment").describe("Generate a deterministic durable artifact from an existing entity attachment provider"),source:l.object({entityType:l.string().min(1).describe("Source entity type"),entityId:l.string().min(1).describe("Canonical source entity ID from a prior tool result or typed entity ref")}).strict().describe("The resolved existing entity whose attachment provider renders the artifact."),attachmentType:l.string().min(1).describe('Source artifact type such as "carousel", "printable", or "og-image"'),title:l.string().optional().describe("Title for the generated artifact"),replace:l.boolean().optional().describe("Set true for regenerate, replace, refresh, or update requests so a deterministic artifact is regenerated instead of reused")}).strict()]),ir=l.object({entityType:l.string().describe("Entity type to create. Use wish for explicitly saved or tracked unmet requested capabilities or outcomes."),title:l.string().optional().describe("Title for a new entity. Leave it out when saving several uploads: each item in source.items takes its own title."),visibility:mc.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:Mi.describe("Concrete source selector. Use exactly one source branch. For AI generation or source-derived artifacts, use system_generate instead."),fields:l.record(l.string(),l.unknown()).optional().describe("Frontmatter for facts the user states outside the source text, e.g. a post first published elsewhere: { status: 'published', publishedAt: '2025-03-12', canonicalUrl }; the section a doc goes in, named exactly as the user names it: { section }; the year a project began: { year }. Never copy values from the text or its frontmatter; omit when nothing extra is stated."),replace:l.boolean().optional().describe("Create a new copy intentionally"),confirmed:l.literal(!0).optional().describe("Confirm the creation"),confirmationToken:l.string().optional().describe("Internal confirmation token returned by the confirmation flow")}).strict(),Sc=l.object({operation:Vm.describe("Exactly one generation operation."),confirmed:l.literal(!0).optional().describe("Confirm generation"),confirmationToken:l.string().optional().describe("Internal confirmation token returned by the confirmation flow")}).strict(),Ym=l.object({oldText:l.string().min(1).describe("Exact text occurring once in the original stored Markdown. Include enough context to be unique."),newText:l.string().describe("Literal replacement text; empty string deletes oldText.")}).strict(),rt="An update operation is exactly one of `fields`, `content`, `edits` or `source`.",Li=l.strictObject({fields:l.record(l.string(),l.unknown()).optional().describe("Update partial frontmatter or metadata fields. 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."),content:l.string().optional().describe("Replace the stored Markdown. 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."),edits:l.array(Ym).min(1).max(50).optional().describe("Apply exact text replacements to the stored Markdown. 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; an upload ref marked saved already holds its text, so edit that note without fetching it. Unchanged text is preserved without regeneration."),source:vc.optional().describe("Replace the stored Markdown with user-supplied text. 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.")},{error:(e)=>{if(e.code!=="unrecognized_keys")return;if(e.keys.includes("kind"))return ae(e.input)&&e.input.kind==="user-message"?'A user-message source is the source operation: put it under `source`, as in `{ source: { kind: "user-message", ... } }`.':"An update operation has no `kind`: name it by its field, as in `{ edits: [...] }`.";return`Unrecognized key ${e.keys.map((t)=>`"${t}"`).join(", ")}: ${rt}`}}).refine((e)=>[e.fields,e.content,e.edits,e.source].filter((t)=>t!==void 0).length===1,{message:rt}).describe(rt),nr=l.object({entityType:l.string().describe("Entity type"),id:l.string().describe("Entity ID, slug, or title"),operation:Li.describe("Exactly one update operation"),confirmed:l.literal(!0).optional().describe("Confirm the update"),confirmationToken:l.string().optional().describe("Internal confirmation token returned by the confirmation flow"),contentHash:l.string().optional().describe("Content hash for optimistic concurrency")}).strict(),Rc=l.object({entityType:l.string().describe("Entity type"),id:l.string().describe("Entity ID"),confirmed:l.literal(!0).optional().describe("Confirm the deletion"),confirmationToken:l.string().optional().describe("Internal confirmation token returned by the confirmation flow")}),IC=l.object({entityType:l.string().describe("Entity type to extract"),source:l.string().optional().describe("Source entity ID \u2014 omit for batch"),mode:l.enum(["derive","rebuild"]).optional().describe("Batch mode: project incrementally or rebuild from scratch"),confirmed:l.literal(!0).optional().describe("Confirm destructive rebuild"),confirmationToken:l.string().optional().describe("Internal confirmation token returned by the confirmation flow")}),wc=l.object({batchId:l.string().optional().describe("Specific batch ID to check"),jobTypes:l.array(l.string()).optional().describe("Filter by job types")}),Xm=l.object({entityType:l.string().optional(),entityId:l.string().optional(),attachmentType:l.string().optional()}),eg=l.object({mediaType:l.string(),url:l.string(),downloadUrl:l.string().optional(),previewUrl:l.string().optional(),filename:l.string().optional(),sizeBytes:l.number().optional(),source:Xm.optional()}),TC=l.object({entityId:l.string().optional(),status:l.enum(["created","generating"]),jobId:l.string().optional(),attachment:eg.optional()}),EC=l.object({status:l.literal("extracting"),jobId:l.string(),entityType:l.string(),source:l.string().optional(),mode:l.enum(["derive","rebuild"]).optional()});function xc(e,t,r){return r==="create"?e.getCreateFieldsSchema(t):e.getEditableFieldsSchema(t)}function Ic(e){if(e instanceof l.ZodOptional||e instanceof l.ZodNullable||e instanceof l.ZodDefault)return Ic(e.unwrap());return e instanceof l.ZodType?e:void 0}function Pc(e){try{let{$schema:t,...r}=l.toJSONSchema(e,{target:"draft-7",io:"input"});return r}catch{return}}function tg(e){return Cc({type:"object",properties:{value:e},required:["value"]})!==void 0}function Tc(e,t){let r=new Map,i=new Map,n=e.getAllEntityTypes();for(let d of n){let u=xc(e,d,t.on);for(let[p,m]of Object.entries(u?.shape??{})){if(t.omit?.includes(p))continue;let g=Ic(m),f=g&&Pc(g);if(!g||!f||!tg(f))continue;let h=r.get(p)??new Map;h.set(JSON.stringify(f),g),r.set(p,h),i.set(p,[...i.get(p)??[],d])}}let o=new Map;for(let[d,u]of r){let[p,...m]=[...u.values()];if(!p)continue;let g=m.length>0?l.union([p,...m]):p,f=JSON.stringify(Pc(g)),h=o.get(f)??{value:g,names:[]};h.names.push(d),o.set(f,h)}let s=[...o.values()].map(({value:d,names:u})=>{let[p,...m]=u,g=u.map((f)=>{let h=i.get(f)??[];return`${f} (${h.length===n.length?"every type":h.join(", ")})`}).join("; ");return l.strictObject({name:(m.length>0&&p!==void 0?l.enum([p,...m]):l.literal(p??"")).describe(`The field, set only on the entity types named: ${g}.`),value:t.on==="update"?d.nullable():d})}),[a,...c]=s;return l.array(a?c.length>0?l.union([a,...c]):a:l.never())}function rg(e){return Object.fromEntries((Array.isArray(e)?e:[]).flatMap((t)=>X(t)&&typeof t.name==="string"?[[t.name,t.value]]:[]))}function or(e,t,r,i){if(!r)return;let{allow:n}=i,o=new Set(Object.keys(xc(e,t,i.on)?.shape??{})),s=Object.keys(r).filter((d)=>!o.has(d)&&!n.includes(d));if(s.length===0)return;let a=s.map((d)=>`"${d}"`).join(", "),c=[...o].join(", ")||"none";return`A ${t} has no ${s.length>1?"fields":"field"} ${a} a caller can set; its fields are ${c}.`}function $i(e){return"fields"in e&&e.fields!==void 0?{...e,fields:rg(e.fields)}:e}function Ec(e){return{prepare:()=>e.ensureGroupingsCurrent(),inputSchema:()=>{let t=Tc(e,{on:"create",omit:["visibility"]}),r=it.shape.items.element,i=it.extend({items:l.array(r.extend({fields:t.optional().describe("Field changes the user stated for this file alone, one { name, value } per field, such as the date and address it was first published at: [{ name: 'publishedAt', value }, { name: 'canonicalUrl', value }]; facts shared by every file go in the top-level fields.")})).min(2).max(20)}),[n,...o]=Mi.options.map((s)=>s===it?i:s);if(!n)throw Error("system_create has no source branches");return{...ir.shape,source:l.discriminatedUnion("kind",[n,...o]).describe("Concrete source selector. Use exactly one source branch. For AI generation or source-derived artifacts, use system_generate instead."),fields:t.optional().describe("Field changes for facts the user states outside the source text, one { name, value } per field, e.g. a post first published elsewhere: [{ name: 'status', value: 'published' }, { name: 'publishedAt', value: '2025-03-12' }, { name: 'canonicalUrl', value }]; the section a doc goes in, named exactly as the user names it: [{ name: 'section', value }]; the year a project began: [{ name: 'year', value }]. Never copy values from the text or its frontmatter; omit when nothing extra is stated.")}},toToolInput:(t)=>{let r=t.source;return $i({...t,...X(r)&&Array.isArray(r.items)&&{source:{...r,items:r.items.map((i)=>X(i)?$i(i):i)}}})}}}function Ui(e){let t=e.unwrap();return e.description?t.describe(e.description):t}function kc(e){let{content:t,edits:r,source:i}=Li.shape;return{prepare:()=>e.ensureGroupingsCurrent(),inputSchema:()=>({...nr.shape,operation:l.union([l.strictObject({fields:Tc(e,{on:"update"}).describe("Change frontmatter or metadata fields, one { name, value } per field changed. Use this for status, title, coverImageId, ogImageId, and metadata changes such as approving an agent. To set an existing image as an entity cover, change coverImageId to that image id. To remove a field, such as a cover image, give it the value null, not an empty string. Do not use fields for anchor-profile; anchor-profile updates require the content operation.")}),l.strictObject({content:Ui(t)}),l.strictObject({edits:Ui(r)}),l.strictObject({source:Ui(i)})]).describe("Exactly one update operation")}),toToolInput:(n)=>{let o=n.operation;return X(o)?{...n,operation:$i(o)}:n}}}function F(e,t,r,i){try{e.permissionService.assertEntityActionAllowed(t,r,i.userPermissionLevel);return}catch(n){if(n instanceof Ac||n instanceof Error)return{success:!1,error:n.message};throw n}}async function ar(e,t,r,{confirmed:i}){let n=r.conversationId??r.channelId;if(!n)return{success:!1,error:"Conversation message is not accessible in this conversation or does not exist."};let o=await e.conversationService.getMessages(n,{limit:100}),s=t.kind==="user-message",a=s?o.filter((y)=>{if(y.role!=="user")return!1;let S=r.userPermissionLevel??"public";if(S==="admin")return!0;let R=sr(y.metadata)?.userPermissionLevel;return(R==="public"||R==="trusted"||R==="admin")&&e.permissionService.hasPermission(S,R)}):o.filter(jc),c=t.messageId?a.find((y)=>y.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(!s)return{success:!0,messageId:c.id,content:c.content};let d=sg(og(t,c.content),c.content),u=(y,S,R,w)=>{if(!S)return{offset:R};let x=`${y} ${JSON.stringify(S)}`;if(d.boundaryMode==="lines"&&/[\r\n]/.test(S))return{problem:`${x} contains a newline; in lines mode give the marker line's text only`};let I=ig(c.content,S,d.boundaryMode==="lines"?"lines":"literal",w),[M]=I;if(I.length===1&&M!==void 0)return{offset:M};return{problem:I.length===0?`${x} does not occur in the message`:`${x} occurs ${I.length} times in the message`}},p=u("startAfter",d.startAfter,0,!0),m=d.boundaryMode==="frontmatter"&&"offset"in p?cg(c.content,p.offset):p,g=u("endBefore",d.endBefore,c.content.length,!1),f=[m,g].flatMap((y)=>("problem"in y)?[y.problem]:[]);if(f.length===0&&"offset"in m&&"offset"in g&&m.offset>=g.offset)f.push("startAfter must come before endBefore with content between them");if(!("offset"in m)||!("offset"in g)||f.length>0)return{success:!1,error:`User-message boundary ${f.join("; ")}; each boundary must occur exactly once. ${ag(c.content)}`};let h=c.content.slice(m.offset,g.offset).replace(/^(?:[ \t]*\r?\n)+(?=---\r?\n)/,""),v=i?t.contentHash:void 0;if(v&&v!==le(h))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:h,source:d}}function cr(e,t){let{startAfter:r,endBefore:i,...n}=t.source??e;return{...n,...r?{startAfter:r}:{},...i?{endBefore:i}:{},messageId:t.messageId,contentHash:le(t.content)}}function ig(e,t,r,i){if(r==="lines"){let o=Bi(e,t,i);return o.length>0||!t.trim()?o:Bi(e,t,i,ng)}let n=Dc(e,t,i);return n.length>0?n:lg(e,t,i)}function ng(e){return e.trim().replace(/\s+/g," ")}function og(e,t){let r=(a)=>a?.trim()==="---";if(!r(e.startAfter)&&!r(e.endBefore))return e;if((t.match(/^---\r?$/gm)?.length??0)!==2||_i(t,0).length!==1)return e;let{startAfter:n,endBefore:o,...s}=e;return{...s,boundaryMode:"frontmatter",...r(n)?{}:{startAfter:n},...r(o)?{}:{endBefore:o}}}function sg(e,t){let{startAfter:r,endBefore:i}=e;if(e.boundaryMode!==void 0||!r||!i)return e;let n=(o)=>!/[\r\n]/.test(o)&&Bi(t,o,!0).length===1;return n(r)&&n(i)?{...e,boundaryMode:"lines"}:e}function ag(e){return _i(e,0).length===1?'--- fences frontmatter, which is part of the content: retry with boundaryMode "frontmatter" and no startAfter or endBefore.':"To select everything after an instruction, use boundaryMode literal with startAfter set to the instruction's exact text and omit endBefore."}function cg(e,t){let r=_i(e,t),[i]=r;if(r.length===1&&i!==void 0)return{offset:i};return{problem:r.length===0?"boundaryMode frontmatter finds no --- frontmatter block":`boundaryMode frontmatter finds ${r.length} --- frontmatter blocks`}}function _i(e,t){return Array.from(e.slice(t).matchAll(/^---\r?\n["']?[A-Za-z_][\w-]*["']?[ \t]*:.*\r?\n(?:.*\r?\n)*?---\r?$/gm),(r)=>t+r.index)}function Bi(e,t,r,i=(n)=>n){let n=i(t);return e.split(/(?<=\n)/).reduce((o,s)=>({offset:o.offset+s.length,matches:i(s.replace(/\r?\n$/,""))===n?[...o.matches,o.offset+(r?s.length:0)]:o.matches}),{offset:0,matches:[]}).matches}function lg(e,t,r){let i=t.trim().split(/\s+/);if(i.join("")===""||!/\s/.test(t))return[];let n=(s)=>s?"\\s*":"",o=new RegExp(n(/^\s/.test(t))+i.map(dg).join("\\s+")+n(/\s$/.test(t)),"g");return Array.from(e.matchAll(o),(s)=>s.index+(r?s[0].length:0))}function dg(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Dc(e,t,r,i=0){let n=e.indexOf(t,i);if(n<0)return[];return[n+(r?t.length:0),...Dc(e,t,r,n+1)]}var ug=/^[ \t]*---[ \t]*$/gm;function zc(e){return e.replace(/\s+/g," ").trim()}function pg(e){return e.kind==="user-message"?e.messageId:void 0}class Zi{pins=new Map;now;constructor(e=Date.now){this.now=e}pin(e,t){this.pins.set(e,{...t,expiresAt:this.now()+1800000})}clear(e){this.pins.delete(e)}live(e){let t=this.pins.get(e);if(t&&t.expiresAt<this.now()){this.pins.delete(e);return}return t}resolveUnresolvable(e,t){let r=this.live(e);if(!r||t.kind!=="user-message"||t.messageId)return;return{kind:"pinned",source:r.source,content:r.content}}resolve(e,t){let r=this.live(e);if(!r)return{kind:"as-given"};let i=pg(r.source),n={kind:"pinned",source:r.source,content:r.content};if(t.source.kind==="user-message"&&t.source.messageId){if(t.source.messageId!==i)this.pins.delete(e);return{kind:"as-given"}}if(t.content===void 0)return{kind:"as-given"};if(r.question==="slide-breaks"&&t.content!==r.content&&zc(t.content.replace(ug,""))===zc(r.content))return{kind:"as-given"};if(t.source.kind==="text")return n;if(t.source.kind==="user-message"&&t.resolvedMessageId!==i){if(t.content.length*2<r.content.length)return n;this.pins.delete(e)}return{kind:"as-given"}}}function Fi(e,t){return e?`${e}\x00${t}`:void 0}function Oc(e){if(e.kind!=="user-message")return e;let{contentHash:t,...r}=e;return r}var mg="system";function q(e,t,r,i,n={}){let{visibility:o="admin",sideEffects:s}=n;return{name:`${mg}_${e}`,description:t,inputSchema:r.shape,handler:async(a,c)=>{let d=r.safeParse(a);if(!d.success)return{success:!1,error:`Invalid input: ${d.error.issues.map((u)=>`${u.path.join(".")}: ${u.message}`).join(", ")}`};try{return await i(d.data,c)}catch(u){return{success:!1,error:C(u)}}},visibility:o,...s?{sideEffects:s}:{}}}function lr(e){return{interfaceType:e.interfaceType,actor:e.actor,userPermissionLevel:e.userPermissionLevel??"public",...e.channelId&&{channelId:e.channelId},...e.channelName&&{channelName:e.channelName}}}async function dr(e,t,r,i){let n=await t(r,lr(i));if(n.kind==="handled")return{kind:"handled",result:n.result};let o=n.input;if(o.visibility!==r.visibility)return{kind:"error",result:{success:!1,error:"Create interceptor changed or dropped the requested entity visibility."}};let s=F(e,o.entityType,"create",i);if(s)return{kind:"error",result:s};return{kind:"continue",createInput:o}}function we(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 Me(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 Ni(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 Pe(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var gg={base:"note"};function Mc(e){return gg[e]??e.replaceAll("-"," ")}function ur(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 Lc(e){return!!e&&Object.keys(e.shape).length>0}async function Uc(e,t,r){if(!r)return!1;let i=await e.conversationService.getMessages(r,{limit:100});for(let n of i){let s=sr(n.metadata)?.attachments;if(!Array.isArray(s))continue;for(let a of s){if(!ae(a))continue;let c=a.source;if(!ae(c))continue;if(c.kind===t.kind&&c.id===t.id)return!0}}return!1}async function pr(e,t,r){if(t.replace||!t.candidateId)return{kind:"ok",value:void 0};let i=await e.entityService.getEntity({entityType:t.entityType,id:t.candidateId,visibilityScope:A(r.userPermissionLevel)});if(!i)return{kind:"ok",value:void 0};if(i.metadata.status==="failed"&&r.userPermissionLevel==="admin"&&!F(e,t.entityType,"delete",r))return{kind:"ok",value:{entityType:i.entityType,id:i.id}};return{kind:"error",result:{success:!1,error:`A ${t.entityType} already exists for "${t.candidateId}". To change it, use system_update on that ${t.entityType} in this turn, without asking first; pass replace:true to ${t.copyHint}.`}}}function mr(e){return`Replaces: failed ${e.entityType} "${e.id}"`}async function gr(e,t){if(!t)return;try{await e.entityService.deleteEntity(t);return}catch(r){return{success:!1,error:C(r,"Failed to replace the failed entity")}}}function Hi(e){return`${e.entityType} "${e.title}"`}function fg(e){return Object.entries(e).map(([t,r])=>`${t}: ${typeof r==="string"?r:JSON.stringify(r)}`).join(", ")}function $c(e){return"error"in e?e.error:"the save was not completed"}function hg(e){let t=new Map;for(let r of e){let i=`${r.entityType}:${te(r.title)}`,n=t.get(i);if(n)return`${n.filename} and ${r.filename} would both be saved as ${Hi(r)}. Give them different titles in source.items.`;t.set(i,r)}return}function yg(e,t){return{summary:`Save ${e.length} uploaded files?`,completionSummary:`Saved ${e.length} uploaded files: ${e.map(Hi).join(", ")}.`,preview:[...e.map((r,i)=>[`${i+1}. ${r.filename} \u2192 ${Hi(r)}`,...r.fields?[` ${fg(r.fields)}`]:[],...r.replacesFailed?[` Replaces failed ${r.replacesFailed}`]:[]].join(`
78
78
  `)),`Visibility: ${t??"public"}`].join(`
79
- `)}}async function vg(e){let t=[],r=[];for(let i of e){let n=await i.save();if("success"in n&&n.success)t.push({filename:i.filename,entityType:i.entityType,title:i.title,...X(n.data)?n.data:{}});else r.push(`${i.filename}: ${Uc(n)}`)}if(r.length>0)return{success:!1,error:`${t.length>0?`Saved ${t.map((n)=>`${String(n.entityType)} "${String(n.title)}"`).join(", ")}. `:""}Could not save ${r.join("; ")}.`};return{success:!0,data:{status:t.some((i)=>i.status==="generating")?"generating":"created",items:t}}}async function $c(e){let{input:t,gate:r}=e;if(t.title!==void 0)return{success:!1,error:"Several uploads take their titles from source.items, not a shared title."};let i=[];for(let[a,c]of t.source.items.entries()){let d=await e.prepare(c);if(d.kind==="error")return{success:!1,error:`Upload ${a+1} of ${t.source.items.length} (${c.id}): ${Uc(d.result)}`};i.push(d.value)}let n=hg(i);if(n)return{success:!1,error:n};if(t.confirmed){let a=r.validateConfirmed(t.confirmationToken,t);if(a)return a;return vg(i)}let o=yg(i,t.visibility),s=r.buildArgs((a)=>({entityType:t.entityType,...t.visibility!==void 0?{visibility:t.visibility}:{},source:{kind:"uploads",items:t.source.items.map((c,d)=>({id:c.id,transform:c.transform,title:i[d]?.title??c.title,...(i[d]?.fields??c.fields)&&{fields:i[d]?.fields??c.fields}}))},...t.fields&&{fields:t.fields},...t.replace?{replace:t.replace}:{},confirmed:!0,confirmationToken:a}));return{needsConfirmation:!0,toolName:"system_create",summary:o.summary,completionSummary:o.completionSummary,preview:o.preview,args:s}}function bg(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(`
79
+ `)}}async function vg(e){let t=[],r=[];for(let i of e){let n=await i.save();if("success"in n&&n.success)t.push({filename:i.filename,entityType:i.entityType,title:i.title,...X(n.data)?n.data:{}});else r.push(`${i.filename}: ${$c(n)}`)}if(r.length>0)return{success:!1,error:`${t.length>0?`Saved ${t.map((n)=>`${String(n.entityType)} "${String(n.title)}"`).join(", ")}. `:""}Could not save ${r.join("; ")}.`};return{success:!0,data:{status:t.some((i)=>i.status==="generating")?"generating":"created",items:t}}}async function Bc(e){let{input:t,gate:r}=e;if(t.title!==void 0)return{success:!1,error:"Several uploads take their titles from source.items, not a shared title."};let i=[];for(let[a,c]of t.source.items.entries()){let d=await e.prepare(c);if(d.kind==="error")return{success:!1,error:`Upload ${a+1} of ${t.source.items.length} (${c.id}): ${$c(d.result)}`};i.push(d.value)}let n=hg(i);if(n)return{success:!1,error:n};if(t.confirmed){let a=r.validateConfirmed(t.confirmationToken,t);if(a)return a;return vg(i)}let o=yg(i,t.visibility),s=r.buildArgs((a)=>({entityType:t.entityType,...t.visibility!==void 0?{visibility:t.visibility}:{},source:{kind:"uploads",items:t.source.items.map((c,d)=>({id:c.id,transform:c.transform,title:i[d]?.title??c.title,...(i[d]?.fields??c.fields)&&{fields:i[d]?.fields??c.fields}}))},...t.fields&&{fields:t.fields},...t.replace?{replace:t.replace}:{},confirmed:!0,confirmationToken:a}));return{needsConfirmation:!0,toolName:"system_create",summary:o.summary,completionSummary:o.completionSummary,preview:o.preview,args:s}}function bg(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(`
80
80
  `)}}function Sg(e){let{entityType:t,title:r,visibility:i,prompt:n,content:o,url:s,from:a,fields:c}=e,d=r?` "${r}"`:` ${t}`,u=`${n?"Generate":"Create"}${d}?`,p=a?.kind==="entity-attachment"?a:void 0,m=[`Entity type: ${t}`,`Visibility: ${i??"public"}`,...r?[`Title: ${r}`]:[],...s?[`URL: ${s}`]:[],...a?.kind==="upload"?["Upload: uploaded file"]:[],...p?[`Source attachment: ${p.sourceEntityType}/${p.sourceEntityId} (${p.attachmentType})`]:[],...n?[`Prompt: ${n}`]:[],...Object.entries(c??{}).map(([g,f])=>`${g}: ${typeof f==="string"?f:JSON.stringify(f)}`),...o?[`Content preview: ${o.slice(0,500)}`]:[]];return{summary:u,preview:m.join(`
81
- `)}}function Rg(e){let t=e.title?` "${e.title}"`:"";return`Saved ${e.entityType}${t}.`}function wg(e){switch(e.kind){case"text":return{content:e.content};case"url":return{url:e.url};case"upload":{let t={kind:"upload",id:e.id};return{from:t,uploadRef:t,transform:e.transform}}case"prior-response":case"user-message":return{conversationMessageRef:e};case"entity":return{entityRef:{entityType:e.entityType,entityId:e.entityId}};case"uploads":throw Error("Several uploads are prepared one upload at a time")}}async function Pg(e,t,r){let i=await B(e.entityService,t.entityType,t.entityId,e.logger,"Source entity",A(r.userPermissionLevel));if(!i.ok)return O(i.error);let{entity:n}=i,o=Bc(n.content);if(!o)return O(`Source entity ${n.entityType}/${n.id} has no text to use.`);let s=n.metadata.title;return{kind:"ok",value:{ref:{entityType:n.entityType,entityId:n.id},content:o,title:typeof s==="string"&&s.trim()?s:void 0,visibility:n.visibility}}}function Hc(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 cr(e.source,{messageId:e.resolvedMessageId,content:e.content,...e.resolvedUserSource&&{source:e.resolvedUserSource}})}if(e.source.kind==="prior-response"){let t=e.source.messageId??e.resolvedMessageId;return{kind:"prior-response",...t?{messageId:t}:{}}}if(e.source.kind==="entity"&&e.resolvedEntity)return{kind:"entity",...e.resolvedEntity};return e.source}async function Cg(e,t){let r=lr(t);return e.handler({upload:e.upload,...e.title&&{title:e.title},...e.visibility!==void 0?{visibility:e.visibility}:{}},r)}async function xg(e,t,r){let{entityService:i,entityRegistry:n}=e,o=te(t.title??`${t.entityType}-${Date.now()}`),s=n.getEffectiveFrontmatterSchema(t.entityType),a=t.content!==void 0&&Mc(s);if(t.fields&&!a)return{success:!1,error:`${t.entityType} has no frontmatter to set fields on; save the text without fields.`};try{let c={deduplicateId:!0,...r?{eventContext:r}:{}};return{success:!0,data:{entityId:(t.content&&a?await i.createEntityFromMarkdown({input:{entityType:t.entityType,id:o,markdown:t.fields?fr(t.fields,t.content):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 O(e){return{kind:"error",result:{success:!1,error:e}}}async function Ig(e,t,r){let{content:i,url:n,from:o,uploadRef:s,conversationMessageRef:a,entityRef:c,transform:d}=wg(t.source),u=c?await Pg(e,c,r):void 0;if(u?.kind==="error")return u;let p=a?await ar(e,a,r,{confirmed:t.confirmed===!0}):void 0;if(p&&!p.success)return{kind:"error",result:p};let m=p?.success===!0?p.content:u?.value.content??i;if(d==="extract-markdown"&&!s)return O('Transform "extract-markdown" requires an upload ref.');if(!m&&!n&&!o)return O('Provide `source` with kind "user-message", "text", "url", "prior-response", "upload", or "entity". Use system_generate for generated content or artifacts.');return{kind:"ok",value:{content:m,url:n,from:o,uploadRef:s,transform:d,resolvedMessageId:p?.success===!0?p.messageId:void 0,resolvedUserSource:p?.success===!0?p.source:void 0,entitySource:u?.value}}}async function Tg(e,t){if(!Zc(t.mediaType))return;let{content:r}=await e.runtimeUploads.scoped(Ae).read(t.id);return _c(r).toString("utf8")}async function Eg(e,t,r){if(!await Lc(e,t.uploadRef,r.conversationId??r.channelId))return O("Upload ref is not accessible in this conversation or no longer exists.");let n,o;try{n=await e.runtimeUploads.scoped(Ae).readRecord(t.uploadRef.id),o=t.transform==="extract-markdown"?await Tg(e,{id:t.uploadRef.id,mediaType:n.mediaType}):void 0}catch{return O("Upload ref not found")}let s=Nc({filename:n.filename,markdown:o});if(t.transform!=="preserve")return{kind:"ok",value:{entityType:t.entityType,title:s,filename:n.filename,mediaType:n.mediaType,markdown:o,uploadPreserve:void 0}};let a=e.entityRegistry.getUploadSaveHandler(n.mediaType);if(!a)return O(`No installed plugin can save uploads with media type "${n.mediaType}".`);return{kind:"ok",value:{entityType:a.entityType,title:s,filename:n.filename,mediaType:n.mediaType,markdown:o,uploadPreserve:{upload:t.uploadRef,filename:n.filename,mediaType:n.mediaType,handler:a.handler}}}}function kg(e,t,r){let i=t?yr(t):void 0;if(e!==void 0&&i!==void 0&&e!==i)return O(`Conflicting entity visibility: system_create requested "${e}" but the source frontmatter declares "${i}".`);let n=e??i,o=n??"public";if(!hr(r.userPermissionLevel,o))return O(`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}}function Ag(e,t,r){return pr(e,{entityType:t.entityType,candidateId:t.title?te(t.title):void 0,replace:t.replace===!0,copyHint:"create a new copy intentionally"},r)}function jg(e,t,r,i){let n=e.entityRegistry;if(r.transform!=="extract-markdown"||!i||n.getEntityTypeConfig(t).markdownImport)return{kind:"ok",value:r};if(i.markdown===void 0){let o=n.getAllEntityTypes().filter((a)=>n.getEntityTypeConfig(a).markdownImport),s=o.length>0?`Import it as a ${o.join(" or ")}, or keep`:"Keep";return O(`A ${t} takes the text of a text upload; ${i.filename} (${i.mediaType}) is not text. ${s} the file itself with transform "preserve".`)}return{kind:"ok",value:{content:i.markdown,from:void 0,transform:void 0}}}async function Dg(e,t,r){let i=e.entityRegistry.getCreateCheck(t.entityType);if(!i)return{kind:"ready"};try{return await i(t,lr(r))}catch(n){return{kind:"error",error:C(n,`Could not check the ${t.entityType}`)}}}function zg(e,t,r){return["Nothing was saved and no approval was requested.",`Ask the user this question in your reply, as written, without mentioning tools or fields: "${e.question}"`,r?`When they answer, call system_create again; to save the same files, pass source ${JSON.stringify(r.source)}, with the answer about this file in its item.`:`When they answer, call system_create again; to save the same text, pass source ${JSON.stringify(zc(t))}.`,e.answerWith].join(" ")}function Og(e,t){let r={...Object.fromEntries(Object.entries(t.fields??{}).filter(([,n])=>n!==void 0)),...e.fields},i=e.title??t.title;return{...e,...i&&{title:i},...Object.keys(r).length>0&&{fields:r}}}async function Wc(e,t,r,i,n){if(!(t.source.kind==="upload"&&t.source.transform==="preserve")){let oe=we(e,t.entityType);if(oe)return{kind:"error",result:oe}}let s=Fi(r.conversationId??r.channelId,t.entityType),a=await Ig(e,t,r),c=a.kind==="error"&&s?i.resolveUnresolvable(s,t.source):void 0,d=c?{kind:"ok",value:{content:c.content,url:void 0,from:void 0,uploadRef:void 0,transform:void 0,resolvedMessageId:void 0,resolvedUserSource:void 0,entitySource:void 0}}:a;if(d.kind==="error")return d;let{url:u,uploadRef:p,resolvedMessageId:m,resolvedUserSource:g,entitySource:f}=d.value,h=c??(s?i.resolve(s,{source:t.source,content:d.value.content,resolvedMessageId:m}):{kind:"as-given"}),v=p?await Eg(e,{entityType:t.entityType,uploadRef:p,transform:d.value.transform},r):void 0;if(v?.kind==="error")return v;let y=v?.value.entityType??t.entityType,S=v?.value.uploadPreserve,R=jg(e,y,d.value,v?.value);if(R.kind==="error")return R;let{from:w,transform:x}=R.value,I=h.kind==="pinned"?h.content:R.value.content,M=we(e,y);if(M)return{kind:"error",result:M};let re=f&&f.visibility!=="public"?f.visibility:void 0,U=kg(t.visibility??re,I,r);if(U.kind==="error")return U;if(t.fields&&"visibility"in t.fields)return O("Set visibility with the typed `visibility` input, not in `fields`.");let _=t.fields&&Object.keys(t.fields).length>0?t.fields:void 0,st=Pe(t.title),at=(v&&Fc(st,v.value.filename)?void 0:st)??f?.title??v?.value.title,ct=t.replace===!0,ie={entityType:y,...at&&{title:at},...U.value!==void 0?{visibility:U.value}:{},...I&&{content:I},...u&&{url:u},...w&&{from:w},...x&&{transform:x},..._&&{fields:_},...ct&&{replace:ct}},lt=F(e,ie.entityType,"create",r);if(lt)return{kind:"error",result:lt};let $e=e.entityRegistry.getCreateInterceptor(ie.entityType);if(!ie.content&&!$e&&!S)return O('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 J=t.confirmed||S?void 0:await Dg(e,ie,r);if(J?.kind==="error")return O(J.error);if(J?.kind==="question"){let oe=h.kind==="pinned"?h.source:Hc({source:t.source,...m&&{resolvedMessageId:m},...g&&{resolvedUserSource:g},...f&&{resolvedEntity:f.ref},...I!==void 0?{content:I}:{}});if(s&&I!==void 0&&!p)i.pin(s,{source:oe,content:I,question:J.asks});return O(zg(J,oe,n))}let xe=J?.kind==="ready"?Og(ie,J):ie,ne=await Ag(e,xe,r);if(ne.kind==="error")return ne;return{kind:"ok",prepared:{createInput:xe,resolvedMessageId:m,resolvedUserSource:g,...h.kind==="pinned"&&{pinnedSource:h.source},...f&&{resolvedEntity:f.ref},interceptor:$e,eventContext:Me(r),...v&&{uploadFilename:v.value.filename},...p&&{uploadId:p.id},...ne.value&&{replacesFailed:ne.value},...S&&{uploadPreserve:S}}}}async function qc(e,t,r,i){let n=await Mg(e,t,r,i),{uploadId:o}=t;if(o===void 0||!("success"in n)||!n.success)return n;if(!X(n.data))return n;return{...n,data:{entityType:t.createInput.entityType,...n.data,uploadId:o}}}async function Mg(e,t,r,i){let{interceptor:n,eventContext:o,uploadPreserve:s,replacesFailed:a}=t,{createInput:c}=t,d=Fi(r.conversationId??r.channelId,c.entityType),u=await gr(e,a);if(u)return u;if(s)return Cg({upload:s.upload,...c.title&&{title:c.title},...c.visibility!==void 0?{visibility:c.visibility}:{},handler:s.handler},r);if(n){let m=await dr(e,n,c,r);if(m.kind==="error")return m.result;if(m.kind==="handled"){let{result:g}=m;if(d&&"success"in g&&g.success)i.clear(d);return g}c=m.createInput}if(!c.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.'};let p=await xg(e,c,o);if(d&&"success"in p&&p.success)i.clear(d);return p}async function Lg(e,t,r,i,n){let o={...t.fields,...r.fields},s=await Wc(e,{entityType:t.entityType,...r.title!==void 0?{title:r.title}:{},...t.visibility!==void 0?{visibility:t.visibility}:{},source:{kind:"upload",id:r.id,transform:r.transform},...Object.keys(o).length>0&&{fields:o},...t.replace!==void 0?{replace:t.replace}:{},...t.confirmed&&{confirmed:t.confirmed}},i,n,{source:t.source});if(s.kind==="error")return s;let{prepared:a}=s;return{kind:"ok",value:{filename:a.uploadFilename??r.id,entityType:a.createInput.entityType,title:a.createInput.title??a.uploadFilename??"",...a.createInput.fields&&{fields:a.createInput.fields},...a.replacesFailed&&{replacesFailed:`${a.replacesFailed.entityType} "${a.replacesFailed.id}"`},save:()=>qc(e,a,i,n)}}}function Jc(e){let t=ee({label:"create",requestNoun:"creation"}),r=new Zi;return{...q("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 such as a team note, restricted for private/admin-only content, and omit it for public content; keep visibility separate from exact source text. Public callers may write only public content, Trusted callers public or shared, and Admin callers all three. If the user only says 'not public' without saying team/shared or private/admin-only, ask which scope they mean. 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; that content is sufficient even when 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'), so never ask the user to paste it again. 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. To save a pasted document that opens with --- frontmatter, use boundaryMode frontmatter without startAfter or endBefore: the server selects it from its opening fence, and the fences are content, never boundaries. 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, and then use it even though the file text also appears in the message; only a pasted uploaded-file transcript (for example, User uploaded a file \"name.md\": ...) with no listed upload ref is saved with source.kind user-message boundaries.",ir,async(n,o)=>{await e.entityRegistry.ensureGroupingsCurrent(n.entityType);let s=[n.fields,...n.source.kind==="uploads"?n.source.items.map((f)=>f.fields):[]].map((f)=>or(e.entityRegistry,n.entityType,f,{on:"create",allow:["visibility"]})).find((f)=>f!==void 0);if(s)return{success:!1,error:s};if(n.source.kind==="uploads")return $c({input:{...n,source:n.source},gate:t,prepare:(f)=>Lg(e,n,f,o,r)});let a=await Wc(e,n,o,r);if(a.kind==="error")return a.result;let{createInput:c}=a.prepared,{resolvedMessageId:d,resolvedUserSource:u,pinnedSource:p,resolvedEntity:m,uploadPreserve:g}=a.prepared;if(n.confirmed){let f=t.validateConfirmed(n.confirmationToken,n);if(f)return f}else{let f=g?bg({...c.title&&{title:c.title},filename:g.filename,mediaType:g.mediaType,entityType:c.entityType,visibility:c.visibility}):Sg(c),h=a.prepared.replacesFailed?{...f,preview:`${f.preview}
82
- ${mr(a.prepared.replacesFailed)}`}:f,v=p??Hc({source:n.source,...d&&{resolvedMessageId:d},...u&&{resolvedUserSource:u},...m&&{resolvedEntity:m},...c.content!==void 0?{content:c.content}:{}}),y=t.buildArgs((S)=>({entityType:c.entityType,...c.title&&{title:c.title},...c.visibility!==void 0?{visibility:c.visibility}:{},source:v,...c.fields&&{fields:c.fields},...c.replace&&{replace:c.replace},confirmed:!0,confirmationToken:S}));return{needsConfirmation:!0,toolName:"system_create",summary:h.summary,completionSummary:Rg(c),preview:h.preview,args:y}}return qc(e,a.prepared,o,r)},{visibility:"trusted",sideEffects:"writes"}),modelInput:Tc(e.entityRegistry)}}function Ug(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(`
83
- `)}}async function $g(e,t,r){if(!t)return{kind:"ok",sourceAttachment:void 0};let i=await B(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 Bg(e,t,r){if(!t)return{kind:"ok",source:void 0};let i=await B(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 _g(e,t,r){if(!t)return{kind:"ok",target:void 0};let i=await B(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 Zg(e,t,r,i,n){let{entityService:o,jobs:s}=e,a=Wi(te(t.title??r),100);if(!a)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 c=t.title??a,d=Gc(e.entityRegistry,{entityType:t.entityType,id:a,title:c});if(!d)return{success:!1,error:`Entity type '${t.entityType}' does not support queued generation. Provide an exact source to system_create instead.`};let u;try{u=(await o.createEntity({entity:d,options:{deduplicateId:!0,...i?{eventContext:i}:{}}})).entityId}catch(g){return{success:!1,error:C(g,"Failed to persist generation stub")}}let p={entityId:u,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}},m=e.entityRegistry.getGenerationEnqueuer(t.entityType);try{let g=m?await m(p,n):await s.enqueue({type:`${t.entityType}:generation`,data:p,toolContext:n});return{success:!0,data:{entityId:u,status:"generating",jobId:g}}}catch(g){return await o.deleteEntity({entityType:t.entityType,id:u}).catch((f)=>{e.logger.warn("Failed to remove unqueued generation stub",{entityType:t.entityType,entityId:u,error:f})}),{success:!1,error:C(g,"Failed to queue generation job")}}}async function Fg(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 s=t.kind==="prompt-from-source"?await Bg(e,t.source,r):{kind:"ok",source:void 0};if(s.kind==="error")return s;let a=Pe(t.title);i={entityType:t.entityType,...a?{title:a}:{},prompt:t.prompt,...s.source?.entityType&&{sourceEntityType:s.source.entityType},...s.source?.entityId&&{sourceEntityId:s.source.entityId,sourceEntityIds:[s.source.entityId]}}}else if(t.kind==="standalone-image"){let s=Pe(t.title);i={entityType:"image",...s?{title:s}:{},prompt:t.prompt}}else if(t.kind==="cover-image"){let s=await _g(e,t.target,r);if(s.kind==="error"){let c=s.result;return{kind:"error",result:"success"in c&&c.success===!1?{...c,code:"target-not-found"}:c}}let a=Pe(t.title);i={entityType:"image",...a?{title:a}:{},prompt:t.prompt,...s.target?.entityType&&{targetEntityType:s.target.entityType},...s.target?.entityId&&{targetEntityId:s.target.entityId}}}else{let s=await $g(e,{sourceEntityType:t.source.entityType,sourceEntityId:t.source.entityId,attachmentType:t.attachmentType},r);if(s.kind==="error")return s;n=s.sourceAttachment;let a=s.metadata;if(!a||!n)return{kind:"error",result:{success:!1,error:"Attachment generation requires provider metadata.",code:"provider-missing-metadata"}};let c=Pe(t.title);i={entityType:a.outputEntityType,...c?{title:c}:{},from:{kind:"entity-attachment",...n},...o&&{replace:o},...a.targetField&&{targetEntityType:n.sourceEntityType,targetEntityId:n.sourceEntityId}}}return{kind:"ok",createInput:i,sourceAttachment:n}}async function Ng(e,t,r){let i=t.operation,n=A(r.userPermissionLevel),o=await Fg(e,i,n);if(o.kind==="error")return o;let{createInput:s,sourceAttachment:a}=o,c=i.kind==="attachment"&&i.replace===!0,d=we(e,s.entityType);if(d)return{kind:"error",result:d};let u=F(e,s.entityType,"create",r);if(u)return{kind:"error",result:u};let p=e.entityRegistry.getCreateInterceptor(s.entityType);if(!s.prompt&&!s.from)return{kind:"error",result:{success:!1,error:"Provide a generation source."}};if(s.from&&!p)return{kind:"error",result:{success:!1,error:`Entity type '${s.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"}};let m=i.kind==="prompt"||i.kind==="prompt-from-source",g=p&&!m?void 0:await pr(e,{entityType:s.entityType,candidateId:s.prompt?Wi(te(s.title??s.prompt),100):s.title?te(s.title):void 0,replace:c===!0,copyHint:"generate a new copy intentionally"},r);if(g?.kind==="error")return g;return{kind:"ok",prepared:{createInput:s,operation:Hg(i,s,a),sourceAttachment:a,interceptor:p,eventContext:Me(r),...g?.value&&{replacesFailed:g.value}}}}function Hg(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 Qc(e){let t=ee({label:"generate",requestNoun:"generation"});return q("generate","Generate durable content or artifacts. Requires confirmation: calling this tool without confirmed is how you request it, so when the user asks to create, write, draft, or generate new durable content without supplying final exact content, call it instead of drafting the content in chat, asking for separate prose approval, or saying 'I can generate it if you want' or 'I need to queue it first'. Critical: broad or underspecified topical generation uses operation.kind prompt with no source field, also in the same turn after an optional search finds no source; preserve the user's wording as the prompt and do not stop to ask what details to highlight. Critical: to generate from an existing source such as 'my latest blog post', resolve it with read/search/list tools unless the user gives an exact entity id in quotes, then call operation.kind prompt-from-source right away, for example { kind: 'prompt-from-source', entityType: 'newsletter', source: { entityType: 'post', entityId: '...' }, prompt: '...' }. For the latest published/blog source, use system_list on that type (blog posts: entityType post) and choose the newest candidate by publishedAt, not updated/created or semantic search order; do not stop with prose like 'I found it and can generate it' or 'if that is the one you mean.' Never invent source IDs, use brain-character/profile, uploads, filenames, guessed ids, or placeholders as source refs. Turning an existing entity into another type ('turn my note X into a post') keeps its text and is not generation: call system_create with source.kind entity, also after a search resolves it. Use system_create as well for saving/importing existing text, URLs, uploads, prior assistant responses, or raw uploaded files. Critical: for a request to generate a post/social-post/newsletter/etc. with a cover image, call only the prompt generation first; call cover-image only once the target entity exists after confirmation, never guess its future id, and never use standalone-image as a substitute for a requested cover. When a cover-image request names the target's exact id in quotes or a search/get resolves a clear target, call cover-image in the same turn; do not stop after saying you found the entity. Use attachment for source-derived artifacts: attachmentType og-image for OG/social preview renders (the provider updates ogImageId), carousel for deck carousel PDFs, printable for post/project PDFs. Call it immediately for save/render requests, with replace:true for regenerate/replace/refresh, instead of saying you can queue it later. To attach a generated artifact to another entity, generate the artifact first in the same turn \u2014 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` \u2014 and update the target only after the real artifact ID exists.",bc,async(r,i)=>{let n=await Ng(e,r,i);if(n.kind==="error")return n.result;let{createInput:o}=n.prepared,{operation:s,interceptor:a,eventContext:c,replacesFailed:d}=n.prepared;if(r.confirmed){let p=t.validateConfirmed(r.confirmationToken,r);if(p)return p}else{let p=Ug(o),m=d?{...p,preview:`${p.preview}
84
- ${mr(d)}`}:p,g=t.buildArgs((f)=>({operation:s,confirmed:!0,confirmationToken:f}));return{needsConfirmation:!0,toolName:"system_generate",summary:m.summary,preview:m.preview,args:g}}let u=await gr(e,d);if(u)return u;if(a){let p=await dr(e,a,o,i);if(p.kind==="handled"||p.kind==="error")return p.result;o=p.createInput}if(!o.prompt)return{success:!1,error:"Attachment generation is supported only for entity types that explicitly handle source-derived artifacts."};return Zg(e,o,o.prompt,c,i)},{visibility:"trusted",sideEffects:"writes"})}function Kc(e){let{entityService:t,entityRegistry:r,logger:i}=e,n=ee({label:"delete",requestNoun:"deletion"});return q("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. For an entity the user names, call this tool directly without searching for or reading it first. Protected identity/profile records such as brain-character and anchor-profile cannot be deleted; update them instead.",Sc,async(o,s)=>{if((s.userPermissionLevel??"public")==="public")return{success:!1,error:"Changing content requires higher permission; current permission is Public."};let a=F(e,o.entityType,"delete",s);if(a)return a;let c=we(e,o.entityType);if(c)return c;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 d=A(s.userPermissionLevel),u=await B(t,o.entityType,o.id,i,void 0,d);if(!u.ok)return{success:!1,error:u.error};let{entity:p}=u;if(o.confirmed){let f=n.validateConfirmed(o.confirmationToken,o);if(f)return f;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 m=ur(p),g=n.buildArgs((f)=>({...o,id:p.id,confirmed:!0,confirmationToken:f}));return{needsConfirmation:!0,toolName:"system_delete",summary:`Delete "${m}"?`,preview:p.content.slice(0,200),args:g}},{visibility:"admin",sideEffects:"writes"})}function Vc(e,t){let r=t.map(({oldText:o,newText:s},a)=>{let c=e.indexOf(o);if(!o||c<0)throw Error(`Edit ${a+1}: oldText was not found. Fetch the entity again and provide exact text.`);if(e.indexOf(o,c+1)!==-1)throw Error(`Edit ${a+1}: oldText is ambiguous. Include more surrounding text to match exactly once.`);return{start:c,end:c+o.length,newText:s}}).sort((o,s)=>o.start-s.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 Yi}from"util";class vr{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),s=this.removeEmpty(this.tokenize(n,r)),a=this.removeEmpty(this.tokenize(o,r));return this.diffWithOptionsObj(s,a,r,i)}diffWithOptionsObj(e,t,r,i){var n;let o=(y)=>{if(y=this.postProcess(y,r),i){setTimeout(function(){i(y)},0);return}else return y},s=t.length,a=e.length,c=1,d=s+a;if(r.maxEditLength!=null)d=Math.min(d,r.maxEditLength);let u=(n=r.timeout)!==null&&n!==void 0?n:1/0,p=Date.now()+u,m=[{oldPos:-1,lastComponent:void 0}],g=this.extractCommon(m[0],t,e,0,r);if(m[0].oldPos+1>=a&&g+1>=s)return o(this.buildValues(m[0].lastComponent,t,e));let f=-1/0,h=1/0,v=()=>{for(let y=Math.max(f,-c);y<=Math.min(h,c);y+=2){let S,R=m[y-1],w=m[y+1];if(R)m[y-1]=void 0;let x=!1;if(w){let M=w.oldPos-y;x=w&&0<=M&&M<s}let I=R&&R.oldPos+1<a;if(!x&&!I){m[y]=void 0;continue}if(!I||x&&R.oldPos<w.oldPos)S=this.addToPath(w,!0,!1,0,r);else S=this.addToPath(R,!1,!0,1,r);if(g=this.extractCommon(S,t,e,y,r),S.oldPos+1>=a&&g+1>=s)return o(this.buildValues(S.lastComponent,t,e))||!0;else{if(m[y]=S,S.oldPos+1>=a)h=Math.min(h,y-1);if(g+1>=s)f=Math.max(f,y+1)}}c++};if(i)(function y(){setTimeout(function(){if(c>d||Date.now()>p)return i(void 0);if(!v())y()},0)})();else while(c<=d&&Date.now()<=p){let y=v();if(y)return y}}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,s=r.length,a=e.oldPos,c=a-i,d=0;while(c+1<o&&a+1<s&&this.equals(r[a+1],t[c+1],n))if(c++,a++,d++,n.oneChangePerToken)e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1};if(d&&!n.oneChangePerToken)e.lastComponent={count:d,previousComponent:e.lastComponent,added:!1,removed:!1};return e.oldPos=a,c}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,s=0,a=0,c=0;for(;s<o;s++){let d=i[s];if(!d.removed){if(!d.added&&this.useLongestToken){let u=t.slice(a,a+d.count);u=u.map(function(p,m){let g=r[c+m];return g.length>p.length?g:p}),d.value=this.join(u)}else d.value=this.join(t.slice(a,a+d.count));if(a+=d.count,!d.added)c+=d.count}else d.value=this.join(r.slice(c,c+d.count)),c+=d.count}return i}}class Yc extends vr{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}}var Xc=new Yc;function br(e,t,r){return Xc.diff(e,t,r)}var Sr=l.enum(["png","jpg","jpeg","webp","gif","svg"]),tl=l.enum(["pending","draft","failed"]),rl=l.object({title:l.string().optional(),alt:l.string().optional(),format:Sr.meta({studioWidget:"provenance"}),width:l.number().meta({studioWidget:"provenance"}),height:l.number().meta({studioWidget:"provenance"}),status:tl.optional().meta({studioWidget:"provenance"}),processingJobId:l.string().optional().meta({studioWidget:"hidden"}),processingError:l.string().optional().meta({studioWidget:"provenance"}),sourceUrl:l.url().optional().meta({studioWidget:"provenance"}),sourceEntityType:l.string().optional().meta({studioWidget:"provenance"}),sourceEntityId:l.string().optional().meta({studioWidget:"provenance"}),sourceUploadId:l.string().optional().meta({studioWidget:"provenance"}),sourceFilename:l.string().optional().meta({studioWidget:"provenance"}),sourceMediaType:l.string().optional().meta({studioWidget:"provenance"}),attachmentType:l.string().optional().meta({studioWidget:"provenance"}),dedupKey:l.string().optional().meta({studioWidget:"hidden"})}),il=el.extend({entityType:l.literal("image"),metadata:rl}),Wg=l.object({url:l.string(),alt:l.string(),title:l.string(),width:l.number(),height:l.number()});function nl(e){return/^https?:\/\//i.test(e)}async function ol(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 sl(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 Rr(e){let t=sl(e);if(!t)throw Error("Invalid image data URL");return t}function qg(e,t){return`data:image/${t==="jpg"?"jpeg":t};base64,${e}`}var Jg={png:"iVBORw",jpg:"/9j/",gif:"R0lGOD",webp:"UklGR"};function qi(e){for(let[t,r]of St(Jg))if(e.startsWith(r))return t;return null}function al(e){let t=e.toLowerCase(),r=t==="svg+xml"?"svg":t,i=Sr.safeParse(r);return i.success?i.data:null}async function Gg(e){return ol(e,"image/")}function wr(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,s=(r|i<<8)&16383,a=(n|o<<8)&16383;return{width:s,height:a}}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 cl(e){let t=al(e);if(!t)throw Error(`Unsupported image format: ${e}`);return t}function Qg(e){let{format:t,base64:r}=Rr(e),i=wr(r);return{format:cl(t),width:i?.width??0,height:i?.height??0}}function Kg(e){let{dataUrl:t,title:r,alt:i}=e,{format:n,base64:o}=Rr(t),s=wr(o),c=qi(o)??cl(n);return{entityType:"image",content:t,metadata:{title:r,alt:i??r,format:c,width:s?.width??0,height:s?.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}}}}function MI(e){return dl(e,{skipInvalid:!0,noRefs:!0,sortKeys:!0})}function ul(e){return ll(e)}var Vg=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,Yg=l.record(l.string(),l.unknown());function pl(e,t){let r=Vg.exec(e.content);if(!r?.[1])return;try{let i=Yg.safeParse(ul(r[1]));if(i.success){let n=i.data[t];return typeof n==="string"?n:void 0}}catch{return}return}function Xg(e){return pl(e,"coverImageId")}function ef(e){return pl(e,"ogImageId")}function Ji(e,t){return{...e,content:nt(e.content,"coverImageId",t)}}function Gi(e,t){return{...e,content:nt(e.content,"ogImageId",t)}}var Qi=ml();function tf(e,t){let r=Qi.parse(e),i=new Map;Pr(r,"definition",(o)=>{if(!i.has(o.identifier))i.set(o.identifier,o)});let n=new Set;return Pr(r,(o,s,a)=>{if(o.type!=="image"&&o.type!=="imageReference")return;let c=o.type==="image"?o:i.get(o.identifier);if(!c)return;let d=t(c.url);if(d===c.url)return;if(n.add(c.url),o.type==="image")o.url=d;else if(a&&s!==void 0)a.children[s]={type:"image",url:d,alt:o.alt,title:c.title}}),n.size>0?Qi.stringify(r):e}function rf(e){let t=[],r=Qi.parse(e);return Pr(r,"image",(i)=>{t.push({url:i.url,alt:i.alt??"",title:i.title??void 0})}),t}var ot=/^---\r?\n(?:[\s\S]*?\r?\n)?---[ \t]*(?:\r?\n|$)/;function Ki(e){return e.replace(ot,"")}var gl=400;function Cr(e,t,r){if(r===null)return!Object.hasOwn(e,t);return Object.hasOwn(e,t)&&Yi(e[t],r)}function Le(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 nf(e,t,r){if(r.has(t))return xr(e.content).frontmatter[t];return t==="visibility"?e.visibility:e.metadata[t]}function Sl(e,t,r){let i=Le(e.entityType,r),n=new Set(Object.keys(r.getAdapter(e.entityType).frontmatterSchema?.shape??{}).filter((s)=>!i.has(s))),o=Object.fromEntries(Object.entries(xr(t).frontmatter).filter(([s])=>!n.has(s)));return Object.keys(o).length>0?{...e,content:fr(o,e.content)}:e}function Rl(e,t,r){let{visibility:i,coverImageId:n,ogImageId:o,...s}=t,a=i===void 0?e.visibility:vl.parse(i),c=Object.hasOwn(t,"coverImageId")?Ji(e,typeof n==="string"?n:null):e,d=Object.hasOwn(t,"ogImageId")?Gi(c,typeof o==="string"?o:null):c,u={...e.metadata};for(let[f,h]of Object.entries(s))if(h===null)delete u[f];else u[f]=h;let p={...d,visibility:a,metadata:u};for(let[f,h]of Object.entries(s))if(h===null)delete p[f];else p[f]=h;let m=Le(e.entityType,r),g=!1;for(let[f,h]of Object.entries(t)){if(!m.has(f))continue;p.content=nt(p.content,f,h),g=!0}if(g)p.metadata=r.projectMetadata(e.entityType,p.content,u);if(r.getAdapter(e.entityType).metadataFromFrontmatter===!0){let f={...p.metadata};for(let h of["coverImageId","ogImageId"]){if(!Object.hasOwn(t,h))continue;let v=t[h];if(typeof v==="string")f[h]=v;else delete f[h]}p.metadata=f}return p}function of(e,t,r){let i=r.getAdapter(e.entityType),n=i.fromMarkdown(e.content),o=i.fromMarkdown(t),s={...e.metadata};for(let a of new Set([...Object.keys(n.metadata??{}),...Object.keys(o.metadata??{})])){let c=o.metadata?.[a];if(Yi(n.metadata?.[a],c))continue;if(c===void 0)delete s[a];else s[a]=c}return{...e,...o,id:e.id,entityType:e.entityType,created:e.created,updated:e.updated,contentHash:e.contentHash,content:t,metadata:s,visibility:yr(t)??e.visibility}}var sf=new Set(["visibility","coverImageId","ogImageId"]),af=l.record(l.string(),l.unknown());function cf(e,t,r,i){if(t.kind!=="fields")return;let n=t.fields,o=r.getEffectiveFrontmatterSchema(e.entityType);if(!o)return;let s=Le(e.entityType,r),a=Object.keys(n).filter((h)=>s.has(h)),c;try{if(c=Rl(e,n,r),a.length>0){let h=r.validateEntity(e.entityType,c),v=i.serializeEntity(h),y=xr(v).frontmatter,S=i.deserializeEntity(v,e.entityType).metadata??{};for(let R of a){let w=n[R];if(!Cr(y,R,w)||!Cr(S,R,w))return{success:!1,error:`The requested ${R} value would not survive frontmatter persistence.`}}}}catch(h){return{success:!1,error:C(h,"Invalid field update")}}let d=r.getAdapter(e.entityType).metadataFromFrontmatter===!0,u=Object.keys(n).filter((h)=>!s.has(h)&&(!sf.has(h)||d&&h!=="visibility")&&(h in o.shape));if(u.length===0)return;let p=r.getAdapter(e.entityType),m;try{c=r.validateEntity(e.entityType,c),m=p.extractMetadata(c)}catch{return}let g=[],f=[];for(let h of u){let v=n[h];if(Object.hasOwn(m,h)){if(!Cr(m,h,v))g.push(h)}else if(v!==null||!Object.hasOwn(e.metadata,h))f.push(h)}if(f.length>0){let h;try{h=p.parseFrontMatter(p.toMarkdown(c),af)}catch{if(g.length===0)return}if(h){for(let v of f)if(!Cr(h,v,n[v]))g.push(v)}}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 wl(e,t,r){let i=ot.exec(e.content)?.[0];if(i===void 0||!t.trim()||ot.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 lf(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."};let o=r.getAdapter(e),s=o.metadataFromFrontmatter===!0;if(s&&!ot.test(t.content))return;try{if(s)o.fromMarkdown(t.content);else o.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 df(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 uf(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 Pl(e,t,r){let i=Le(e.entityType,r);if(t.kind==="fields")return Object.entries(t.fields).map(([a,c])=>{let d=nf(e,a,i);if(!i.has(a))return`${a}: ${String(d??"(empty)")} \u2192 ${String(c)}`;let u=r.getEffectiveFrontmatterSchema(e.entityType)?.shape[a],p=u!==void 0&&l.safeParse(u,d).success,m=d===void 0?"(absent)":`${JSON.stringify(d)}${p?"":" (invalid existing value)"}`,g=c===null?"(removed)":JSON.stringify(c);return`${a}: ${m} \u2192 ${g}`}).join(`
81
+ `)}}function Rg(e){let t=e.title?` "${e.title}"`:"";return`Saved ${e.entityType}${t}.`}function wg(e){switch(e.kind){case"text":return{content:e.content};case"url":return{url:e.url};case"upload":{let t={kind:"upload",id:e.id};return{from:t,uploadRef:t,transform:e.transform}}case"prior-response":case"user-message":return{conversationMessageRef:e};case"entity":return{entityRef:{entityType:e.entityType,entityId:e.entityId}};case"uploads":throw Error("Several uploads are prepared one upload at a time")}}async function Pg(e,t,r){let i=await B(e.entityService,t.entityType,t.entityId,e.logger,"Source entity",A(r.userPermissionLevel));if(!i.ok)return O(i.error);let{entity:n}=i,o=_c(n.content);if(!o)return O(`Source entity ${n.entityType}/${n.id} has no text to use.`);let s=n.metadata.title;return{kind:"ok",value:{ref:{entityType:n.entityType,entityId:n.id},content:o,title:typeof s==="string"&&s.trim()?s:void 0,visibility:n.visibility}}}function Hc(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 cr(e.source,{messageId:e.resolvedMessageId,content:e.content,...e.resolvedUserSource&&{source:e.resolvedUserSource}})}if(e.source.kind==="prior-response"){let t=e.source.messageId??e.resolvedMessageId;return{kind:"prior-response",...t?{messageId:t}:{}}}if(e.source.kind==="entity"&&e.resolvedEntity)return{kind:"entity",...e.resolvedEntity};return e.source}async function Cg(e,t){let r=lr(t);return e.handler({upload:e.upload,...e.title&&{title:e.title},...e.visibility!==void 0?{visibility:e.visibility}:{}},r)}async function xg(e,t,r){let{entityService:i,entityRegistry:n}=e,o=te(t.title??`${t.entityType}-${Date.now()}`),s=n.getEffectiveFrontmatterSchema(t.entityType),a=t.content!==void 0&&Lc(s);if(t.fields&&!a)return{success:!1,error:`${t.entityType} has no frontmatter to set fields on; save the text without fields.`};try{let c={deduplicateId:!0,...r?{eventContext:r}:{}};return{success:!0,data:{entityId:(t.content&&a?await i.createEntityFromMarkdown({input:{entityType:t.entityType,id:o,markdown:t.fields?fr(t.fields,t.content):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 O(e){return{kind:"error",result:{success:!1,error:e}}}async function Ig(e,t,r){let{content:i,url:n,from:o,uploadRef:s,conversationMessageRef:a,entityRef:c,transform:d}=wg(t.source),u=c?await Pg(e,c,r):void 0;if(u?.kind==="error")return u;let p=a?await ar(e,a,r,{confirmed:t.confirmed===!0}):void 0;if(p&&!p.success)return{kind:"error",result:p};let m=p?.success===!0?p.content:u?.value.content??i;if(d==="extract-markdown"&&!s)return O('Transform "extract-markdown" requires an upload ref.');if(!m&&!n&&!o)return O('Provide `source` with kind "user-message", "text", "url", "prior-response", "upload", or "entity". Use system_generate for generated content or artifacts.');return{kind:"ok",value:{content:m,url:n,from:o,uploadRef:s,transform:d,resolvedMessageId:p?.success===!0?p.messageId:void 0,resolvedUserSource:p?.success===!0?p.source:void 0,entitySource:u?.value}}}async function Tg(e,t){if(!Wi(t.mediaType))return;let{content:r}=await e.runtimeUploads.scoped(Ae).read(t.id);return Zc(r).toString("utf8")}async function Eg(e,t,r){if(!await Uc(e,t.uploadRef,r.conversationId??r.channelId))return O("Upload ref is not accessible in this conversation or no longer exists.");let n,o;try{n=await e.runtimeUploads.scoped(Ae).readRecord(t.uploadRef.id),o=t.transform==="extract-markdown"?await Tg(e,{id:t.uploadRef.id,mediaType:n.mediaType}):void 0}catch{return O("Upload ref not found")}let s=Nc({filename:n.filename,markdown:o});if(t.transform!=="preserve")return{kind:"ok",value:{entityType:t.entityType,title:s,filename:n.filename,mediaType:n.mediaType,markdown:o,uploadPreserve:void 0}};let a=e.entityRegistry.getUploadSaveHandler(n.mediaType);if(!a){let c=Wi(n.mediaType)?' Keep a text upload as a note: entityType "note" with transform "extract-markdown".':"";return O(`No installed plugin can save uploads with media type "${n.mediaType}".${c}`)}return{kind:"ok",value:{entityType:a.entityType,title:s,filename:n.filename,mediaType:n.mediaType,markdown:o,uploadPreserve:{upload:t.uploadRef,filename:n.filename,mediaType:n.mediaType,handler:a.handler}}}}function kg(e,t,r){let i=t?yr(t):void 0;if(e!==void 0&&i!==void 0&&e!==i)return O(`Conflicting entity visibility: system_create requested "${e}" but the source frontmatter declares "${i}".`);let n=e??i,o=n??"public";if(!hr(r.userPermissionLevel,o))return O(`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}}function Ag(e,t,r){return pr(e,{entityType:t.entityType,candidateId:t.title?te(t.title):void 0,replace:t.replace===!0,copyHint:"create a new copy intentionally"},r)}function jg(e,t,r,i){let n=e.entityRegistry;if(r.transform!=="extract-markdown"||!i||n.getEntityTypeConfig(t).markdownImport)return{kind:"ok",value:r};if(i.markdown===void 0){let o=n.getAllEntityTypes().filter((a)=>n.getEntityTypeConfig(a).markdownImport),s=o.length>0?`Import it as a ${o.join(" or ")}, or keep`:"Keep";return O(`A ${t} takes the text of a text upload; ${i.filename} (${i.mediaType}) is not text. ${s} the file itself with transform "preserve".`)}return{kind:"ok",value:{content:i.markdown,from:void 0,transform:void 0}}}async function Dg(e,t,r){let i=e.entityRegistry.getCreateCheck(t.entityType);if(!i)return{kind:"ready"};try{return await i(t,lr(r))}catch(n){return{kind:"error",error:C(n,`Could not check the ${t.entityType}`)}}}function zg(e,t,r){return["Nothing was saved and no approval was requested.",`Ask the user this question in your reply, as written, without mentioning tools or fields: "${e.question}"`,r?`When they answer, call system_create again; to save the same files, pass source ${JSON.stringify(r.source)}, with the answer about this file in its item.`:`When they answer, call system_create again; to save the same text, pass source ${JSON.stringify(Oc(t))}.`,e.answerWith].join(" ")}function Og(e,t){let r={...Object.fromEntries(Object.entries(t.fields??{}).filter(([,n])=>n!==void 0)),...e.fields},i=e.title??t.title;return{...e,...i&&{title:i},...Object.keys(r).length>0&&{fields:r}}}async function Wc(e,t,r,i,n){if(!(t.source.kind==="upload"&&t.source.transform==="preserve")){let oe=we(e,t.entityType);if(oe)return{kind:"error",result:oe}}let s=Fi(r.conversationId??r.channelId,t.entityType),a=await Ig(e,t,r),c=a.kind==="error"&&s?i.resolveUnresolvable(s,t.source):void 0,d=c?{kind:"ok",value:{content:c.content,url:void 0,from:void 0,uploadRef:void 0,transform:void 0,resolvedMessageId:void 0,resolvedUserSource:void 0,entitySource:void 0}}:a;if(d.kind==="error")return d;let{url:u,uploadRef:p,resolvedMessageId:m,resolvedUserSource:g,entitySource:f}=d.value,h=c??(s?i.resolve(s,{source:t.source,content:d.value.content,resolvedMessageId:m}):{kind:"as-given"}),v=p?await Eg(e,{entityType:t.entityType,uploadRef:p,transform:d.value.transform},r):void 0;if(v?.kind==="error")return v;let y=v?.value.entityType??t.entityType,S=v?.value.uploadPreserve,R=jg(e,y,d.value,v?.value);if(R.kind==="error")return R;let{from:w,transform:x}=R.value,I=h.kind==="pinned"?h.content:R.value.content,M=we(e,y);if(M)return{kind:"error",result:M};let re=f&&f.visibility!=="public"?f.visibility:void 0,U=kg(t.visibility??re,I,r);if(U.kind==="error")return U;if(t.fields&&"visibility"in t.fields)return O("Set visibility with the typed `visibility` input, not in `fields`.");let _=t.fields&&Object.keys(t.fields).length>0?t.fields:void 0,st=Pe(t.title),at=(v&&Fc(st,v.value.filename)?void 0:st)??f?.title??v?.value.title,ct=t.replace===!0,ie={entityType:y,...at&&{title:at},...U.value!==void 0?{visibility:U.value}:{},...I&&{content:I},...u&&{url:u},...w&&{from:w},...x&&{transform:x},..._&&{fields:_},...ct&&{replace:ct}},lt=F(e,ie.entityType,"create",r);if(lt)return{kind:"error",result:lt};let $e=e.entityRegistry.getCreateInterceptor(ie.entityType);if(!ie.content&&!$e&&!S)return O('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 J=t.confirmed||S?void 0:await Dg(e,ie,r);if(J?.kind==="error")return O(J.error);if(J?.kind==="question"){let oe=h.kind==="pinned"?h.source:Hc({source:t.source,...m&&{resolvedMessageId:m},...g&&{resolvedUserSource:g},...f&&{resolvedEntity:f.ref},...I!==void 0?{content:I}:{}});if(s&&I!==void 0&&!p)i.pin(s,{source:oe,content:I,question:J.asks});return O(zg(J,oe,n))}let xe=J?.kind==="ready"?Og(ie,J):ie,ne=await Ag(e,xe,r);if(ne.kind==="error")return ne;return{kind:"ok",prepared:{createInput:xe,resolvedMessageId:m,resolvedUserSource:g,...h.kind==="pinned"&&{pinnedSource:h.source},...f&&{resolvedEntity:f.ref},interceptor:$e,eventContext:Me(r),...v&&{uploadFilename:v.value.filename},...p&&{uploadId:p.id},...ne.value&&{replacesFailed:ne.value},...S&&{uploadPreserve:S}}}}async function qc(e,t,r,i){let n=await Mg(e,t,r,i),{uploadId:o}=t;if(o===void 0||!("success"in n)||!n.success)return n;if(!X(n.data))return n;return{...n,data:{entityType:t.createInput.entityType,...n.data,uploadId:o}}}async function Mg(e,t,r,i){let{interceptor:n,eventContext:o,uploadPreserve:s,replacesFailed:a}=t,{createInput:c}=t,d=Fi(r.conversationId??r.channelId,c.entityType),u=await gr(e,a);if(u)return u;if(s)return Cg({upload:s.upload,...c.title&&{title:c.title},...c.visibility!==void 0?{visibility:c.visibility}:{},handler:s.handler},r);if(n){let m=await dr(e,n,c,r);if(m.kind==="error")return m.result;if(m.kind==="handled"){let{result:g}=m;if(d&&"success"in g&&g.success)i.clear(d);return g}c=m.createInput}if(!c.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.'};let p=await xg(e,c,o);if(d&&"success"in p&&p.success)i.clear(d);return p}async function Lg(e,t,r,i,n){let o={...t.fields,...r.fields},s=await Wc(e,{entityType:t.entityType,...r.title!==void 0?{title:r.title}:{},...t.visibility!==void 0?{visibility:t.visibility}:{},source:{kind:"upload",id:r.id,transform:r.transform},...Object.keys(o).length>0&&{fields:o},...t.replace!==void 0?{replace:t.replace}:{},...t.confirmed&&{confirmed:t.confirmed}},i,n,{source:t.source});if(s.kind==="error")return s;let{prepared:a}=s;return{kind:"ok",value:{filename:a.uploadFilename??r.id,entityType:a.createInput.entityType,title:a.createInput.title??a.uploadFilename??"",...a.createInput.fields&&{fields:a.createInput.fields},...a.replacesFailed&&{replacesFailed:`${a.replacesFailed.entityType} "${a.replacesFailed.id}"`},save:()=>qc(e,a,i,n)}}}function Jc(e){let t=ee({label:"create",requestNoun:"creation"}),r=new Zi;return{...q("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 such as a team note, restricted for private/admin-only content, and omit it for public content; keep visibility separate from exact source text. Public callers may write only public content, Trusted callers public or shared, and Admin callers all three. If the user only says 'not public' without saying team/shared or private/admin-only, ask which scope they mean. 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; that content is sufficient even when 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'), so never ask the user to paste it again. 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. To save a pasted document that opens with --- frontmatter, use boundaryMode frontmatter without startAfter or endBefore: the server selects it from its opening fence, and the fences are content, never boundaries. 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, and then use it even though the file text also appears in the message; only a pasted uploaded-file transcript (for example, User uploaded a file \"name.md\": ...) with no listed upload ref is saved with source.kind user-message boundaries.",ir,async(n,o)=>{await e.entityRegistry.ensureGroupingsCurrent(n.entityType);let s=[n.fields,...n.source.kind==="uploads"?n.source.items.map((f)=>f.fields):[]].map((f)=>or(e.entityRegistry,n.entityType,f,{on:"create",allow:["visibility"]})).find((f)=>f!==void 0);if(s)return{success:!1,error:s};if(n.source.kind==="uploads")return Bc({input:{...n,source:n.source},gate:t,prepare:(f)=>Lg(e,n,f,o,r)});let a=await Wc(e,n,o,r);if(a.kind==="error")return a.result;let{createInput:c}=a.prepared,{resolvedMessageId:d,resolvedUserSource:u,pinnedSource:p,resolvedEntity:m,uploadPreserve:g}=a.prepared;if(n.confirmed){let f=t.validateConfirmed(n.confirmationToken,n);if(f)return f}else{let f=g?bg({...c.title&&{title:c.title},filename:g.filename,mediaType:g.mediaType,entityType:c.entityType,visibility:c.visibility}):Sg(c),h=a.prepared.replacesFailed?{...f,preview:`${f.preview}
82
+ ${mr(a.prepared.replacesFailed)}`}:f,v=p??Hc({source:n.source,...d&&{resolvedMessageId:d},...u&&{resolvedUserSource:u},...m&&{resolvedEntity:m},...c.content!==void 0?{content:c.content}:{}}),y=t.buildArgs((S)=>({entityType:c.entityType,...c.title&&{title:c.title},...c.visibility!==void 0?{visibility:c.visibility}:{},source:v,...c.fields&&{fields:c.fields},...c.replace&&{replace:c.replace},confirmed:!0,confirmationToken:S}));return{needsConfirmation:!0,toolName:"system_create",summary:h.summary,completionSummary:Rg(c),preview:h.preview,args:y}}return qc(e,a.prepared,o,r)},{visibility:"trusted",sideEffects:"writes"}),modelInput:Ec(e.entityRegistry)}}function Ug(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(`
83
+ `)}}async function $g(e,t,r){if(!t)return{kind:"ok",sourceAttachment:void 0};let i=await B(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 Bg(e,t,r){if(!t)return{kind:"ok",source:void 0};let i=await B(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 _g(e,t,r){if(!t)return{kind:"ok",target:void 0};let i=await B(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 Zg(e,t,r,i,n){let{entityService:o,jobs:s}=e,a=qi(te(t.title??r),100);if(!a)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 c=t.title??a,d=Gc(e.entityRegistry,{entityType:t.entityType,id:a,title:c});if(!d)return{success:!1,error:`Entity type '${t.entityType}' does not support queued generation. Provide an exact source to system_create instead.`};let u;try{u=(await o.createEntity({entity:d,options:{deduplicateId:!0,...i?{eventContext:i}:{}}})).entityId}catch(g){return{success:!1,error:C(g,"Failed to persist generation stub")}}let p={entityId:u,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}},m=e.entityRegistry.getGenerationEnqueuer(t.entityType);try{let g=m?await m(p,n):await s.enqueue({type:`${t.entityType}:generation`,data:p,toolContext:n});return{success:!0,data:{entityId:u,status:"generating",jobId:g}}}catch(g){return await o.deleteEntity({entityType:t.entityType,id:u}).catch((f)=>{e.logger.warn("Failed to remove unqueued generation stub",{entityType:t.entityType,entityId:u,error:f})}),{success:!1,error:C(g,"Failed to queue generation job")}}}async function Fg(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 s=t.kind==="prompt-from-source"?await Bg(e,t.source,r):{kind:"ok",source:void 0};if(s.kind==="error")return s;let a=Pe(t.title);i={entityType:t.entityType,...a?{title:a}:{},prompt:t.prompt,...s.source?.entityType&&{sourceEntityType:s.source.entityType},...s.source?.entityId&&{sourceEntityId:s.source.entityId,sourceEntityIds:[s.source.entityId]}}}else if(t.kind==="standalone-image"){let s=Pe(t.title);i={entityType:"image",...s?{title:s}:{},prompt:t.prompt}}else if(t.kind==="cover-image"){let s=await _g(e,t.target,r);if(s.kind==="error"){let c=s.result;return{kind:"error",result:"success"in c&&c.success===!1?{...c,code:"target-not-found"}:c}}let a=Pe(t.title);i={entityType:"image",...a?{title:a}:{},prompt:t.prompt,...s.target?.entityType&&{targetEntityType:s.target.entityType},...s.target?.entityId&&{targetEntityId:s.target.entityId}}}else{let s=await $g(e,{sourceEntityType:t.source.entityType,sourceEntityId:t.source.entityId,attachmentType:t.attachmentType},r);if(s.kind==="error")return s;n=s.sourceAttachment;let a=s.metadata;if(!a||!n)return{kind:"error",result:{success:!1,error:"Attachment generation requires provider metadata.",code:"provider-missing-metadata"}};let c=Pe(t.title);i={entityType:a.outputEntityType,...c?{title:c}:{},from:{kind:"entity-attachment",...n},...o&&{replace:o},...a.targetField&&{targetEntityType:n.sourceEntityType,targetEntityId:n.sourceEntityId}}}return{kind:"ok",createInput:i,sourceAttachment:n}}async function Ng(e,t,r){let i=t.operation,n=A(r.userPermissionLevel),o=await Fg(e,i,n);if(o.kind==="error")return o;let{createInput:s,sourceAttachment:a}=o,c=i.kind==="attachment"&&i.replace===!0,d=we(e,s.entityType);if(d)return{kind:"error",result:d};let u=F(e,s.entityType,"create",r);if(u)return{kind:"error",result:u};let p=e.entityRegistry.getCreateInterceptor(s.entityType);if(!s.prompt&&!s.from)return{kind:"error",result:{success:!1,error:"Provide a generation source."}};if(s.from&&!p)return{kind:"error",result:{success:!1,error:`Entity type '${s.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"}};let m=i.kind==="prompt"||i.kind==="prompt-from-source",g=p&&!m?void 0:await pr(e,{entityType:s.entityType,candidateId:s.prompt?qi(te(s.title??s.prompt),100):s.title?te(s.title):void 0,replace:c===!0,copyHint:"generate a new copy intentionally"},r);if(g?.kind==="error")return g;return{kind:"ok",prepared:{createInput:s,operation:Hg(i,s,a),sourceAttachment:a,interceptor:p,eventContext:Me(r),...g?.value&&{replacesFailed:g.value}}}}function Hg(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 Qc(e){let t=ee({label:"generate",requestNoun:"generation"});return q("generate","Generate durable content or artifacts. Requires confirmation: calling this tool without confirmed is how you request it, so when the user asks to create, write, draft, or generate new durable content without supplying final exact content, call it instead of drafting the content in chat, asking for separate prose approval, or saying 'I can generate it if you want' or 'I need to queue it first'. Critical: broad or underspecified topical generation uses operation.kind prompt with no source field, also in the same turn after an optional search finds no source; preserve the user's wording as the prompt and do not stop to ask what details to highlight. Critical: to generate from an existing source such as 'my latest blog post', resolve it with read/search/list tools unless the user gives an exact entity id in quotes, then call operation.kind prompt-from-source right away, for example { kind: 'prompt-from-source', entityType: 'newsletter', source: { entityType: 'post', entityId: '...' }, prompt: '...' }. For the latest published/blog source, use system_list on that type (blog posts: entityType post) and choose the newest candidate by publishedAt, not updated/created or semantic search order; do not stop with prose like 'I found it and can generate it' or 'if that is the one you mean.' Never invent source IDs, use brain-character/profile, uploads, filenames, guessed ids, or placeholders as source refs. Turning an existing entity into another type ('turn my note X into a post') keeps its text and is not generation: call system_create with source.kind entity, also after a search resolves it. Use system_create as well for saving/importing existing text, URLs, uploads, prior assistant responses, or raw uploaded files. Critical: for a request to generate a post/social-post/newsletter/etc. with a cover image, call only the prompt generation first; call cover-image only once the target entity exists after confirmation, never guess its future id, and never use standalone-image as a substitute for a requested cover. When a cover-image request names the target's exact id in quotes or a search/get resolves a clear target, call cover-image in the same turn; do not stop after saying you found the entity. Use attachment for source-derived artifacts: attachmentType og-image for OG/social preview renders (the provider updates ogImageId), carousel for deck carousel PDFs, printable for post/project PDFs. Call it immediately for save/render requests, with replace:true for regenerate/replace/refresh, instead of saying you can queue it later. To attach a generated artifact to another entity, generate the artifact first in the same turn \u2014 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` \u2014 and update the target only after the real artifact ID exists.",Sc,async(r,i)=>{let n=await Ng(e,r,i);if(n.kind==="error")return n.result;let{createInput:o}=n.prepared,{operation:s,interceptor:a,eventContext:c,replacesFailed:d}=n.prepared;if(r.confirmed){let p=t.validateConfirmed(r.confirmationToken,r);if(p)return p}else{let p=Ug(o),m=d?{...p,preview:`${p.preview}
84
+ ${mr(d)}`}:p,g=t.buildArgs((f)=>({operation:s,confirmed:!0,confirmationToken:f}));return{needsConfirmation:!0,toolName:"system_generate",summary:m.summary,preview:m.preview,args:g}}let u=await gr(e,d);if(u)return u;if(a){let p=await dr(e,a,o,i);if(p.kind==="handled"||p.kind==="error")return p.result;o=p.createInput}if(!o.prompt)return{success:!1,error:"Attachment generation is supported only for entity types that explicitly handle source-derived artifacts."};return Zg(e,o,o.prompt,c,i)},{visibility:"trusted",sideEffects:"writes"})}function Kc(e){let{entityService:t,entityRegistry:r,logger:i}=e,n=ee({label:"delete",requestNoun:"deletion"});return q("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. For an entity the user names, call this tool directly without searching for or reading it first. Protected identity/profile records such as brain-character and anchor-profile cannot be deleted; update them instead.",Rc,async(o,s)=>{if((s.userPermissionLevel??"public")==="public")return{success:!1,error:"Changing content requires higher permission; current permission is Public."};let a=F(e,o.entityType,"delete",s);if(a)return a;let c=we(e,o.entityType);if(c)return c;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 d=A(s.userPermissionLevel),u=await B(t,o.entityType,o.id,i,void 0,d);if(!u.ok)return{success:!1,error:u.error};let{entity:p}=u;if(o.confirmed){let f=n.validateConfirmed(o.confirmationToken,o);if(f)return f;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 m=ur(p),g=n.buildArgs((f)=>({...o,id:p.id,confirmed:!0,confirmationToken:f}));return{needsConfirmation:!0,toolName:"system_delete",summary:`Delete "${m}"?`,preview:p.content.slice(0,200),args:g}},{visibility:"admin",sideEffects:"writes"})}function Vc(e,t){let r=t.map(({oldText:o,newText:s},a)=>{let c=e.indexOf(o);if(!o||c<0)throw Error(`Edit ${a+1}: oldText was not found. Fetch the entity again and provide exact text.`);if(e.indexOf(o,c+1)!==-1)throw Error(`Edit ${a+1}: oldText is ambiguous. Include more surrounding text to match exactly once.`);return{start:c,end:c+o.length,newText:s}}).sort((o,s)=>o.start-s.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 Xi}from"util";class vr{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),s=this.removeEmpty(this.tokenize(n,r)),a=this.removeEmpty(this.tokenize(o,r));return this.diffWithOptionsObj(s,a,r,i)}diffWithOptionsObj(e,t,r,i){var n;let o=(y)=>{if(y=this.postProcess(y,r),i){setTimeout(function(){i(y)},0);return}else return y},s=t.length,a=e.length,c=1,d=s+a;if(r.maxEditLength!=null)d=Math.min(d,r.maxEditLength);let u=(n=r.timeout)!==null&&n!==void 0?n:1/0,p=Date.now()+u,m=[{oldPos:-1,lastComponent:void 0}],g=this.extractCommon(m[0],t,e,0,r);if(m[0].oldPos+1>=a&&g+1>=s)return o(this.buildValues(m[0].lastComponent,t,e));let f=-1/0,h=1/0,v=()=>{for(let y=Math.max(f,-c);y<=Math.min(h,c);y+=2){let S,R=m[y-1],w=m[y+1];if(R)m[y-1]=void 0;let x=!1;if(w){let M=w.oldPos-y;x=w&&0<=M&&M<s}let I=R&&R.oldPos+1<a;if(!x&&!I){m[y]=void 0;continue}if(!I||x&&R.oldPos<w.oldPos)S=this.addToPath(w,!0,!1,0,r);else S=this.addToPath(R,!1,!0,1,r);if(g=this.extractCommon(S,t,e,y,r),S.oldPos+1>=a&&g+1>=s)return o(this.buildValues(S.lastComponent,t,e))||!0;else{if(m[y]=S,S.oldPos+1>=a)h=Math.min(h,y-1);if(g+1>=s)f=Math.max(f,y+1)}}c++};if(i)(function y(){setTimeout(function(){if(c>d||Date.now()>p)return i(void 0);if(!v())y()},0)})();else while(c<=d&&Date.now()<=p){let y=v();if(y)return y}}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,s=r.length,a=e.oldPos,c=a-i,d=0;while(c+1<o&&a+1<s&&this.equals(r[a+1],t[c+1],n))if(c++,a++,d++,n.oneChangePerToken)e.lastComponent={count:1,previousComponent:e.lastComponent,added:!1,removed:!1};if(d&&!n.oneChangePerToken)e.lastComponent={count:d,previousComponent:e.lastComponent,added:!1,removed:!1};return e.oldPos=a,c}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,s=0,a=0,c=0;for(;s<o;s++){let d=i[s];if(!d.removed){if(!d.added&&this.useLongestToken){let u=t.slice(a,a+d.count);u=u.map(function(p,m){let g=r[c+m];return g.length>p.length?g:p}),d.value=this.join(u)}else d.value=this.join(t.slice(a,a+d.count));if(a+=d.count,!d.added)c+=d.count}else d.value=this.join(r.slice(c,c+d.count)),c+=d.count}return i}}class Yc extends vr{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}}var Xc=new Yc;function br(e,t,r){return Xc.diff(e,t,r)}var Sr=l.enum(["png","jpg","jpeg","webp","gif","svg"]),tl=l.enum(["pending","draft","failed"]),rl=l.object({title:l.string().optional(),alt:l.string().optional(),format:Sr.meta({studioWidget:"provenance"}),width:l.number().meta({studioWidget:"provenance"}),height:l.number().meta({studioWidget:"provenance"}),status:tl.optional().meta({studioWidget:"provenance"}),processingJobId:l.string().optional().meta({studioWidget:"hidden"}),processingError:l.string().optional().meta({studioWidget:"provenance"}),sourceUrl:l.url().optional().meta({studioWidget:"provenance"}),sourceEntityType:l.string().optional().meta({studioWidget:"provenance"}),sourceEntityId:l.string().optional().meta({studioWidget:"provenance"}),sourceUploadId:l.string().optional().meta({studioWidget:"provenance"}),sourceFilename:l.string().optional().meta({studioWidget:"provenance"}),sourceMediaType:l.string().optional().meta({studioWidget:"provenance"}),attachmentType:l.string().optional().meta({studioWidget:"provenance"}),dedupKey:l.string().optional().meta({studioWidget:"hidden"})}),il=el.extend({entityType:l.literal("image"),metadata:rl}),Wg=l.object({url:l.string(),alt:l.string(),title:l.string(),width:l.number(),height:l.number()});function nl(e){return/^https?:\/\//i.test(e)}async function ol(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 sl(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 Rr(e){let t=sl(e);if(!t)throw Error("Invalid image data URL");return t}function qg(e,t){return`data:image/${t==="jpg"?"jpeg":t};base64,${e}`}var Jg={png:"iVBORw",jpg:"/9j/",gif:"R0lGOD",webp:"UklGR"};function Ji(e){for(let[t,r]of St(Jg))if(e.startsWith(r))return t;return null}function al(e){let t=e.toLowerCase(),r=t==="svg+xml"?"svg":t,i=Sr.safeParse(r);return i.success?i.data:null}async function Gg(e){return ol(e,"image/")}function wr(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,s=(r|i<<8)&16383,a=(n|o<<8)&16383;return{width:s,height:a}}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 cl(e){let t=al(e);if(!t)throw Error(`Unsupported image format: ${e}`);return t}function Qg(e){let{format:t,base64:r}=Rr(e),i=wr(r);return{format:cl(t),width:i?.width??0,height:i?.height??0}}function Kg(e){let{dataUrl:t,title:r,alt:i}=e,{format:n,base64:o}=Rr(t),s=wr(o),c=Ji(o)??cl(n);return{entityType:"image",content:t,metadata:{title:r,alt:i??r,format:c,width:s?.width??0,height:s?.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}}}}function MI(e){return dl(e,{skipInvalid:!0,noRefs:!0,sortKeys:!0})}function ul(e){return ll(e)}var Vg=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,Yg=l.record(l.string(),l.unknown());function pl(e,t){let r=Vg.exec(e.content);if(!r?.[1])return;try{let i=Yg.safeParse(ul(r[1]));if(i.success){let n=i.data[t];return typeof n==="string"?n:void 0}}catch{return}return}function Xg(e){return pl(e,"coverImageId")}function ef(e){return pl(e,"ogImageId")}function Gi(e,t){return{...e,content:nt(e.content,"coverImageId",t)}}function Qi(e,t){return{...e,content:nt(e.content,"ogImageId",t)}}var Ki=ml();function tf(e,t){let r=Ki.parse(e),i=new Map;Pr(r,"definition",(o)=>{if(!i.has(o.identifier))i.set(o.identifier,o)});let n=new Set;return Pr(r,(o,s,a)=>{if(o.type!=="image"&&o.type!=="imageReference")return;let c=o.type==="image"?o:i.get(o.identifier);if(!c)return;let d=t(c.url);if(d===c.url)return;if(n.add(c.url),o.type==="image")o.url=d;else if(a&&s!==void 0)a.children[s]={type:"image",url:d,alt:o.alt,title:c.title}}),n.size>0?Ki.stringify(r):e}function rf(e){let t=[],r=Ki.parse(e);return Pr(r,"image",(i)=>{t.push({url:i.url,alt:i.alt??"",title:i.title??void 0})}),t}var ot=/^---\r?\n(?:[\s\S]*?\r?\n)?---[ \t]*(?:\r?\n|$)/;function Vi(e){return e.replace(ot,"")}var gl=400;function Cr(e,t,r){if(r===null)return!Object.hasOwn(e,t);return Object.hasOwn(e,t)&&Xi(e[t],r)}function Le(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 nf(e,t,r){if(r.has(t))return xr(e.content).frontmatter[t];return t==="visibility"?e.visibility:e.metadata[t]}function Sl(e,t,r){let i=Le(e.entityType,r),n=new Set(Object.keys(r.getAdapter(e.entityType).frontmatterSchema?.shape??{}).filter((s)=>!i.has(s))),o=Object.fromEntries(Object.entries(xr(t).frontmatter).filter(([s])=>!n.has(s)));return Object.keys(o).length>0?{...e,content:fr(o,e.content)}:e}function Rl(e,t,r){let{visibility:i,coverImageId:n,ogImageId:o,...s}=t,a=i===void 0?e.visibility:vl.parse(i),c=Object.hasOwn(t,"coverImageId")?Gi(e,typeof n==="string"?n:null):e,d=Object.hasOwn(t,"ogImageId")?Qi(c,typeof o==="string"?o:null):c,u={...e.metadata};for(let[f,h]of Object.entries(s))if(h===null)delete u[f];else u[f]=h;let p={...d,visibility:a,metadata:u};for(let[f,h]of Object.entries(s))if(h===null)delete p[f];else p[f]=h;let m=Le(e.entityType,r),g=!1;for(let[f,h]of Object.entries(t)){if(!m.has(f))continue;p.content=nt(p.content,f,h),g=!0}if(g)p.metadata=r.projectMetadata(e.entityType,p.content,u);if(r.getAdapter(e.entityType).metadataFromFrontmatter===!0){let f={...p.metadata};for(let h of["coverImageId","ogImageId"]){if(!Object.hasOwn(t,h))continue;let v=t[h];if(typeof v==="string")f[h]=v;else delete f[h]}p.metadata=f}return p}function of(e,t,r){let i=r.getAdapter(e.entityType),n=i.fromMarkdown(e.content),o=i.fromMarkdown(t),s={...e.metadata};for(let a of new Set([...Object.keys(n.metadata??{}),...Object.keys(o.metadata??{})])){let c=o.metadata?.[a];if(Xi(n.metadata?.[a],c))continue;if(c===void 0)delete s[a];else s[a]=c}return{...e,...o,id:e.id,entityType:e.entityType,created:e.created,updated:e.updated,contentHash:e.contentHash,content:t,metadata:s,visibility:yr(t)??e.visibility}}var sf=new Set(["visibility","coverImageId","ogImageId"]),af=l.record(l.string(),l.unknown());function cf(e,t,r,i){if(t.kind!=="fields")return;let n=t.fields,o=r.getEffectiveFrontmatterSchema(e.entityType);if(!o)return;let s=Le(e.entityType,r),a=Object.keys(n).filter((h)=>s.has(h)),c;try{if(c=Rl(e,n,r),a.length>0){let h=r.validateEntity(e.entityType,c),v=i.serializeEntity(h),y=xr(v).frontmatter,S=i.deserializeEntity(v,e.entityType).metadata??{};for(let R of a){let w=n[R];if(!Cr(y,R,w)||!Cr(S,R,w))return{success:!1,error:`The requested ${R} value would not survive frontmatter persistence.`}}}}catch(h){return{success:!1,error:C(h,"Invalid field update")}}let d=r.getAdapter(e.entityType).metadataFromFrontmatter===!0,u=Object.keys(n).filter((h)=>!s.has(h)&&(!sf.has(h)||d&&h!=="visibility")&&(h in o.shape));if(u.length===0)return;let p=r.getAdapter(e.entityType),m;try{c=r.validateEntity(e.entityType,c),m=p.extractMetadata(c)}catch{return}let g=[],f=[];for(let h of u){let v=n[h];if(Object.hasOwn(m,h)){if(!Cr(m,h,v))g.push(h)}else if(v!==null||!Object.hasOwn(e.metadata,h))f.push(h)}if(f.length>0){let h;try{h=p.parseFrontMatter(p.toMarkdown(c),af)}catch{if(g.length===0)return}if(h){for(let v of f)if(!Cr(h,v,n[v]))g.push(v)}}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 wl(e,t,r){let i=ot.exec(e.content)?.[0];if(i===void 0||!t.trim()||ot.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 lf(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."};let o=r.getAdapter(e),s=o.metadataFromFrontmatter===!0;if(s&&!ot.test(t.content))return;try{if(s)o.fromMarkdown(t.content);else o.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 df(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 uf(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 Pl(e,t,r){let i=Le(e.entityType,r);if(t.kind==="fields")return Object.entries(t.fields).map(([a,c])=>{let d=nf(e,a,i);if(!i.has(a))return`${a}: ${String(d??"(empty)")} \u2192 ${String(c)}`;let u=r.getEffectiveFrontmatterSchema(e.entityType)?.shape[a],p=u!==void 0&&l.safeParse(u,d).success,m=d===void 0?"(absent)":`${JSON.stringify(d)}${p?"":" (invalid existing value)"}`,g=c===null?"(removed)":JSON.stringify(c);return`${a}: ${m} \u2192 ${g}`}).join(`
85
85
  `);let n=e.content.split(`
86
86
  `),o=t.content.split(`
87
87
  `),s=br(n,o,{maxEditLength:gl});if(!s)return`Full content replacement (line diff omitted: more than ${gl} changed lines).`;return s.filter((a)=>a.added||a.removed).flatMap((a)=>a.value.map((c)=>`${a.added?"+":"-"} ${c}`)).join(`
88
- `)}function Cl(e,t,r,i){return cf(e,t,r,i)??lf(e.entityType,t,r)??df(e.entityType,t,r)}function xl(e,t,r){return bl(e.entityType,e.metadata.status,uf(e,t,r),r)==="non-publish"?"update":"publish"}function Il(e,t,r){return t.kind==="content"?of(e,t.content,r):Rl(e,t.fields,r)}var fl=5,hl=160;function pf(e){return e.length>hl?`${e.slice(0,hl)}\u2026`:e}function mf(e){if(e===void 0)return"(removed)";return typeof e==="string"?e:JSON.stringify(e)}function yl(e){return e.trim().length>0}function Vi(e,t){if(t.length===0)return;let r=t.length-fl;return[e,...t.slice(0,fl).map((i)=>`> ${pf(i)}`),...r>0?[`\u2026 and ${r} more changed lines`]:[]].join(`
89
- `)}function gf(e,t){return[...new Set([...Object.keys(e.metadata),...Object.keys(t.metadata)])].filter((r)=>!Yi(e.metadata[r],t.metadata[r])).map((r)=>`${r}: ${mf(t.metadata[r])}`)}function Tl(e,t){if(t.content===e.content)return Vi("Stored now:",gf(e,t));let r=br(e.content.split(`
88
+ `)}function Cl(e,t,r,i){return cf(e,t,r,i)??lf(e.entityType,t,r)??df(e.entityType,t,r)}function xl(e,t,r){return bl(e.entityType,e.metadata.status,uf(e,t,r),r)==="non-publish"?"update":"publish"}function Il(e,t,r){return t.kind==="content"?of(e,t.content,r):Rl(e,t.fields,r)}var fl=5,hl=160;function pf(e){return e.length>hl?`${e.slice(0,hl)}\u2026`:e}function mf(e){if(e===void 0)return"(removed)";return typeof e==="string"?e:JSON.stringify(e)}function yl(e){return e.trim().length>0}function Yi(e,t){if(t.length===0)return;let r=t.length-fl;return[e,...t.slice(0,fl).map((i)=>`> ${pf(i)}`),...r>0?[`\u2026 and ${r} more changed lines`]:[]].join(`
89
+ `)}function gf(e,t){return[...new Set([...Object.keys(e.metadata),...Object.keys(t.metadata)])].filter((r)=>!Xi(e.metadata[r],t.metadata[r])).map((r)=>`${r}: ${mf(t.metadata[r])}`)}function Tl(e,t){if(t.content===e.content)return Yi("Stored now:",gf(e,t));let r=br(e.content.split(`
90
90
  `),t.content.split(`
91
- `)),i=r.filter((n)=>n.added).flatMap((n)=>n.value).filter(yl);if(i.length>0)return Vi("Stored now:",i);return Vi("No longer stored:",r.filter((n)=>n.removed).flatMap((n)=>n.value).filter(yl))}function Ce(e){return{success:!1,error:e}}async function ff(e,t,r,i){if(t.confirmed&&t.contentHash&&r.contentHash!==t.contentHash)return Ce("Entity was modified since you reviewed the changes. Please try again.");let n=t.operation;if(n.fields!==void 0)return{operation:{kind:"fields",fields:n.fields}};if(n.edits!==void 0)return{operation:{kind:"content",content:Vc(r.content,n.edits)}};if(n.content!==void 0)return El(e,r,n.content);if(n.source===void 0)return Ce(rt);let o=await ar(e,n.source,i,{confirmed:t.confirmed===!0});if(!o.success)return o;return El(e,r,o.content,cr(n.source,o))}function El(e,t,r,i){let n=wl(t,r,e.entityRegistry);if(typeof n!=="string")return n;return{operation:{kind:"content",content:n},...i?{source:i}:{}}}function kl(e){let{entityService:t,logger:r,entityRegistry:i}=e,n=ee({label:"update",requestNoun:"the update"}),o=async(d,u,p,m)=>{let g=n.validateConfirmed(d.confirmationToken,d);if(g)return g;let f=Il(u,p,i);if(f.visibility!==u.visibility&&!hr(m.userPermissionLevel,f.visibility))return Ce(`Cannot set entity visibility to "${f.visibility}" \u2014 caller permission "${m.userPermissionLevel??"public"}" is not allowed to write at that level.`);try{let y=Me(m);if((await t.updateEntity({entity:f,options:{expectedContentHash:u.contentHash,...y?{eventContext:y}:{}}})).skipReason==="content-conflict")return Ce("Entity was modified before the update could be saved. Please request and confirm the update again.")}catch(y){return Ce(C(y,"Failed to update entity"))}let h=await t.getEntity({entityType:u.entityType,id:u.id,visibilityScope:A(m.userPermissionLevel)}),v=h?Tl(u,h):void 0;return{success:!0,data:{updated:u.id},...v!==void 0&&{completionDetail:v}}},s=async(d,u,p)=>{if(u.kind!=="fields")return d;if(i.getAdapter(d.entityType).metadataFromFrontmatter!==!0)return d;let m=Le(d.entityType,i);if(!Object.keys(u.fields).some((f)=>m.has(f)))return d;let g=await t.getEntity({entityType:d.entityType,id:d.id,visibilityScope:p,source:!0});return g?Sl(d,g.content,i):d},a=(d,u,{operation:p,source:m})=>({needsConfirmation:!0,toolName:"system_update",summary:`Update "${ur(u)}"?`,completionSummary:`Updated ${Oc(u.entityType)}.`,preview:Pl(u,p,i),args:n.buildArgs((g)=>({...d,...m?{operation:{source:m}}:{},id:u.id,confirmed:!0,confirmationToken:g,contentHash:u.contentHash}))});return{...q("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 a fields change to an entity the user names, call this tool directly without reading the entity first. For small content changes, fetch the entity (an upload ref marked saved already holds its text, so edit that note without fetching it) and use the edits operation with exact oldText/newText pairs, several non-overlapping edits in one call, instead of regenerating the whole document. Never replace unchanged content with placeholders or ellipses. 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, even when ogImageId already points at that image; do not stop after lookup. Cover images use coverImageId and OG/social previews ogImageId; they are not interchangeable. To generate a new cover, use system_generate cover-image. For explicit publish requests, use the publishing tool if available instead of changing status here; a follow-up like 'publish it' targets the entity just read or updated.",nr,async(d,u)=>{await i.ensureGroupingsCurrent(d.entityType);let p=or(i,d.entityType,d.operation.fields,{on:"update",allow:["visibility","coverImageId","ogImageId"]});if(p)return Ce(p);let m=await B(t,d.entityType,d.id,r,void 0,A(u.userPermissionLevel));if(!m.ok)return Ce(m.error);let g=await ff(e,d,m.entity,u);if("success"in g)return g;let{operation:f}=g,h=await s(m.entity,f,A(u.userPermissionLevel)),v=Cl(h,f,i,t);if(v)return v;let y=F(e,d.entityType,xl(h,f,i),u);if(y)return y;return d.confirmed?o(d,h,f,u):a(d,h,g)},{visibility:"trusted",sideEffects:"writes"}),modelInput:Ec(e.entityRegistry)}}function Al(e){return[Jc(e),Qc(e),Kc(e),kl(e)]}function Ir(e){if(e.interfaceType!==jl)return;if(e.userPermissionLevel!=="public"||e.isAnchor)throw Error("Guest execution denied")}var Ml=3000,hf={limit:10,excerptChars:Ml},yf={limit:5,maxLimit:5,excerptChars:800};function Ll(e){return e!==void 0&&ve(e)==="local"?yf:hf}var Dl=`
91
+ `)),i=r.filter((n)=>n.added).flatMap((n)=>n.value).filter(yl);if(i.length>0)return Yi("Stored now:",i);return Yi("No longer stored:",r.filter((n)=>n.removed).flatMap((n)=>n.value).filter(yl))}function Ce(e){return{success:!1,error:e}}async function ff(e,t,r,i){if(t.confirmed&&t.contentHash&&r.contentHash!==t.contentHash)return Ce("Entity was modified since you reviewed the changes. Please try again.");let n=t.operation;if(n.fields!==void 0)return{operation:{kind:"fields",fields:n.fields}};if(n.edits!==void 0)return{operation:{kind:"content",content:Vc(r.content,n.edits)}};if(n.content!==void 0)return El(e,r,n.content);if(n.source===void 0)return Ce(rt);let o=await ar(e,n.source,i,{confirmed:t.confirmed===!0});if(!o.success)return o;return El(e,r,o.content,cr(n.source,o))}function El(e,t,r,i){let n=wl(t,r,e.entityRegistry);if(typeof n!=="string")return n;return{operation:{kind:"content",content:n},...i?{source:i}:{}}}function kl(e){let{entityService:t,logger:r,entityRegistry:i}=e,n=ee({label:"update",requestNoun:"the update"}),o=async(d,u,p,m)=>{let g=n.validateConfirmed(d.confirmationToken,d);if(g)return g;let f=Il(u,p,i);if(f.visibility!==u.visibility&&!hr(m.userPermissionLevel,f.visibility))return Ce(`Cannot set entity visibility to "${f.visibility}" \u2014 caller permission "${m.userPermissionLevel??"public"}" is not allowed to write at that level.`);try{let y=Me(m);if((await t.updateEntity({entity:f,options:{expectedContentHash:u.contentHash,...y?{eventContext:y}:{}}})).skipReason==="content-conflict")return Ce("Entity was modified before the update could be saved. Please request and confirm the update again.")}catch(y){return Ce(C(y,"Failed to update entity"))}let h=await t.getEntity({entityType:u.entityType,id:u.id,visibilityScope:A(m.userPermissionLevel)}),v=h?Tl(u,h):void 0;return{success:!0,data:{updated:u.id},...v!==void 0&&{completionDetail:v}}},s=async(d,u,p)=>{if(u.kind!=="fields")return d;if(i.getAdapter(d.entityType).metadataFromFrontmatter!==!0)return d;let m=Le(d.entityType,i);if(!Object.keys(u.fields).some((f)=>m.has(f)))return d;let g=await t.getEntity({entityType:d.entityType,id:d.id,visibilityScope:p,source:!0});return g?Sl(d,g.content,i):d},a=(d,u,{operation:p,source:m})=>({needsConfirmation:!0,toolName:"system_update",summary:`Update "${ur(u)}"?`,completionSummary:`Updated ${Mc(u.entityType)}.`,preview:Pl(u,p,i),args:n.buildArgs((g)=>({...d,...m?{operation:{source:m}}:{},id:u.id,confirmed:!0,confirmationToken:g,contentHash:u.contentHash}))});return{...q("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 a fields change to an entity the user names, call this tool directly without reading the entity first. For small content changes, fetch the entity (an upload ref marked saved already holds its text, so edit that note without fetching it) and use the edits operation with exact oldText/newText pairs, several non-overlapping edits in one call, instead of regenerating the whole document. Never replace unchanged content with placeholders or ellipses. 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, even when ogImageId already points at that image; do not stop after lookup. Cover images use coverImageId and OG/social previews ogImageId; they are not interchangeable. To generate a new cover, use system_generate cover-image. For explicit publish requests, use the publishing tool if available instead of changing status here; a follow-up like 'publish it' targets the entity just read or updated.",nr,async(d,u)=>{await i.ensureGroupingsCurrent(d.entityType);let p=or(i,d.entityType,d.operation.fields,{on:"update",allow:["visibility","coverImageId","ogImageId"]});if(p)return Ce(p);let m=await B(t,d.entityType,d.id,r,void 0,A(u.userPermissionLevel));if(!m.ok)return Ce(m.error);let g=await ff(e,d,m.entity,u);if("success"in g)return g;let{operation:f}=g,h=await s(m.entity,f,A(u.userPermissionLevel)),v=Cl(h,f,i,t);if(v)return v;let y=F(e,d.entityType,xl(h,f,i),u);if(y)return y;return d.confirmed?o(d,h,f,u):a(d,h,g)},{visibility:"trusted",sideEffects:"writes"}),modelInput:kc(e.entityRegistry)}}function Al(e){return[Jc(e),Qc(e),Kc(e),kl(e)]}function Ir(e){if(e.interfaceType!==jl)return;if(e.userPermissionLevel!=="public"||e.isAnchor)throw Error("Guest execution denied")}var Ml=3000,hf={limit:10,excerptChars:Ml},yf={limit:5,maxLimit:5,excerptChars:800};function Ll(e){return e!==void 0&&ve(e)==="local"?yf:hf}var Dl=`
92
92
 
93
93
  \u2026
94
94
 
95
- `,vf=new Set(["about","and","are","can","does","for","from","how","into","the","this","what","when","where","which","who","why","with","you","your"]);function Xi(e){return new Set(e.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter((t)=>t.length>=3&&!vf.has(t)).map((t)=>t.length>3&&t.endsWith("s")?t.slice(0,-1):t))}var zl=/^#{1,6}\s/,bf=/^\s*(```|~~~)/;function Sf(e){let t=e.split(`
95
+ `,vf=new Set(["about","and","are","can","does","for","from","how","into","the","this","what","when","where","which","who","why","with","you","your"]);function en(e){return new Set(e.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter((t)=>t.length>=3&&!vf.has(t)).map((t)=>t.length>3&&t.endsWith("s")?t.slice(0,-1):t))}var zl=/^#{1,6}\s/,bf=/^\s*(```|~~~)/;function Sf(e){let t=e.split(`
96
96
  `),{starts:r}=t.reduce((n,o,s)=>{if(!n.inFence&&s>0&&zl.test(o))n.starts.push(s);if(bf.test(o))n.inFence=!n.inFence;return n},{inFence:!1,starts:[]}),i=[0,...r,t.length];return i.slice(0,-1).map((n,o)=>t.slice(n,i[o+1]).join(`
97
97
  `).trim()).filter((n)=>n.length>0).map((n,o)=>({index:o,heading:zl.test(n)?n.split(`
98
- `)[0]??"":"",text:n}))}function Rf(e,t){let r=Xi(t.heading),i=Xi(t.text);return Array.from(e).reduce((n,o)=>n+(i.has(o)?1:0)+(r.has(o)?1:0),0)}function Ol(e,t){if(e.length<=t)return e;let r=e.slice(0,t-1);return`${r.slice(0,Math.max(r.lastIndexOf(" "),1)).trimEnd()}\u2026`}function Ul(e,t,r=Ml){if(e.length<=r)return e;let i=Xi(t),n=Sf(e).map((a)=>({section:a,score:Rf(i,a)})).filter(({score:a})=>a>0).sort((a,c)=>c.score-a.score||a.section.index-c.section.index).map(({section:a})=>a),[o]=n;if(!o)return Ol(e.trim(),r);if(o.text.length>r)return Ol(o.text,r);let{kept:s}=n.reduce((a,c)=>{let d=c.text.length+(a.kept.length>0?Dl.length:0);return a.used+d<=r?{used:a.used+d,kept:[...a.kept,c]}:a},{used:0,kept:[]});return s.sort((a,c)=>a.index-c.index).map((a,c,d)=>{let u=d[c-1];if(!u)return a.text;return`${a.index===u.index+1?`
98
+ `)[0]??"":"",text:n}))}function Rf(e,t){let r=en(t.heading),i=en(t.text);return Array.from(e).reduce((n,o)=>n+(i.has(o)?1:0)+(r.has(o)?1:0),0)}function Ol(e,t){if(e.length<=t)return e;let r=e.slice(0,t-1);return`${r.slice(0,Math.max(r.lastIndexOf(" "),1)).trimEnd()}\u2026`}function Ul(e,t,r=Ml){if(e.length<=r)return e;let i=en(t),n=Sf(e).map((a)=>({section:a,score:Rf(i,a)})).filter(({score:a})=>a>0).sort((a,c)=>c.score-a.score||a.section.index-c.section.index).map(({section:a})=>a),[o]=n;if(!o)return Ol(e.trim(),r);if(o.text.length>r)return Ol(o.text,r);let{kept:s}=n.reduce((a,c)=>{let d=c.text.length+(a.kept.length>0?Dl.length:0);return a.used+d<=r?{used:a.used+d,kept:[...a.kept,c]}:a},{used:0,kept:[]});return s.sort((a,c)=>a.index-c.index).map((a,c,d)=>{let u=d[c-1];if(!u)return a.text;return`${a.index===u.index+1?`
99
99
 
100
- `:Dl}${a.text}`}).join("")}var wf=0.5;function $l(e,t){let r=e??t.limit;return t.maxLimit===void 0?r:Math.min(r,t.maxLimit)}function Bl(e,t,r,i){let n=Ni(e.entity,r);if(n!==e.entity)return{...e,entity:n,excerpt:n.content};let o=Ki(n.content);if(o.length<=i)return{...e,entity:n};let{content:s,...a}=n;return{...e,entity:a,excerpt:Ul(o,t,i),excerpted:!0}}var Tr=(e)=>e==="public"?{publishedOnly:!0}:{};function Pf(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 _l(e){let{entityService:t,logger:r}=e;return[ge("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. When the user names entity types, search each with scope.kind type in the same step, without a broad search first. 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. When the question is in a different language from the saved content, also search with the query translated into the content's language before concluding that little exists; the content's language is the language of the search results and of the brain's profile, and matches across languages score lower. Search results include each matched entity's content; a long one's is excerpted to its best-matching sections, which system_get reads whole. 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. 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 results or memory, including analysis phrasing such as 'How do I discuss X in my writing?'.",mc,async(i,n)=>{Ir(n);let o=A(n.userPermissionLevel);if(i.scope.kind==="type"&&e.entityRegistry.getEntityTypeConfig(i.scope.entityType).embeddable===!1){let{entityType:u}=i.scope;return{success:!0,data:{results:(await t.listEntities({entityType:u,options:{limit:$l(i.limit,e.searchBudget),filter:{visibilityScope:o},...Tr(o)}})).map((m)=>Bl({entity:m},i.query,e.entityRegistry,e.searchBudget.excerptChars)),notSearchable:{entityType:u,hint:`${u} is not in the search index, so the results are its entries, unranked.`}}}}let s=i.minScore??wf,a=await t.search({query:i.query,options:{limit:$l(i.limit,e.searchBudget),...i.scope.kind==="type"&&{types:[i.scope.entityType]},...i.includeUngenerated!==void 0&&{includeUngenerated:i.includeUngenerated},visibilityScope:o,...Tr(o)}}),c=a.filter((u)=>u.score>=s),d=c.length===0?Pf(a,s):void 0;return{success:!0,data:{results:c.map((u)=>Bl(u,i.query,e.entityRegistry,e.searchBudget.excerptChars)),...d&&{belowThreshold:d}}}},{visibility:"public",sideEffects:"none",cli:{name:"search"}}),ge("system","get","Retrieve a specific entity by type and identifier (ID, slug, or title). When the user asks to read, show or verify an entity, call system_get in that turn instead of answering from earlier results in this conversation: stored content can change outside this conversation. If retrieval fails, report the entity as not found rather than describing related generation work as pending.",gc,async(i,n)=>{if(Ir(n),!t.getEntityTypes().includes(i.entityType))return{success:!1,error:`Unknown entity type: ${i.entityType}. Available: ${t.getEntityTypes().join(", ")}`};let o=A(n.userPermissionLevel),s=await B(t,i.entityType,i.id,r,void 0,o,{...Tr(o),source:!0});if(!s.ok)return{success:!1,error:s.error};let a=Ni(s.entity,e.entityRegistry);return{success:!0,data:{entity:i.part==="body"?{...a,content:Ki(a.content)}:a}}},{visibility:"public",sideEffects:"none",cli:{name:"get"}}),ge("system","list","List entities by a known entity type. Returns metadata only; it answers a request to show or list items of a type, such as titles, dates and descriptions, so answer from it and use system_get only when the user asks about an item's full content. Use system_search, not system_list, for broad or vague lookup requests. For list/show-all requests that name or browse a known type or synonym (essays/articles/blog posts => post), list that type instead of searching; for a whole-type summary such as 'summarize my blog posts', list it first, then summarize the returned entities. 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.",fc,async(i,n)=>{if(Ir(n),!t.getEntityTypes().includes(i.entityType))return{success:!1,error:`Unknown entity type: ${i.entityType}. Available: ${t.getEntityTypes().join(", ")}`};let o=A(n.userPermissionLevel),s={visibilityScope:o};if(i.status&&i.status!=="any")s.metadata={status:i.status};let{defaultSort:a}=e.entityRegistry.getEntityTypeConfig(i.entityType),d=(await t.listEntities({entityType:i.entityType,options:{limit:i.limit??20,filter:s,...Tr(o),...a?{sortFields:a}:{}}})).map(({content:u,contentHash:p,...m})=>m);return{success:!0,data:{entities:d,count:d.length}}},{visibility:"public",sideEffects:"none",cli:{name:"list"}})]}function Cf(e){let t=Object.fromEntries(Object.entries(e.params.shape).map(([r,i])=>{let n=i instanceof l.ZodDefault?i.unwrap():i,o=i.description?n.describe(i.description):n;return[r,o.optional()]}));return l.looseObject(t).describe(`Params for ${e.type}`)}function xf(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(Cf),n=l.union([...i,l.looseObject({})]);return l.object({type:l.enum([t,...r]).describe("The report to run"),params:n.optional().describe("The report's params; each report lists its own")})}function Zl(e){let{entityService:t,analytics:r}=e,i=r.getDefinitions(),n=i.map((o)=>`${o.type} (${o.description})`).join("; ");return[ge("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}.`,xf(i),async(o,s)=>({success:!0,data:await r.run({type:o.type,params:o.params,entityService:t,permission:s.userPermissionLevel??"public"})}),{visibility:"public",sideEffects:"none"})]}function Fl(e){let{jobs:t}=e;return[q("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.",Rc,async(r,i)=>{let n=e.permissionService.hasPermission(i.userPermissionLevel??"public","trusted");if(r.batchId){let a=await t.getBatchStatus(r.batchId);if(!a)return{success:!1,error:`No batch found with ID: ${r.batchId}`};let c=a.totalOperations>0?Math.round(a.completedOperations/a.totalOperations*100):0;return{success:!0,data:{batchId:r.batchId,status:a.status,progress:{total:a.totalOperations,completed:a.completedOperations,failed:a.failedOperations,percentComplete:c},currentOperation:a.currentOperation,...n&&{errors:a.errors}}}}let o=await t.getActiveJobs(r.jobTypes),s=await t.getActiveBatches();return{success:!0,data:{summary:{activeJobs:o.length,activeBatches:s.length},jobs:o.map((a)=>({id:a.id,type:a.type,status:a.status,priority:a.priority,retryCount:a.retryCount,createdAt:new Date(a.createdAt).toISOString(),startedAt:a.startedAt?new Date(a.startedAt).toISOString():null})),batches:s.map((a)=>({batchId:a.batchId,status:a.status.status,totalOperations:a.status.totalOperations,completedOperations:a.status.completedOperations,failedOperations:a.status.failedOperations,currentOperation:a.status.currentOperation,pluginId:a.metadata.metadata.pluginId,...n&&{errors:a.status.errors}}))}}},{visibility:"public",sideEffects:"none"})]}function If(e,t){let{entityCounts:r,daemons:i,endpoints:n,interactions:o,...s}=e,a=n.filter((c)=>t(c.visibility)).sort((c,d)=>c.priority-d.priority).map(({label:c,url:d})=>({label:c,url:d}));if(!t("trusted"))return{...{version:e.version,uptime:e.uptime,backgroundWork:e.backgroundWork},endpoints:a};return{...s,endpoints:a}}function Nl(e){return[ge("system","status","Get system status including version, background work, and the web surfaces (such as the dashboard and Studio) the caller can open, with their paths; trusted callers also get the model and entity totals",l.object({}),async(t,r)=>({success:!0,data:If(await e.getAppInfo(),(i)=>e.permissionService.hasPermission(r.userPermissionLevel??"public",i))}),{visibility:"public",sideEffects:"none",cli:{name:"status"}})]}function Hl(e){return[..._l(e),...Fl(e),...Nl(e),...Al(e),...Zl(e)]}function Wl(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(`
100
+ `:Dl}${a.text}`}).join("")}var wf=0.5;function $l(e,t){let r=e??t.limit;return t.maxLimit===void 0?r:Math.min(r,t.maxLimit)}function Bl(e,t,r,i){let n=Ni(e.entity,r);if(n!==e.entity)return{...e,entity:n,excerpt:n.content};let o=Vi(n.content);if(o.length<=i)return{...e,entity:n};let{content:s,...a}=n;return{...e,entity:a,excerpt:Ul(o,t,i),excerpted:!0}}var Tr=(e)=>e==="public"?{publishedOnly:!0}:{};function Pf(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 _l(e){let{entityService:t,logger:r}=e;return[ge("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. When the user names entity types, search each with scope.kind type in the same step, without a broad search first. 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. When the question is in a different language from the saved content, also search with the query translated into the content's language before concluding that little exists; the content's language is the language of the search results and of the brain's profile, and matches across languages score lower. Search results include each matched entity's content; a long one's is excerpted to its best-matching sections, which system_get reads whole. 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. 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 results or memory, including analysis phrasing such as 'How do I discuss X in my writing?'.",gc,async(i,n)=>{Ir(n);let o=A(n.userPermissionLevel);if(i.scope.kind==="type"&&e.entityRegistry.getEntityTypeConfig(i.scope.entityType).embeddable===!1){let{entityType:u}=i.scope;return{success:!0,data:{results:(await t.listEntities({entityType:u,options:{limit:$l(i.limit,e.searchBudget),filter:{visibilityScope:o},...Tr(o)}})).map((m)=>Bl({entity:m},i.query,e.entityRegistry,e.searchBudget.excerptChars)),notSearchable:{entityType:u,hint:`${u} is not in the search index, so the results are its entries, unranked.`}}}}let s=i.minScore??wf,a=await t.search({query:i.query,options:{limit:$l(i.limit,e.searchBudget),...i.scope.kind==="type"&&{types:[i.scope.entityType]},...i.includeUngenerated!==void 0&&{includeUngenerated:i.includeUngenerated},visibilityScope:o,...Tr(o)}}),c=a.filter((u)=>u.score>=s),d=c.length===0?Pf(a,s):void 0;return{success:!0,data:{results:c.map((u)=>Bl(u,i.query,e.entityRegistry,e.searchBudget.excerptChars)),...d&&{belowThreshold:d}}}},{visibility:"public",sideEffects:"none",cli:{name:"search"}}),ge("system","get","Retrieve a specific entity by type and identifier (ID, slug, or title). When the user asks to read, show or verify an entity, call system_get in that turn instead of answering from earlier results in this conversation: stored content can change outside this conversation. If retrieval fails, report the entity as not found rather than describing related generation work as pending.",fc,async(i,n)=>{if(Ir(n),!t.getEntityTypes().includes(i.entityType))return{success:!1,error:`Unknown entity type: ${i.entityType}. Available: ${t.getEntityTypes().join(", ")}`};let o=A(n.userPermissionLevel),s=await B(t,i.entityType,i.id,r,void 0,o,{...Tr(o),source:!0});if(!s.ok)return{success:!1,error:s.error};let a=Ni(s.entity,e.entityRegistry);return{success:!0,data:{entity:i.part==="body"?{...a,content:Vi(a.content)}:a}}},{visibility:"public",sideEffects:"none",cli:{name:"get"}}),ge("system","list","List entities by a known entity type. Returns metadata only; it answers a request to show or list items of a type, such as titles, dates and descriptions, so answer from it and use system_get only when the user asks about an item's full content. Use system_search, not system_list, for broad or vague lookup requests. For list/show-all requests that name or browse a known type or synonym (essays/articles/blog posts => post), list that type instead of searching; for a whole-type summary such as 'summarize my blog posts', list it first, then summarize the returned entities. 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.",hc,async(i,n)=>{if(Ir(n),!t.getEntityTypes().includes(i.entityType))return{success:!1,error:`Unknown entity type: ${i.entityType}. Available: ${t.getEntityTypes().join(", ")}`};let o=A(n.userPermissionLevel),s={visibilityScope:o};if(i.status&&i.status!=="any")s.metadata={status:i.status};let{defaultSort:a}=e.entityRegistry.getEntityTypeConfig(i.entityType),d=(await t.listEntities({entityType:i.entityType,options:{limit:i.limit??20,filter:s,...Tr(o),...a?{sortFields:a}:{}}})).map(({content:u,contentHash:p,...m})=>m);return{success:!0,data:{entities:d,count:d.length}}},{visibility:"public",sideEffects:"none",cli:{name:"list"}})]}function Cf(e){let t=Object.fromEntries(Object.entries(e.params.shape).map(([r,i])=>{let n=i instanceof l.ZodDefault?i.unwrap():i,o=i.description?n.describe(i.description):n;return[r,o.optional()]}));return l.looseObject(t).describe(`Params for ${e.type}`)}function xf(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(Cf),n=l.union([...i,l.looseObject({})]);return l.object({type:l.enum([t,...r]).describe("The report to run"),params:n.optional().describe("The report's params; each report lists its own")})}function Zl(e){let{entityService:t,analytics:r}=e,i=r.getDefinitions(),n=i.map((o)=>`${o.type} (${o.description})`).join("; ");return[ge("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}.`,xf(i),async(o,s)=>({success:!0,data:await r.run({type:o.type,params:o.params,entityService:t,permission:s.userPermissionLevel??"public"})}),{visibility:"public",sideEffects:"none"})]}function Fl(e){let{jobs:t}=e;return[q("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.",wc,async(r,i)=>{let n=e.permissionService.hasPermission(i.userPermissionLevel??"public","trusted");if(r.batchId){let a=await t.getBatchStatus(r.batchId);if(!a)return{success:!1,error:`No batch found with ID: ${r.batchId}`};let c=a.totalOperations>0?Math.round(a.completedOperations/a.totalOperations*100):0;return{success:!0,data:{batchId:r.batchId,status:a.status,progress:{total:a.totalOperations,completed:a.completedOperations,failed:a.failedOperations,percentComplete:c},currentOperation:a.currentOperation,...n&&{errors:a.errors}}}}let o=await t.getActiveJobs(r.jobTypes),s=await t.getActiveBatches();return{success:!0,data:{summary:{activeJobs:o.length,activeBatches:s.length},jobs:o.map((a)=>({id:a.id,type:a.type,status:a.status,priority:a.priority,retryCount:a.retryCount,createdAt:new Date(a.createdAt).toISOString(),startedAt:a.startedAt?new Date(a.startedAt).toISOString():null})),batches:s.map((a)=>({batchId:a.batchId,status:a.status.status,totalOperations:a.status.totalOperations,completedOperations:a.status.completedOperations,failedOperations:a.status.failedOperations,currentOperation:a.status.currentOperation,pluginId:a.metadata.metadata.pluginId,...n&&{errors:a.status.errors}}))}}},{visibility:"public",sideEffects:"none"})]}function If(e,t){let{entityCounts:r,daemons:i,endpoints:n,interactions:o,...s}=e,a=n.filter((c)=>t(c.visibility)).sort((c,d)=>c.priority-d.priority).map(({label:c,url:d})=>({label:c,url:d}));if(!t("trusted"))return{...{version:e.version,uptime:e.uptime,backgroundWork:e.backgroundWork},endpoints:a};return{...s,endpoints:a}}function Nl(e){return[ge("system","status","Get system status including version, background work, and the web surfaces (such as the dashboard and Studio) the caller can open, with their paths; trusted callers also get the model and entity totals",l.object({}),async(t,r)=>({success:!0,data:If(await e.getAppInfo(),(i)=>e.permissionService.hasPermission(r.userPermissionLevel??"public",i))}),{visibility:"public",sideEffects:"none",cli:{name:"status"}})]}function Hl(e){return[..._l(e),...Fl(e),...Nl(e),...Al(e),...Zl(e)]}function Wl(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(`
101
101
  `)}]})},{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 ql(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((s)=>({id:s.id,entityType:s.entityType,...s.metadata,updated:s.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 Jl(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 Gl(e){return["## Entity CRUD","","Use the system tools for ALL entity operations; each tool's description is its contract.","","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.","","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 pass `confirmed: true` on the initial user request. Deletion is Admin-only: if system_delete is not available in the current tool surface, say deletion requires Admin access; do not imply a confirmation flow is available. 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:",...e.entityService.getEntityTypes().map((i)=>`- ${i}: ${e.entityRegistry.getAdapter(i).purpose}`)].join(`
102
- `)}var Ue="system",Tf=l.object({toolName:l.string(),args:l.unknown(),...Ql.partial().shape});function Er(e,t,r,i,n){for(let o of e)try{t(o)}catch{n.debug(`System ${i} ${r(o)} already registered, skipping`)}}function Kl(e,t,r,i){let n=Hl(e);Er(n,(u)=>t.registerTool(Ue,u),(u)=>u.name,"tool",i);let o=r.subscribe(Xt.toolExecute(Ue),async(u)=>{let p=Tf.safeParse(u.payload);if(!p.success)return{success:!1,error:"Invalid system tool execute payload"};let{toolName:m,args:g,interfaceType:f,actor:h,conversationId:v,channelId:y,userPermissionLevel:S}=p.data,R=n.find((I)=>I.name===m);if(!R)return{success:!1,error:`System tool not found: ${m}`};let w={interfaceType:f??"system",actor:h??{kind:"service",serviceId:"system"}};if(v)w.conversationId=v;if(y)w.channelId=y;if(S)w.userPermissionLevel=S;return{success:!0,data:await R.handler(g,w)}});i.debug(`Registered ${n.length} system tools`);let s=Wl(e);Er(s,(u)=>t.registerResource(Ue,u),(u)=>u.uri,"resource",i),i.debug(`Registered ${s.length} system resources`);let a=ql(e);Er(a,(u)=>t.registerResourceTemplate(Ue,u),(u)=>u.uriTemplate,"resource template",i),i.debug(`Registered ${a.length} system resource templates`);let c=Jl(e);Er(c,(u)=>t.registerPrompt(Ue,u),(u)=>u.name,"prompt",i),i.debug(`Registered ${c.length} system prompts`);let d=Gl(e);try{t.registerInstructions(Ue,d)}catch{i.debug("System instructions already registered, skipping")}return i.debug("Registered system instructions"),o}function td(e){let{services:t,jobs:r,analytics:i,query:n,getAppInfo:o}=e,s=t.jobQueueService,a=t.logger.child("system"),c=Kl({entityService:t.entityService,entityRegistry:t.entityRegistry,jobs:{...r,enqueue:Vl(s,"system",!1),enqueueBatch:Xl(r,"system"),registerHandler:ed(s,"system"),has:Yl(s)},conversationService:t.conversationService,runtimeUploads:t.runtimeUploadRegistry,attachments:kr(t.attachmentRegistry),logger:a,query:n,getIdentity:()=>t.identityService.getCharacter(),getProfile:()=>t.profileService.getProfile(),getAppInfo:o,searchBudget:Ll(t.aiService.getConfig().model),analytics:i,permissionService:t.permissionService},t.mcpService,t.messageBus,a);t.disposables.push(c)}class en{scope;closePromise=null;closed=!1;constructor(){this.scope=b.runSync(E.make())}buildLayer(e){this.assertOpen();let t=b.runSyncExit(V.buildWithScope(e,this.scope));if(k.isFailure(t))throw de.squash(t.cause);return t.value}addFinalizer(e){this.assertOpen(),b.runSync(E.addFinalizer(this.scope,b.promise(async()=>{await e()})))}addSyncFinalizer(e){this.assertOpen(),b.runSync(E.addFinalizer(this.scope,b.sync(()=>{e()})))}async fork(e){if(this.closed)throw Error("Cannot start background work after shell shutdown");await b.runPromise(b.forkIn(e,this.scope))}close(e=k.void){if(this.closePromise)return this.closePromise;if(this.closed)return Promise.resolve();return this.closed=!0,this.closePromise=b.runPromise(E.close(this.scope,e)),this.closePromise}closeSync(e){if(this.closed)return;this.closed=!0,b.runSync(E.close(this.scope,e))}assertOpen(){if(this.closed)throw Error("Cannot register cleanup after shell shutdown")}}class tn{config;services;lifecycle;bootloader;initialized=!1;lifecycleState="constructed";bootMode;bootPromise=null;shutdownPromise=null;analyticsRegistry;bootTime=Date.now();endpointRegistry=new Di;interactionRegistry=new zi;httpRouteRegistry=rr.createFresh();httpServed;jobs;static createFresh(e,t,r){return new tn(ft(e),t,r)}constructor(e,t,r){this.config=e,this.httpServed=e.http.enabled&&ke(r?.processRole).serves,this.lifecycle=new en,ld(this,()=>this.httpRouteRegistry.getSnapshot());let i=t?.logger??Ee.getInstance(),n=$t.createFresh(i,this.config,r?.processRole,r?.peerChannel);try{if(this.services=n.initializeServices(this.lifecycle,t),this.jobs=sc(this.services.batchJobManager,this.services.jobQueueService),this.analyticsRegistry=tc(this.services.entityRegistry),this.bootloader=new Ai(this.config,this.services,this.lifecycle,n,r?.processRole,{registerCoreDataSources:()=>wn(this.services,this.config),finalizeHttpRoutes:()=>{this.httpRouteRegistry.finalize(cc(this.services.pluginManager))},registerSystemCapabilities:()=>td({services:this.services,jobs:this.jobs,analytics:this.analyticsRegistry,query:(o,s)=>this.query(o,s),getAppInfo:()=>this.getAppInfo()}),createProjectionInputContext:()=>this.createProjectionInputContext(),createProjectionExecutionContext:()=>this.createProjectionExecutionContext(),...t?.projectionRuntime&&{projectionRuntime:t.projectionRuntime}}),n.wireShell(this.services,this),this.httpServed)this.registerHttpHost();uc(this.lifecycle,this.services)}catch(o){try{this.lifecycle.closeSync(k.fail(o))}catch(s){i.error("Failed to roll back Shell service construction",s)}throw o}}createProjectionInputContext(){return{entities:this.services.entityService,resolvePrompt:(e,t)=>ht(this.services.entityService,e,t),appInfo:()=>this.getAppInfo(),identityInput:()=>{let e=this.getIdentity(),t=this.getProfile();return id.parse({brainName:e.name,role:e.role,purpose:e.purpose,values:e.values,profileName:t.name,...t.description!==void 0?{profileDescription:t.description}:{},...t.organization!==void 0?{profileOrganization:t.organization}:{}})}}}createProjectionExecutionContext(){return{ai:od(this),logger:this.services.logger.child("ProjectionRuntime")}}async runProjectionRule(e,t={},r=new AbortController().signal){let i=this.services.pluginManager.getProjectionRulesSnapshot().find(({id:s})=>s===e);if(!i)throw Error(`Unknown projection rule "${e}"`);let n=await i.selectInput({waveId:"eval",inputs:t.inputs??[]},this.createProjectionInputContext(),r),o=await i.derive(n,this.createProjectionExecutionContext(),r);return Array.isArray(o)?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 je(this.services.messageBus,sd,{timestamp:new Date().toISOString()},"shell"),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(k.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"),Pn(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 rd.parse(await this.generateContent({prompt:e,templateName:Ne.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}getCallerAuthorizer(){return this.services.callerAuthorizer}getRenderService(){return this.services.renderService}getAttachmentRegistry(){return kr(this.services.attachmentRegistry)}getRuntimeUploadRegistry(){return ad(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}getAuthRegistry(){return this.services.authRegistry}getAtprotoProjectionRegistry(){return this.services.atprotoProjectionRegistry}getDomain(){return this.config.siteBaseUrl}getLocalSiteUrl(){return this.config.localSiteUrl}shouldPreferLocalUrls(){return this.config.preferLocalUrls}isProduction(){return this.config.production}servesHttp(){return this.httpServed}registerHttpHost(){let{daemonRegistry:e,logger:t,messageBus:r,pluginManager:i}=this.services;e.register(Y,Na({config:this.config.http,domain:this.config.siteBaseUrl,logger:t.child(W),messageBus:r,getRoutes:()=>this.httpRouteRegistry.getSnapshot(),getPlugins:()=>[...i.getAllPlugins().values()].map(({plugin:s})=>s),getOperationalInfo:async()=>cd(nd(await this.getAppInfo())),getReadinessData:()=>this.getRuntimeReadiness()}),W),this.lifecycle.addSyncFinalizer(()=>e.abandon(Y));let{endpoints:n,interactions:o}=Ha(this.config.http,this.config.siteBaseUrl);for(let s of n)this.endpointRegistry.register(s);for(let s of o)this.interactionRegistry.register(s)}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 un({config:this.config,services:this.services,bootTime:this.bootTime,endpoints:()=>this.listEndpoints(),interactions:()=>this.listInteractions()})}getRuntimeReadiness(){return gn(this.services)}}async function Sd(e,t){await fe({label:"entity",config:e,schema:{assets:ud,entities:dd,entityMutationReceipts:pd,projectionDirtyInputs:md,projectionWaves:gd,projectionIncidents:fd,projectionWaveInputs:hd,projectionWaveRules:yd,projectionRuleMemos:vd},migrationsFolder:he(import.meta.url,"entity-service"),authTokenEnv:"DATABASE_AUTH_TOKEN",logger:t,afterMigrate:bd})}async function Pd(e,t){await fe({label:"job-queue",config:e,schema:{jobQueue:Rd,jobWorkerSessions:wd},migrationsFolder:he(import.meta.url,"job-queue"),authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",logger:t})}async function Td(e,t){await fe({label:"conversation",config:e,schema:{conversations:Cd,messages:xd,summaryTracking:Id},migrationsFolder:he(import.meta.url,"conversation-service"),authTokenEnv:"CONVERSATION_DATABASE_AUTH_TOKEN",logger:t})}async function Ed(e,t){await fe({label:"runtime-state",config:e,schema:{runtimeStateRecords:P},migrationsFolder:he(import.meta.url,"runtime-state"),authTokenEnv:"RUNTIME_STATE_DATABASE_AUTH_TOKEN",logger:t})}import{mkdir as nn}from"fs/promises";import{isAbsolute as Ef}from"path";function kd(e=process.env){return{dataDir:e.XDG_DATA_HOME??"./data",cacheDir:e.XDG_CACHE_HOME??"./cache",distDir:"./dist"}}function Ad(e=process.env){let t=e.BRAIN_GIT_BROKER_CHECKOUT;if(!t)return;if(!Ef(t))throw Error(`Git broker checkout path must be absolute: ${t}`);return t}function jd(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 Dd(e=process.env){return ye(kd(e))}async function zd(e=process.env){let t=kd(e);try{await nn(t.dataDir,{recursive:!0}),await nn(t.cacheDir,{recursive:!0}),await nn(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 ye(t)}class kf{logger;migrations;constructor(e,t){this.logger=e,this.migrations=t??{getStandardConfigWithDirectories:()=>zd(),migrateEntities:Sd,migrateJobQueue:Pd,migrateConversations:Td,migrateRuntimeState:Ed}}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 on={kind:"service",serviceId:"brain-cli"},sn=`${on.kind}:${on.serviceId}`;function Ok(e="admin"){return{interfaceType:"cli",actor:on,userPermissionLevel:e}}var Uk=l.enum(["eval"]),$k=l.enum(["person","team","organization"]),an=l.object({provider:l.enum(["hetzner","docker"]).default("hetzner"),serverSize:l.string().default("cx33"),location:l.string().default("fsn1"),domain:l.string().optional(),docker:l.object({enabled:l.boolean().default(!0),image:l.string().optional()}).prefault({}),ports:l.object({default:l.number().default(3333),preview:l.number().default(4321),production:l.number().default(8080)}).prefault({}),cdn:l.object({enabled:l.boolean().default(!1),provider:l.enum(["bunny","none"]).default("none")}).prefault({}),dns:l.object({enabled:l.boolean().default(!1),provider:l.enum(["bunny","none"]).default("none")}).prefault({}),paths:l.object({install:l.string().optional(),data:l.string().optional()}).prefault({})});var Md=l.object({name:l.string().default("brain-app"),version:l.string().default("1.0.0"),database:l.string().optional(),aiProviderKeys:Fe.optional(),aiModel:l.string().optional(),aiEmbeddingModel:l.string().optional(),aiModelRuntimeUrl:l.string().optional(),aiAnswerModel:l.string().optional(),aiVisionModel:l.string().optional(),aiImageModel:l.string().optional(),aiReasoningEffort:se.optional(),logLevel:Te.optional(),logFile:l.string().optional(),profileKind:l.string().trim().min(1).optional(),plugins:l.array(gt).default([]),spaces:l.array(l.string()).default([]),identity:Od.optional(),agentInstructions:l.array(l.string()).optional(),deployment:an.prefault({}),http:Ze.prefault({})});var Af="NODE_ENV";function jf(){return process.env[Af]}function cn(){return jf()==="production"}function Ld(){return!cn()}var Df="startup-check";function zf(){return Object.fromEntries(rn.map((e)=>[e,Df]))}function tA(e){let r={...Md.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 rA(e,t){let r={plugins:e.plugins??[],...e.shellConfig};return Of(r),Mf(e,r),Lf(e,r,t),Uf(e,r),$f(e,r),Bf(e,r),_f(e,r),Zf(e,r),Nf(e,r),Ff(e,r),r}function Of(e){let t=Dd();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??=jd(),e.gitBrokerCheckout??=Ad()}function Mf(e,t){if(e.database)t.database={url:e.database};if(e.profileKind)t.profileKind=e.profileKind;t.features={}}function Lf(e,t,r){let i=r?.mode==="startup-check";if(!e.aiProviderKeys&&!e.aiModel&&!e.aiEmbeddingModel&&!e.aiModelRuntimeUrl&&!e.aiAnswerModel&&!e.aiVisionModel&&!e.aiImageModel&&!e.aiReasoningEffort&&!i)return;t.ai={...t.ai,providerKeys:{...i&&zf(),...t.ai?.providerKeys,...e.aiProviderKeys},...e.aiModel&&{model:e.aiModel},...e.aiEmbeddingModel&&{embeddingModel:e.aiEmbeddingModel},...e.aiModelRuntimeUrl&&{modelRuntimeUrl:e.aiModelRuntimeUrl},...e.aiAnswerModel&&{answerModel:e.aiAnswerModel},...e.aiVisionModel&&{visionModel:e.aiVisionModel},...e.aiImageModel&&{imageModel:e.aiImageModel},...e.aiReasoningEffort&&{reasoningEffort:e.aiReasoningEffort}}}function Uf(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 $f(e,t){let r=e.permissions?.rules??[];t.permissions={...e.permissions,rules:r.some((i)=>i.pattern===sn)?r:[{pattern:sn,level:"admin"},...r]}}function Bf(e,t){if(e.spaces)t.spaces=e.spaces}function _f(e,t){if(e.identity)t.identity=e.identity}function Zf(e,t){if(e.agentInstructions)t.agentInstructions=e.agentInstructions}function Ff(e,t){t.http??={...Q(e.http),port:e.deployment.ports.production}}function Nf(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=Ld(),t.production=cn()}
103
- export{ye as R,Ze as S,Te as T,ft as U,D as V,xu as W,Iu as X,Tu as Y,zu as Z,Hn as _,Mu as $,Lu as aa,Uu as ba,$u as ca,Bu as da,_u as ea,Zu as fa,qe as ga,Po as ha,ti as ia,Gs as ja,Pi as ka,rl as la,nl as ma,sl as na,Rr as oa,qg as pa,qi as qa,Gg as ra,wr as sa,Qg as ta,Kg as ua,MI as va,Xg as wa,ef as xa,tf as ya,rf as za,tn as Aa,Sd as Ba,Pd as Ca,Td as Da,Ed as Ea,kf as Fa,Ok as Ga,$k as Ha,tA as Ia,rA as Ja};
102
+ `)}var Ue="system",Tf=l.object({toolName:l.string(),args:l.unknown(),...Ql.partial().shape});function Er(e,t,r,i,n){for(let o of e)try{t(o)}catch{n.debug(`System ${i} ${r(o)} already registered, skipping`)}}function Kl(e,t,r,i){let n=Hl(e);Er(n,(u)=>t.registerTool(Ue,u),(u)=>u.name,"tool",i);let o=r.subscribe(Xt.toolExecute(Ue),async(u)=>{let p=Tf.safeParse(u.payload);if(!p.success)return{success:!1,error:"Invalid system tool execute payload"};let{toolName:m,args:g,interfaceType:f,actor:h,conversationId:v,channelId:y,userPermissionLevel:S}=p.data,R=n.find((I)=>I.name===m);if(!R)return{success:!1,error:`System tool not found: ${m}`};let w={interfaceType:f??"system",actor:h??{kind:"service",serviceId:"system"}};if(v)w.conversationId=v;if(y)w.channelId=y;if(S)w.userPermissionLevel=S;return{success:!0,data:await R.handler(g,w)}});i.debug(`Registered ${n.length} system tools`);let s=Wl(e);Er(s,(u)=>t.registerResource(Ue,u),(u)=>u.uri,"resource",i),i.debug(`Registered ${s.length} system resources`);let a=ql(e);Er(a,(u)=>t.registerResourceTemplate(Ue,u),(u)=>u.uriTemplate,"resource template",i),i.debug(`Registered ${a.length} system resource templates`);let c=Jl(e);Er(c,(u)=>t.registerPrompt(Ue,u),(u)=>u.name,"prompt",i),i.debug(`Registered ${c.length} system prompts`);let d=Gl(e);try{t.registerInstructions(Ue,d)}catch{i.debug("System instructions already registered, skipping")}return i.debug("Registered system instructions"),o}function td(e){let{services:t,jobs:r,analytics:i,query:n,getAppInfo:o}=e,s=t.jobQueueService,a=t.logger.child("system"),c=Kl({entityService:t.entityService,entityRegistry:t.entityRegistry,jobs:{...r,enqueue:Vl(s,"system",!1),enqueueBatch:Xl(r,"system"),registerHandler:ed(s,"system"),has:Yl(s)},conversationService:t.conversationService,runtimeUploads:t.runtimeUploadRegistry,attachments:kr(t.attachmentRegistry),logger:a,query:n,getIdentity:()=>t.identityService.getCharacter(),getProfile:()=>t.profileService.getProfile(),getAppInfo:o,searchBudget:Ll(t.aiService.getConfig().model),analytics:i,permissionService:t.permissionService},t.mcpService,t.messageBus,a);t.disposables.push(c)}class tn{scope;closePromise=null;closed=!1;constructor(){this.scope=b.runSync(E.make())}buildLayer(e){this.assertOpen();let t=b.runSyncExit(V.buildWithScope(e,this.scope));if(k.isFailure(t))throw de.squash(t.cause);return t.value}addFinalizer(e){this.assertOpen(),b.runSync(E.addFinalizer(this.scope,b.promise(async()=>{await e()})))}addSyncFinalizer(e){this.assertOpen(),b.runSync(E.addFinalizer(this.scope,b.sync(()=>{e()})))}async fork(e){if(this.closed)throw Error("Cannot start background work after shell shutdown");await b.runPromise(b.forkIn(e,this.scope))}close(e=k.void){if(this.closePromise)return this.closePromise;if(this.closed)return Promise.resolve();return this.closed=!0,this.closePromise=b.runPromise(E.close(this.scope,e)),this.closePromise}closeSync(e){if(this.closed)return;this.closed=!0,b.runSync(E.close(this.scope,e))}assertOpen(){if(this.closed)throw Error("Cannot register cleanup after shell shutdown")}}class rn{config;services;lifecycle;bootloader;initialized=!1;lifecycleState="constructed";bootMode;bootPromise=null;shutdownPromise=null;analyticsRegistry;bootTime=Date.now();endpointRegistry=new Di;interactionRegistry=new zi;httpRouteRegistry=rr.createFresh();httpServed;jobs;static createFresh(e,t,r){return new rn(ft(e),t,r)}constructor(e,t,r){this.config=e,this.httpServed=e.http.enabled&&ke(r?.processRole).serves,this.lifecycle=new tn,ld(this,()=>this.httpRouteRegistry.getSnapshot());let i=t?.logger??Ee.getInstance(),n=$t.createFresh(i,this.config,r?.processRole,r?.peerChannel);try{if(this.services=n.initializeServices(this.lifecycle,t),this.jobs=ac(this.services.batchJobManager,this.services.jobQueueService),this.analyticsRegistry=rc(this.services.entityRegistry),this.bootloader=new Ai(this.config,this.services,this.lifecycle,n,r?.processRole,{registerCoreDataSources:()=>Pn(this.services,this.config),finalizeHttpRoutes:()=>{this.httpRouteRegistry.finalize(lc(this.services.pluginManager))},registerSystemCapabilities:()=>td({services:this.services,jobs:this.jobs,analytics:this.analyticsRegistry,query:(o,s)=>this.query(o,s),getAppInfo:()=>this.getAppInfo()}),createProjectionInputContext:()=>this.createProjectionInputContext(),createProjectionExecutionContext:()=>this.createProjectionExecutionContext(),...t?.projectionRuntime&&{projectionRuntime:t.projectionRuntime}}),n.wireShell(this.services,this),this.httpServed)this.registerHttpHost();pc(this.lifecycle,this.services)}catch(o){try{this.lifecycle.closeSync(k.fail(o))}catch(s){i.error("Failed to roll back Shell service construction",s)}throw o}}createProjectionInputContext(){return{entities:this.services.entityService,resolvePrompt:(e,t)=>ht(this.services.entityService,e,t),appInfo:()=>this.getAppInfo(),identityInput:()=>{let e=this.getIdentity(),t=this.getProfile();return id.parse({brainName:e.name,role:e.role,purpose:e.purpose,values:e.values,profileName:t.name,...t.description!==void 0?{profileDescription:t.description}:{},...t.organization!==void 0?{profileOrganization:t.organization}:{}})}}}createProjectionExecutionContext(){return{ai:od(this),logger:this.services.logger.child("ProjectionRuntime")}}async runProjectionRule(e,t={},r=new AbortController().signal){let i=this.services.pluginManager.getProjectionRulesSnapshot().find(({id:s})=>s===e);if(!i)throw Error(`Unknown projection rule "${e}"`);let n=await i.selectInput({waveId:"eval",inputs:t.inputs??[]},this.createProjectionInputContext(),r),o=await i.derive(n,this.createProjectionExecutionContext(),r);return Array.isArray(o)?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 je(this.services.messageBus,sd,{timestamp:new Date().toISOString()},"shell"),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(k.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"),Cn(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 rd.parse(await this.generateContent({prompt:e,templateName:Ne.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}getCallerAuthorizer(){return this.services.callerAuthorizer}getRenderService(){return this.services.renderService}getAttachmentRegistry(){return kr(this.services.attachmentRegistry)}getRuntimeUploadRegistry(){return ad(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}getAuthRegistry(){return this.services.authRegistry}getAtprotoProjectionRegistry(){return this.services.atprotoProjectionRegistry}getDomain(){return this.config.siteBaseUrl}getLocalSiteUrl(){return this.config.localSiteUrl}shouldPreferLocalUrls(){return this.config.preferLocalUrls}isProduction(){return this.config.production}servesHttp(){return this.httpServed}registerHttpHost(){let{daemonRegistry:e,logger:t,messageBus:r,pluginManager:i}=this.services;e.register(Y,Ha({config:this.config.http,domain:this.config.siteBaseUrl,logger:t.child(W),messageBus:r,getRoutes:()=>this.httpRouteRegistry.getSnapshot(),getPlugins:()=>[...i.getAllPlugins().values()].map(({plugin:s})=>s),getOperationalInfo:async()=>cd(nd(await this.getAppInfo())),getReadinessData:()=>this.getRuntimeReadiness()}),W),this.lifecycle.addSyncFinalizer(()=>e.abandon(Y));let{endpoints:n,interactions:o}=Wa(this.config.http,this.config.siteBaseUrl);for(let s of n)this.endpointRegistry.register(s);for(let s of o)this.interactionRegistry.register(s)}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 pn({config:this.config,services:this.services,bootTime:this.bootTime,endpoints:()=>this.listEndpoints(),interactions:()=>this.listInteractions()})}getRuntimeReadiness(){return fn(this.services)}}async function Sd(e,t){await fe({label:"entity",config:e,schema:{assets:ud,entities:dd,entityMutationReceipts:pd,projectionDirtyInputs:md,projectionWaves:gd,projectionIncidents:fd,projectionWaveInputs:hd,projectionWaveRules:yd,projectionRuleMemos:vd},migrationsFolder:he(import.meta.url,"entity-service"),authTokenEnv:"DATABASE_AUTH_TOKEN",logger:t,afterMigrate:bd})}async function Pd(e,t){await fe({label:"job-queue",config:e,schema:{jobQueue:Rd,jobWorkerSessions:wd},migrationsFolder:he(import.meta.url,"job-queue"),authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",logger:t})}async function Td(e,t){await fe({label:"conversation",config:e,schema:{conversations:Cd,messages:xd,summaryTracking:Id},migrationsFolder:he(import.meta.url,"conversation-service"),authTokenEnv:"CONVERSATION_DATABASE_AUTH_TOKEN",logger:t})}async function Ed(e,t){await fe({label:"runtime-state",config:e,schema:{runtimeStateRecords:P},migrationsFolder:he(import.meta.url,"runtime-state"),authTokenEnv:"RUNTIME_STATE_DATABASE_AUTH_TOKEN",logger:t})}import{mkdir as on}from"fs/promises";import{isAbsolute as Ef}from"path";function kd(e=process.env){return{dataDir:e.XDG_DATA_HOME??"./data",cacheDir:e.XDG_CACHE_HOME??"./cache",distDir:"./dist"}}function Ad(e=process.env){let t=e.BRAIN_GIT_BROKER_CHECKOUT;if(!t)return;if(!Ef(t))throw Error(`Git broker checkout path must be absolute: ${t}`);return t}function jd(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 Dd(e=process.env){return ye(kd(e))}async function zd(e=process.env){let t=kd(e);try{await on(t.dataDir,{recursive:!0}),await on(t.cacheDir,{recursive:!0}),await on(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 ye(t)}class kf{logger;migrations;constructor(e,t){this.logger=e,this.migrations=t??{getStandardConfigWithDirectories:()=>zd(),migrateEntities:Sd,migrateJobQueue:Pd,migrateConversations:Td,migrateRuntimeState:Ed}}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 sn={kind:"service",serviceId:"brain-cli"},an=`${sn.kind}:${sn.serviceId}`;function Ok(e="admin"){return{interfaceType:"cli",actor:sn,userPermissionLevel:e}}var Uk=l.enum(["eval"]),$k=l.enum(["person","team","organization"]),cn=l.object({provider:l.enum(["hetzner","docker"]).default("hetzner"),serverSize:l.string().default("cx33"),location:l.string().default("fsn1"),domain:l.string().optional(),docker:l.object({enabled:l.boolean().default(!0),image:l.string().optional()}).prefault({}),ports:l.object({default:l.number().default(3333),preview:l.number().default(4321),production:l.number().default(8080)}).prefault({}),cdn:l.object({enabled:l.boolean().default(!1),provider:l.enum(["bunny","none"]).default("none")}).prefault({}),dns:l.object({enabled:l.boolean().default(!1),provider:l.enum(["bunny","none"]).default("none")}).prefault({}),paths:l.object({install:l.string().optional(),data:l.string().optional()}).prefault({})});var Md=l.object({name:l.string().default("brain-app"),version:l.string().default("1.0.0"),database:l.string().optional(),aiProviderKeys:Fe.optional(),aiModel:l.string().optional(),aiEmbeddingModel:l.string().optional(),aiModelRuntimeUrl:l.string().optional(),aiAnswerModel:l.string().optional(),aiVisionModel:l.string().optional(),aiImageModel:l.string().optional(),aiReasoningEffort:se.optional(),logLevel:Te.optional(),logFile:l.string().optional(),profileKind:l.string().trim().min(1).optional(),plugins:l.array(gt).default([]),spaces:l.array(l.string()).default([]),identity:Od.optional(),agentInstructions:l.array(l.string()).optional(),deployment:cn.prefault({}),http:Ze.prefault({})});var Af="NODE_ENV";function jf(){return process.env[Af]}function ln(){return jf()==="production"}function Ld(){return!ln()}var Df="startup-check";function zf(){return Object.fromEntries(nn.map((e)=>[e,Df]))}function tA(e){let r={...Md.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 rA(e,t){let r={plugins:e.plugins??[],...e.shellConfig};return Of(r),Mf(e,r),Lf(e,r,t),Uf(e,r),$f(e,r),Bf(e,r),_f(e,r),Zf(e,r),Nf(e,r),Ff(e,r),r}function Of(e){let t=Dd();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??=jd(),e.gitBrokerCheckout??=Ad()}function Mf(e,t){if(e.database)t.database={url:e.database};if(e.profileKind)t.profileKind=e.profileKind;t.features={}}function Lf(e,t,r){let i=r?.mode==="startup-check";if(!e.aiProviderKeys&&!e.aiModel&&!e.aiEmbeddingModel&&!e.aiModelRuntimeUrl&&!e.aiAnswerModel&&!e.aiVisionModel&&!e.aiImageModel&&!e.aiReasoningEffort&&!i)return;t.ai={...t.ai,providerKeys:{...i&&zf(),...t.ai?.providerKeys,...e.aiProviderKeys},...e.aiModel&&{model:e.aiModel},...e.aiEmbeddingModel&&{embeddingModel:e.aiEmbeddingModel},...e.aiModelRuntimeUrl&&{modelRuntimeUrl:e.aiModelRuntimeUrl},...e.aiAnswerModel&&{answerModel:e.aiAnswerModel},...e.aiVisionModel&&{visionModel:e.aiVisionModel},...e.aiImageModel&&{imageModel:e.aiImageModel},...e.aiReasoningEffort&&{reasoningEffort:e.aiReasoningEffort}}}function Uf(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 $f(e,t){let r=e.permissions?.rules??[];t.permissions={...e.permissions,rules:r.some((i)=>i.pattern===an)?r:[{pattern:an,level:"admin"},...r]}}function Bf(e,t){if(e.spaces)t.spaces=e.spaces}function _f(e,t){if(e.identity)t.identity=e.identity}function Zf(e,t){if(e.agentInstructions)t.agentInstructions=e.agentInstructions}function Ff(e,t){t.http??={...Q(e.http),port:e.deployment.ports.production}}function Nf(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=Ld(),t.production=ln()}
103
+ export{ye as R,Ze as S,Te as T,ft as U,D as V,xu as W,Iu as X,Tu as Y,zu as Z,Wn as _,Mu as $,Lu as aa,Uu as ba,$u as ca,Bu as da,_u as ea,Zu as fa,qe as ga,Co as ha,ti as ia,Qs as ja,Pi as ka,rl as la,nl as ma,sl as na,Rr as oa,qg as pa,Ji as qa,Gg as ra,wr as sa,Qg as ta,Kg as ua,MI as va,Xg as wa,ef as xa,tf as ya,rf as za,rn as Aa,Sd as Ba,Pd as Ca,Td as Da,Ed as Ea,kf as Fa,Ok as Ga,$k as Ha,tA as Ia,rA as Ja};
104
104
 
105
- //# debugId=259275D6D6E517C464756E2164756E21
106
- //# sourceMappingURL=index-1rmmrnhf.js.map
105
+ //# debugId=F9C9F8E17483815164756E2164756E21
106
+ //# sourceMappingURL=index-y6d5ckd0.js.map