@rizom/brain 0.2.0-alpha.766 → 0.2.0-alpha.767

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{Qa as Ls,Ra as Us}from"./index-65426t8n.js";import{$a as mt,$b as _l,$e as Td,$j as zs,Ad as $s,Bg as xs,Bi as As,Cb as Ro,Cd as _s,Cg as Ke,Ci as ks,Db as Eo,Dd as ll,De as Ya,Dg as ac,Di as Bc,Ee as bt,Eg as cc,Ei as js,Fb as ue,Fd as Fl,Ff as Vd,Fi as Zo,Gb as pe,Gd as fs,Gf as Yd,Gg as lc,Gi as Ds,Hb as Bd,Hf as Xd,Hg as dc,Ib as $d,Ic as kd,Id as ee,Ie as so,Ig as Od,Jb as _d,Jc as Ys,Jd as Hi,Je as vs,Jg as No,Ji as zo,Kb as Fd,Kc as ho,Ke as kn,Ki as Ho,Lb as Nd,Le as bs,Li as Wo,Mb as Zd,Mf as or,Mg as xr,Mi as qo,Nb as Hd,Nc as fd,Ne as Vs,Nf as Vc,Ng as Ps,Ni as Jo,Ob as Wd,Oc as uo,Oe as Xr,Of as co,Og as je,Pb as qd,Pf as au,Qb as mo,Qg as zd,Rb as fo,Re as Gd,Rg as Cs,Sb as go,Se as Qd,Sg as Rc,Te as Xo,Tg as Ga,Ub as Lt,Ue as es,Ug as xi,Vb as ps,Ve as ts,Vi as Go,Vj as Fs,Wa as jl,Wb as Rt,Wj as Qo,Xa as lt,Xb as ke,Xc as ms,Xe as rs,Yb as be,Yd as Kc,Ye as xd,Zb as bd,Ze as Pd,Zj as Ns,_a as nn,_b as Tc,_e as Cd,_j as Ko,ab as ve,af as jd,ag as jn,aj as vc,ak as Vo,bb as xo,bc as A,be as _,bf as Xl,bg as ht,bj as bc,cb as M,cc as fr,ce as Xs,cg as sc,cj as ft,dc as ei,dg as Dd,eb as se,ec as bl,ej as Md,fc as $o,fj as Os,gb as Po,gc as _o,hc as Fo,hg as Ni,ig as il,ii as qe,jc as Br,jg as nl,ji as un,jk as Zs,kc as $r,kg as Ss,kk as Ld,lg as Rs,li as Cn,mg as ws,mi as ge,mk as Ms,ni as Tn,nk as mc,ob as Co,oi as En,ok as er,pi as Or,qc as gr,qi as Es,ri as An,tb as Jr,ub as Ct,ud as br,vb as vo,wb as bo,yb as So,yd as Ml,zb as Ud,zg as Is}from"./index-0gmp23pf.js";import{Ak as Ie,An as Ad,Ao as Ts,Bk as $e,Ck as Se,Cm as oo,Co as Ha,Dk as mr,Ek as Fe,En as ss,Fo as de,Jo as Y,Om as he,Qm as jt,Vm as Ks,Wm as Yt,Xl as Uo,Xn as qa,Zn as Ja,cm as Bo,dn as ic,en as nc,eo as re,fm as no,fo as V,hn as Kt,mo as gs,sm as Ce,so as hs,to as ys,ul as G,um as P,uo as wd,vm as Qe,wk as El,xk as Al,yk as ie,yl as Qa,zl as F,zn as vd}from"./index-1nk43d2s.js";import{Ko as Ye,Mo as Ee}from"./index-ddchamjy.js";import{At as Q,Hw as ne,Jw as Xt,Kw as oc,Nq as C,Nw as uc,Rs as oe,Ts as us,dt as j,rw as w,st as D}from"./index-5g395jvw.js";import{dy as c}from"./index-4m52m4bj.js";function jr(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 He(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=jr(e,t).reduce((a,l)=>a+l.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 Rn(e){let{config:t,services:r,bootTime:i,endpoints:n,interactions:o}=e,[s,a,l,d]=await Promise.all([r.entityService.getEntityCounts(mt("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:He(d,r.jobQueueService.getExecutionRegistrations()),ai:{model:t.ai.model,embeddingModel:r.embeddingService.identity.model},daemons:l,endpoints:n(),interactions:o()}}import{readdir as wn,readFile as Tu}from"fs/promises";var Eu=10;async function Au(e="/proc"){let t=null;try{t=(await wn(`${e}/self/fd`)).length}catch{}try{let i=(await wn(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 Tu(`${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 In(e,t,r){return t.status==="fulfilled"?{name:e,status:"healthy",message:r}:{name:e,status:"unhealthy",message:P(t.reason)}}function ku(e){if(!e)return{name:"job-worker",status:"degraded",message:"Worker session state is unavailable"};let t=e.workerSessions,r=He(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 ju(e){if(!e)return{name:"job-queue-progress",status:"degraded",message:"Queue progress state is unavailable"};let t=He(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 Du(e,t){if(!e||!t)return{name:"job-execution-inventory",status:"degraded",message:"Job execution inventory is unavailable"};let r=jr(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 Ou(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 zu(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 Mu(e){let t=e.entityService.getProjectionStore(),[r,i,n]=await Promise.all([t.getActiveWave(),t.getUnresolvedProjectionIncidentDiagnostics(Eu),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((l)=>l.status==="queued"||l.status==="failed"),a=(await Promise.all(s.map(async(l)=>{let d=l.jobId?await e.jobQueueService.getStatus(l.jobId):null;if(l.status!=="failed"&&d&&(d.status==="pending"||d.status==="processing"))return null;return{ruleId:l.ruleId,jobId:l.jobId,jobStatus:d?.status??"missing"}}))).filter((l)=>l!==null);return{waveId:r.id,batches:n,strandedRules:a,incidentCount:i.total,incidents:i.incidents}}function Lu(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 Uu(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 xn(e){let t=e.now?.()??Date.now(),r=(e.memoryUsage??process.memoryUsage)(),[i,n,o,s,a,l,d,u]=await Promise.allSettled([e.entityService.getEntityCounts(mt("runtime readiness database probe")),e.jobQueueService.getDiagnostics(t),Promise.resolve(e.jobQueueService.getExecutionRegistrations()),e.daemonRegistry.getStatuses(),(e.readProcessSignals??Au)(),e.projectionRuntimeSupervisor.getDiagnostics(),Mu(e),e.operationalHealthRegistry.getChecks()]),p=n.status==="fulfilled"?n.value:null,m=o.status==="fulfilled"?o.value??null:null,f=s.status==="fulfilled"?s.value:[],g=a.status==="fulfilled"?a.value:{fileDescriptors:null,processCount:null,zombieCount:null},h=l.status==="fulfilled"?l.value:{status:"unhealthy",initialized:!1,trackedRoots:0,openCircuits:[]},S=[In("entity-database",i,"Entity database is accessible"),In("job-queue-database",n,"Job queue database is accessible"),ku(p),ju(p),Du(p,m),Ou(p),l.status==="fulfilled"?zu(h):{name:"projection-circuits",status:"degraded",message:P(l.reason)},d.status==="fulfilled"?Lu(d.value):{name:"projection-waves",status:"degraded",message:P(d.reason)},s.status==="fulfilled"?Uu(f):{name:"daemons",status:"degraded",message:P(s.reason)}],b=u.status==="fulfilled"?u.value:[{name:"plugin-operational-health",status:"degraded",message:"Plugin operational health is unavailable"}],y=[...S,...b];return{status:S.some((v)=>v.status==="unhealthy")?"not_ready":"ready",operationalStatus:y.some((v)=>v.status!=="healthy")?"degraded":"operational",checkedAt:new Date(t).toISOString(),checks:y,resources:{memory:{rssBytes:r.rss,heapUsedBytes:r.heapUsed,heapTotalBytes:r.heapTotal},fileDescriptors:g.fileDescriptors,processes:{total:g.processCount,zombies:g.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 Pn(){return{dataDir:"./data",cacheDir:"./cache",distDir:"./dist"}}function fe(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 We=c.strictObject({enabled:c.boolean().optional().describe("Serve HTTP; defaults to whether the selected bundles host the web surface"),preview:c.boolean().optional().describe("Serve the preview site; defaults to whether a site builder runs"),hostname:c.string().trim().min(1).optional().describe("Bind address; use 127.0.0.1 for isolated local tests"),productionDistDir:c.string().min(1).optional().describe("Directory of the production site, when no site builder writes it"),previewDistDir:c.string().min(1).optional().describe("Directory of the preview site, when no site builder writes it"),sharedImagesDir:c.string().min(1).optional().describe("Directory of shared optimized images")}),Dr=We.extend({enabled:c.boolean().default(!1),preview:c.boolean().default(!0),port:c.number().default(8080).describe("Port of the production listener")});var zr=Pn(),Bu=c.looseObject({label:c.string().min(1),pluralName:c.string().optional(),layout:c.string().optional(),paginate:c.boolean().optional(),pageSize:c.number().optional(),navigation:c.object({show:c.boolean().optional(),slot:c.enum(["primary","secondary"]).optional(),priority:c.number().optional()}).optional()});function Mr(){return fe(zr)}var Te=c.enum(["debug","info","warn","error"]);var Lr=c.object({name:c.string().default("brain-app"),version:c.string().default("1.0.0"),database:Ce,jobQueueDatabase:Ce,jobQueue:c.object({workerConcurrency:c.number().int().min(1).max(32).default(4)}).prefault({}),conversationDatabase:Ce,runtimeStateDatabase:Ce,embeddingDatabase:Ce,ai:c.object({providerKeys:qe.default({}),model:c.string().refine(Cn,{error:(e)=>`Unsupported model "${String(e.input)}"`}),embeddingModel:c.string().refine((e)=>Or(e)!==void 0,{error:(e)=>An(String(e.input))}).default(En),modelRuntimeUrl:c.string().url().optional(),answerModel:c.string().optional(),visionModel:c.string().optional(),imageModel:c.string().optional(),temperature:c.number().min(0).max(2).default(0.7),webSearch:c.boolean().default(!0),reasoningEffort:re.optional()}).superRefine((e,t)=>{if(e.answerModel&&ge(e.answerModel)!=="local")t.addIssue({code:"custom",path:["answerModel"],message:`answerModel must be a local: model, not ${e.answerModel}`});if(e.visionModel&&ge(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=[...ge(e.model)==="local"?[e.model]:[],...[e.answerModel,e.visionModel].filter((i)=>i!==void 0&&ge(i)==="local"),...e.imageModel&&Tn(e.imageModel).provider==="local"?[e.imageModel]:[],...Or(e.embeddingModel)?.provider==="local"?[e.embeddingModel]:[]];for(let i of r)t.addIssue({code:"custom",path:["modelRuntimeUrl"],message:`${i} needs modelRuntime.url`})}),embedding:c.object({enabled:c.boolean().default(!0)}),logging:c.object({level:Te.default("info"),format:c.enum(["text","json"]).default("text"),file:c.string().optional(),context:c.string().default("shell")}).prefault({level:"info",context:"shell"}),features:c.object({}).default({}),plugins:c.array(ft).default([]),dataDir:c.string().default("./brain-data"),gitBrokerSocket:c.string().min(1).optional(),gitBrokerCheckout:c.string().min(1).optional(),spaces:c.array(c.string()).default([]),siteBaseUrl:c.string().optional(),localSiteUrl:c.string().optional(),preferLocalUrls:c.boolean().default(!1),production:c.boolean().default(!1),themeCSS:c.string().default(""),entityDisplay:c.record(c.string(),Bu).optional(),profileKind:c.string().trim().min(1).optional(),http:Dr.prefault({})});function gt(e={}){let{plugins:t=[],permissions:r={},identity:i,profile:n,agentInstructions:o,evalHandlerRegistry:s,ai:a,logging:l,embedding:d,jobQueue:u,...p}=e,{entityDisplay:m,...f}=Lr.parse({...Mr(),...F(p),ai:F({...a}),logging:F({...l}),embedding:F({...d}),jobQueue:F({...u}),plugins:[]});return{...f,plugins:t,permissions:r,...F({entityDisplay:m,identity:i,profile:n,agentInstructions:o,evalHandlerRegistry:s})}}var L={NOTE:"note",BRAIN_CHARACTER:"brain-character",ANCHOR_PROFILE:"anchor-profile"},Je={KNOWLEDGE_QUERY:"shell:knowledge-query",BASE_ENTITY_DISPLAY:"shell:base-entity-display",CONTENT_GENERATION:"shell:content-generation"},Ur={ENTITIES:"shell:entities"};var $u=kn.extend({templateName:c.string()}),_u=c.object({slug:c.string()}),Fu="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.",Nu="Generate the content described in your instructions.";function Zu(e){return e instanceof c.ZodType}function Hu(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=Hu(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=$u.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 jn((S,b)=>i.getEntity(S,b),n.templateName,o.basePrompt):await ht(this.entityService,n.templateName,o.basePrompt);r?.throwIfAborted();let a=[s,n.prompt].filter(Boolean).join(" "),l=a.length>0&&o.useKnowledgeContext===!0,d=this.entityService.getWeightMap(),u=Object.keys(d).length>0,p=l?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),f=i?await this.readIdentities(i,n.representedIdentity):void 0,g=this.buildSystemPrompt(s,n,f);if(!Zu(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(g,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",Fu,"");return i.push("# Instructions",e),i.join(`
2
+ import{Qa as Ls,Ra as Us}from"./index-65426t8n.js";import{$a as mt,$b as _l,$e as Td,$j as zs,Ad as $s,Bg as xs,Bi as As,Cb as Ro,Cd as _s,Cg as Ke,Ci as ks,Db as Eo,Dd as ll,De as Ya,Dg as ac,Di as Bc,Ee as bt,Eg as cc,Ei as js,Fb as pe,Fd as Fl,Ff as Vd,Fi as Zo,Gb as me,Gd as fs,Gf as Yd,Gg as lc,Gi as Ds,Hb as Bd,Hf as Xd,Hg as dc,Ib as $d,Ic as kd,Id as ee,Ie as so,Ig as Od,Jb as _d,Jc as Ys,Jd as Hi,Je as vs,Jg as No,Ji as zo,Kb as Fd,Kc as ho,Ke as kn,Ki as Ho,Lb as Nd,Le as bs,Li as Wo,Mb as Zd,Mf as or,Mg as xr,Mi as qo,Nb as Hd,Nc as fd,Ne as Vs,Nf as Vc,Ng as Ps,Ni as Jo,Ob as Wd,Oc as uo,Oe as Xr,Of as co,Og as je,Pb as qd,Pf as au,Qb as mo,Qg as zd,Rb as fo,Re as Gd,Rg as Cs,Sb as go,Se as Qd,Sg as Rc,Te as Xo,Tg as Ga,Ub as Lt,Ue as es,Ug as xi,Vb as ps,Ve as ts,Vi as Go,Vj as Fs,Wa as jl,Wb as Rt,Wj as Qo,Xa as lt,Xb as ke,Xc as ms,Xe as rs,Yb as Se,Yd as Kc,Ye as xd,Zb as bd,Ze as Pd,Zj as Ns,_a as nn,_b as Tc,_e as Cd,_j as Ko,ab as be,af as jd,ag as jn,aj as vc,ak as Vo,bb as xo,bc as A,be as _,bf as Xl,bg as ht,bj as bc,cb as M,cc as fr,ce as Xs,cg as sc,cj as ft,dc as ei,dg as Dd,eb as se,ec as bl,ej as Md,fc as $o,fj as Os,gb as Po,gc as _o,hc as Fo,hg as Ni,ig as il,ii as qe,jc as Br,jg as nl,ji as un,jk as Zs,kc as $r,kg as Ss,kk as Ld,lg as Rs,li as Cn,mg as ws,mi as he,mk as Ms,ni as Tn,nk as mc,ob as Co,oi as En,ok as er,pi as Or,qc as gr,qi as Es,ri as An,tb as Jr,ub as Ct,ud as br,vb as vo,wb as bo,yb as So,yd as Ml,zb as Ud,zg as Is}from"./index-0gmp23pf.js";import{Ak as de,An as Ad,Ao as Ts,Bk as $e,Ck as Re,Cm as oo,Co as Ha,Dk as mr,Ek as Fe,En as ss,Fo as ue,Jo as Y,Om as ye,Qm as jt,Vm as Ks,Wm as Yt,Xl as Uo,Xn as qa,Zn as Ja,cm as Bo,dn as ic,en as nc,eo as re,fm as no,fo as V,hn as Kt,mo as gs,sm as Ce,so as hs,to as ys,ul as G,um as P,uo as wd,vm as Qe,wk as El,xk as Al,yk as ie,yl as Qa,zl as F,zn as vd}from"./index-1nk43d2s.js";import{Ko as Ye,Mo as Ee}from"./index-ddchamjy.js";import{At as Q,Hw as ne,Jw as Xt,Kw as oc,Nq as C,Nw as uc,Rs as oe,Ts as us,dt as j,rw as w,st as D}from"./index-5g395jvw.js";import{dy as c}from"./index-4m52m4bj.js";function jr(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 He(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=jr(e,t).reduce((a,l)=>a+l.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 Rn(e){let{config:t,services:r,bootTime:i,endpoints:n,interactions:o}=e,[s,a,l,d]=await Promise.all([r.entityService.getEntityCounts(mt("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:He(d,r.jobQueueService.getExecutionRegistrations()),ai:{model:t.ai.model,embeddingModel:r.embeddingService.identity.model},daemons:l,endpoints:n(),interactions:o()}}import{readdir as wn,readFile as Tu}from"fs/promises";var Eu=10;async function Au(e="/proc"){let t=null;try{t=(await wn(`${e}/self/fd`)).length}catch{}try{let i=(await wn(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 Tu(`${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 In(e,t,r){return t.status==="fulfilled"?{name:e,status:"healthy",message:r}:{name:e,status:"unhealthy",message:P(t.reason)}}function ku(e){if(!e)return{name:"job-worker",status:"degraded",message:"Worker session state is unavailable"};let t=e.workerSessions,r=He(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 ju(e){if(!e)return{name:"job-queue-progress",status:"degraded",message:"Queue progress state is unavailable"};let t=He(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 Du(e,t){if(!e||!t)return{name:"job-execution-inventory",status:"degraded",message:"Job execution inventory is unavailable"};let r=jr(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 Ou(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 zu(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 Mu(e){let t=e.entityService.getProjectionStore(),[r,i,n]=await Promise.all([t.getActiveWave(),t.getUnresolvedProjectionIncidentDiagnostics(Eu),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((l)=>l.status==="queued"||l.status==="failed"),a=(await Promise.all(s.map(async(l)=>{let d=l.jobId?await e.jobQueueService.getStatus(l.jobId):null;if(l.status!=="failed"&&d&&(d.status==="pending"||d.status==="processing"))return null;return{ruleId:l.ruleId,jobId:l.jobId,jobStatus:d?.status??"missing"}}))).filter((l)=>l!==null);return{waveId:r.id,batches:n,strandedRules:a,incidentCount:i.total,incidents:i.incidents}}function Lu(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 Uu(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 xn(e){let t=e.now?.()??Date.now(),r=(e.memoryUsage??process.memoryUsage)(),[i,n,o,s,a,l,d,u]=await Promise.allSettled([e.entityService.getEntityCounts(mt("runtime readiness database probe")),e.jobQueueService.getDiagnostics(t),Promise.resolve(e.jobQueueService.getExecutionRegistrations()),e.daemonRegistry.getStatuses(),(e.readProcessSignals??Au)(),e.projectionRuntimeSupervisor.getDiagnostics(),Mu(e),e.operationalHealthRegistry.getChecks()]),p=n.status==="fulfilled"?n.value:null,m=o.status==="fulfilled"?o.value??null:null,f=s.status==="fulfilled"?s.value:[],g=a.status==="fulfilled"?a.value:{fileDescriptors:null,processCount:null,zombieCount:null},h=l.status==="fulfilled"?l.value:{status:"unhealthy",initialized:!1,trackedRoots:0,openCircuits:[]},S=[In("entity-database",i,"Entity database is accessible"),In("job-queue-database",n,"Job queue database is accessible"),ku(p),ju(p),Du(p,m),Ou(p),l.status==="fulfilled"?zu(h):{name:"projection-circuits",status:"degraded",message:P(l.reason)},d.status==="fulfilled"?Lu(d.value):{name:"projection-waves",status:"degraded",message:P(d.reason)},s.status==="fulfilled"?Uu(f):{name:"daemons",status:"degraded",message:P(s.reason)}],b=u.status==="fulfilled"?u.value:[{name:"plugin-operational-health",status:"degraded",message:"Plugin operational health is unavailable"}],y=[...S,...b];return{status:S.some((v)=>v.status==="unhealthy")?"not_ready":"ready",operationalStatus:y.some((v)=>v.status!=="healthy")?"degraded":"operational",checkedAt:new Date(t).toISOString(),checks:y,resources:{memory:{rssBytes:r.rss,heapUsedBytes:r.heapUsed,heapTotalBytes:r.heapTotal},fileDescriptors:g.fileDescriptors,processes:{total:g.processCount,zombies:g.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 Pn(){return{dataDir:"./data",cacheDir:"./cache",distDir:"./dist"}}function ge(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 We=c.strictObject({enabled:c.boolean().optional().describe("Serve HTTP; defaults to whether the selected bundles host the web surface"),preview:c.boolean().optional().describe("Serve the preview site; defaults to whether a site builder runs"),hostname:c.string().trim().min(1).optional().describe("Bind address; use 127.0.0.1 for isolated local tests"),productionDistDir:c.string().min(1).optional().describe("Directory of the production site, when no site builder writes it"),previewDistDir:c.string().min(1).optional().describe("Directory of the preview site, when no site builder writes it"),sharedImagesDir:c.string().min(1).optional().describe("Directory of shared optimized images")}),Dr=We.extend({enabled:c.boolean().default(!1),preview:c.boolean().default(!0),port:c.number().default(8080).describe("Port of the production listener")});var zr=Pn(),Bu=c.looseObject({label:c.string().min(1),pluralName:c.string().optional(),layout:c.string().optional(),paginate:c.boolean().optional(),pageSize:c.number().optional(),navigation:c.object({show:c.boolean().optional(),slot:c.enum(["primary","secondary"]).optional(),priority:c.number().optional()}).optional()});function Mr(){return ge(zr)}var Te=c.enum(["debug","info","warn","error"]);var Lr=c.object({name:c.string().default("brain-app"),version:c.string().default("1.0.0"),database:Ce,jobQueueDatabase:Ce,jobQueue:c.object({workerConcurrency:c.number().int().min(1).max(32).default(4)}).prefault({}),conversationDatabase:Ce,runtimeStateDatabase:Ce,embeddingDatabase:Ce,ai:c.object({providerKeys:qe.default({}),model:c.string().refine(Cn,{error:(e)=>`Unsupported model "${String(e.input)}"`}),embeddingModel:c.string().refine((e)=>Or(e)!==void 0,{error:(e)=>An(String(e.input))}).default(En),modelRuntimeUrl:c.string().url().optional(),answerModel:c.string().optional(),visionModel:c.string().optional(),imageModel:c.string().optional(),temperature:c.number().min(0).max(2).default(0.7),webSearch:c.boolean().default(!0),reasoningEffort:re.optional()}).superRefine((e,t)=>{if(e.answerModel&&he(e.answerModel)!=="local")t.addIssue({code:"custom",path:["answerModel"],message:`answerModel must be a local: model, not ${e.answerModel}`});if(e.visionModel&&he(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=[...he(e.model)==="local"?[e.model]:[],...[e.answerModel,e.visionModel].filter((i)=>i!==void 0&&he(i)==="local"),...e.imageModel&&Tn(e.imageModel).provider==="local"?[e.imageModel]:[],...Or(e.embeddingModel)?.provider==="local"?[e.embeddingModel]:[]];for(let i of r)t.addIssue({code:"custom",path:["modelRuntimeUrl"],message:`${i} needs modelRuntime.url`})}),embedding:c.object({enabled:c.boolean().default(!0)}),logging:c.object({level:Te.default("info"),format:c.enum(["text","json"]).default("text"),file:c.string().optional(),context:c.string().default("shell")}).prefault({level:"info",context:"shell"}),features:c.object({}).default({}),plugins:c.array(ft).default([]),dataDir:c.string().default("./brain-data"),gitBrokerSocket:c.string().min(1).optional(),gitBrokerCheckout:c.string().min(1).optional(),spaces:c.array(c.string()).default([]),siteBaseUrl:c.string().optional(),localSiteUrl:c.string().optional(),preferLocalUrls:c.boolean().default(!1),production:c.boolean().default(!1),themeCSS:c.string().default(""),entityDisplay:c.record(c.string(),Bu).optional(),profileKind:c.string().trim().min(1).optional(),http:Dr.prefault({})});function gt(e={}){let{plugins:t=[],permissions:r={},identity:i,profile:n,agentInstructions:o,evalHandlerRegistry:s,ai:a,logging:l,embedding:d,jobQueue:u,...p}=e,{entityDisplay:m,...f}=Lr.parse({...Mr(),...F(p),ai:F({...a}),logging:F({...l}),embedding:F({...d}),jobQueue:F({...u}),plugins:[]});return{...f,plugins:t,permissions:r,...F({entityDisplay:m,identity:i,profile:n,agentInstructions:o,evalHandlerRegistry:s})}}var L={NOTE:"note",BRAIN_CHARACTER:"brain-character",ANCHOR_PROFILE:"anchor-profile"},Je={KNOWLEDGE_QUERY:"shell:knowledge-query",BASE_ENTITY_DISPLAY:"shell:base-entity-display",CONTENT_GENERATION:"shell:content-generation"},Ur={ENTITIES:"shell:entities"};var $u=kn.extend({templateName:c.string()}),_u=c.object({slug:c.string()}),Fu="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.",Nu="Generate the content described in your instructions.";function Zu(e){return e instanceof c.ZodType}function Hu(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=Hu(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=$u.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 jn((S,b)=>i.getEntity(S,b),n.templateName,o.basePrompt):await ht(this.entityService,n.templateName,o.basePrompt);r?.throwIfAborted();let a=[s,n.prompt].filter(Boolean).join(" "),l=a.length>0&&o.useKnowledgeContext===!0,d=this.entityService.getWeightMap(),u=Object.keys(d).length>0,p=l?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),f=i?await this.readIdentities(i,n.representedIdentity):void 0,g=this.buildSystemPrompt(s,n,f);if(!Zu(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(g,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",Fu,"");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
- `):Nu}formatRelevantEntity(e,t){let{entity:r,excerpt:i}=e,n=r.entityType,o=_u.safeParse(r.metadata),s=o.success?o.data.slug:r.id;if(this.siteBaseUrl&&t.hasRoute(n)){let a=t.generateUrl(n,s),l=`https://${this.siteBaseUrl}${a}`;return`[${n}] ${r.id}: ${i} (${l})`}return`[${n}] ${r.id}: ${i}`}}var Wu=c.object({entityType:c.string(),query:c.object({id:c.string()})});class vt{entityService;id=Ur.ENTITIES;name="Entity DataSource";description="Fetches entity content from the entity service";constructor(e){this.entityService=e}async fetch(e,t,r){let i=Wu.safeParse(e);if(!i.success){let a=i.error.issues.map((l)=>`${l.path.join(".")}: ${l.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 Dn(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 On(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 zn={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 Mn={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 Ln={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 Un={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 Bn={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"},updatedAt:{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 $n={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 _n={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 Fn={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 Nn={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=c.object({type:c.string()}).catchall(c.unknown()),tp=c.object({type:c.literal("object"),description:c.string().optional(),required:c.array(c.string()).optional(),properties:c.record(c.string(),Zn)}),rp=c.object({lexicon:c.literal(1),id:c.string(),defs:c.object({main:c.object({type:c.literal("record"),key:c.string().min(1),description:c.string().optional(),record:c.object({type:c.literal("object"),required:c.array(c.string()).optional(),properties:c.record(c.string(),Zn)})})}).catchall(tp)});function N(e){return rp.parse(e)}var O={"ai.rizom.brain.card":N(zn),"ai.rizom.brain.deck":N(Mn),"ai.rizom.brain.link":N(Ln),"ai.rizom.brain.note":N(Un),"ai.rizom.brain.post":N(Bn),"ai.rizom.brain.project":N($n),"ai.rizom.brain.series":N(_n),"ai.rizom.brain.socialPost":N(Fn),"ai.rizom.brain.topic":N(Nn)},ip="Additive optional fields are compatible; required-field, type, or constraint changes require a migration plan or new NSID.";function J(e){return{status:"approved",version:"1.0.0",revision:1,owner:"Rizom",steward:"Rizom protocol registry",projectionPackage:e,compatibility:ip}}var Hn={"ai.rizom.brain.card":J("@brains/atproto"),"ai.rizom.brain.deck":J("@brains/decks"),"ai.rizom.brain.link":J("@brains/link"),"ai.rizom.brain.note":J("@brains/note"),"ai.rizom.brain.post":J("@brains/blog"),"ai.rizom.brain.project":J("@brains/portfolio"),"ai.rizom.brain.series":J("@brains/series"),"ai.rizom.brain.socialPost":J("@brains/social-media"),"ai.rizom.brain.topic":J("@brains/topics")};function np(){return Object.values(O)}function op(e){if(!$r(O,e))return;return O[e]}function sp(){return Br(Hn).map(([e,t])=>({id:e,...t}))}var ap=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;function cp(e){let t=c.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)=>ap.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 lp(e,t){if(typeof e!=="string"||!e.startsWith("#"))return;let r=t[e.slice(1)];return r?.type==="object"?r:void 0}function qn(e,t){switch(e.type){case"string":return cp(e);case"integer":return c.number().int();case"boolean":return c.boolean();case"array":{let r=e.items?qn(e.items,t):c.unknown(),i=c.array(r);if(e.maxLength!==void 0)i=i.max(e.maxLength);return i}case"object":return Wn(e,t);case"ref":{let r=lp(e.ref,t);if(!r)return c.custom(()=>!1,{message:`unresolvable lexicon ref ${String(e.ref)}`});return c.lazy(()=>Wn(r,t))}case"blob":return c.custom(ie,{message:"expected blob"});default:return c.unknown()}}function Jn(e,t){let r=new Set(e.required??[]),i={};for(let[n,o]of Object.entries(e.properties??{})){let s=qn(o,t);i[n]=r.has(n)?s:s.optional()}return i}function Wn(e,t){return c.strictObject(Jn(e,t))}function U(e){return c.strictObject({...Jn(e.defs.main.record,e.defs),$type:c.literal(e.id).optional()})}var _r={"ai.rizom.brain.card":U(O["ai.rizom.brain.card"]),"ai.rizom.brain.deck":U(O["ai.rizom.brain.deck"]),"ai.rizom.brain.link":U(O["ai.rizom.brain.link"]),"ai.rizom.brain.note":U(O["ai.rizom.brain.note"]),"ai.rizom.brain.post":U(O["ai.rizom.brain.post"]),"ai.rizom.brain.project":U(O["ai.rizom.brain.project"]),"ai.rizom.brain.series":U(O["ai.rizom.brain.series"]),"ai.rizom.brain.socialPost":U(O["ai.rizom.brain.socialPost"]),"ai.rizom.brain.topic":U(O["ai.rizom.brain.topic"])};function dp(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(!ie(r))return;r=r[String(i)]}return r}function up(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"&&dp(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 pp(e,t){let r=U(e).safeParse(t);if(r.success)return;let i=r.error.issues[0];if(!i)throw r.error;throw Error(up(e,t,i))}var Gn="atproto:brain-card-discovered",Qn="atproto:brain-discovered",Kn="atproto:brain-card-refreshed",Vn="atproto:brain-card-unavailable",Yn="atproto:brain-card-conflict",Xn="atproto:jetstream-gap",mp=c.custom((e)=>_r["ai.rizom.brain.card"].safeParse(e).success),eo=c.object({repoDid:c.string().min(1),uri:c.string().min(1),cid:c.string().min(1),record:mp}).strict(),Fr=c.object({agentId:c.string().min(1),name:c.string().min(1),url:c.string().url(),status:c.enum(["discovered","approved","archived"]),repoDid:c.string().min(1).optional(),brainDid:c.string().min(1).optional(),anchorDid:c.string().min(1).optional(),cardUri:c.string().min(1).optional(),cardCid:c.string().min(1).optional()}).strict(),to=c.object({repoDid:c.string().startsWith("did:plc:"),observedAt:c.string().datetime(),staleAfter:c.string().datetime().optional(),reason:c.enum(["deleted","refresh-failed"]),error:c.string().min(1).optional()}).strict(),ro=c.object({domain:c.string().min(1),existingRepoDid:c.string().min(1).optional(),candidateRepoDid:c.string().startsWith("did:plc:"),observedAt:c.string().datetime(),reason:c.string().min(1)}).strict(),io=c.object({previousCursorTimeUs:c.number().int().nonnegative(),clampedCursorTimeUs:c.number().int().nonnegative(),observedAt:c.string().datetime()}).strict(),fp=he(Gn,eo),gp=he(Qn,Fr),hp=he(Kn,Fr),yp=he(Vn,to),vp=he(Yn,ro),bp=he(Xn,io);class St{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 Sp({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 wt(e,t,r){let i=await Rt(e,no,{actor:r},t);if(i.status==="unavailable")return null;if(i.status==="failed")throw oo(i.error,`Principal resolution failed: ${i.error.message}`);return i.data.principal}function ao(e,t){return new so(e,(r)=>wt(t,"shell:content-service",r))}var Nr=C.Service("@brains/conversation-service/ConversationService");function Rp(e){if(e.service){let r=e.service;return{service:r,close:()=>r.close()}}let t=co.createFreshFromConfig(e.logger,e.messageBus,e.dbConfig);try{return{service:t,close:()=>t.close()}}catch(r){throw t.close(),r}}function lo(e){return ne(Nr,()=>Rp(e))}var Zr=C.Service("@brains/entity-service/EntityService");function wp(e){return"close"in e&&typeof e.close==="function"}function po(e){return ne(Zr,()=>{let t=e.service??uo.createFresh(e);return{service:t,close:()=>{if(wp(t))t.close()}}})}var Ge=c.strictObject({dedupeKey:c.string().min(1).max(512),title:c.string().min(1),body:c.string().min(1),html:c.string().min(1).optional(),sensitivity:c.enum(["normal","secret"]).optional(),includeInInbox:c.boolean().optional()}),Hr=c.strictObject({alerts:c.array(Ge).optional()});var It="shell:recurring-check",qr=86400000,Ip=7*qr,xp=3*qr,Pp=c.strictObject({checkId:c.string().min(1)}),Cp=c.discriminatedUnion("kind",[c.strictObject({kind:c.literal("last-success"),checkId:c.string(),at:c.string().datetime()}),c.strictObject({kind:c.literal("alert"),checkId:c.string(),dedupeKey:c.string(),status:c.enum(["pending","suppressed","delivered","resolved"]),alert:Ge,observedAt:c.string().datetime(),includeInInbox:c.boolean().optional(),deliveredAt:c.string().datetime().optional(),resolvedAt:c.string().datetime().optional()})]);class Pt{brainId;scheduler;state;jobQueue;delivery;logger;clock;checks=new Map;pluginChecks=new Map;alertOperations=new ho;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:Cp});let t={validateAndParse:(r)=>{let i=Pp.safeParse(r);return i.success?i.data:null},process:async(r)=>{await this.runNow(r.checkId)}};this.jobQueue.registerHandler(It,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(It),this.handlerRegistered=!1}namespace(e){return{register:(t)=>this.register(e,t)}}register(e,t){Ap(e),yo(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 l=AbortSignal.any([t,a]),d=e.definition.deliverAlerts!==!1;if(d)await this.flushPendingAlerts(r);else await this.suppressPendingAlerts(r);l.throwIfAborted();let u=await e.definition.run({signal:l});l.throwIfAborted();let p=Hr.parse(u);for(let m of p.alerts??[])l.throwIfAborted(),await this.recordAlert(r,m,{deliver:d,includeInInbox:m.includeInInbox??e.definition.includeInInbox!==!1});l.throwIfAborted(),await this.state.set(this.lastSuccessKey(r),{kind:"last-success",checkId:r,at:this.currentTime().toISOString()})},o=w.tryPromise({try:(a)=>(i=n(a),i),catch:(a)=>a}),s=await w.runPromiseExit(o,{signal:t});if(i)await Promise.allSettled([i]);if(j.isSuccess(s))return!0;if(t.aborted)throw t.reason;throw oe.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=Wr(this.currentTime(),i).getTime()+i.periodMs,o=new AbortController,s={controller:o,settled:Promise.resolve()};e.enqueueRetry=s,s.settled=mo(()=>this.enqueue(r.id),t,{firstDelayMs:fo,maxDelayMs:go,giveUpAt:n,signal:o.signal,clock:this.clock,onRetry:(a,l)=>{this.logger.warn(`Failed to enqueue recurring check ${r.id}; retrying in ${l}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=Wr(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:It,data:{checkId:e},options:t})}async listOpenAlerts(){return(await this.state.list({keyPrefix:"alert:"})).flatMap((t)=>{let r=t.value;if(r.kind!=="alert"||r.status==="resolved")return[];if(!(r.includeInInbox??this.checks.get(r.checkId)?.definition.includeInInbox!==!1))return[];return[{id:t.key,checkId:r.checkId,title:r.alert.title,body:r.alert.body,observedAt:r.observedAt}]}).sort((t,r)=>t.observedAt.localeCompare(r.observedAt)||t.id.localeCompare(r.id))}async resolveOpenAlert(e){await this.alertOperations.run(e,async()=>{let t=await this.state.get(e),r=t?.kind==="alert"&&(t.includeInInbox??this.checks.get(t.checkId)?.definition.includeInInbox!==!1);if(t?.kind!=="alert"||t.status==="resolved"||!r)throw Error("Recurring-check inbox item is not open");await this.state.set(e,{...t,status:"resolved",resolvedAt:this.currentTime().toISOString()})})}async flushPendingAlerts(e){let t=await this.state.list({keyPrefix:this.alertKeyPrefix(e)});for(let r of t)await this.alertOperations.run(r.key,async()=>{let i=await this.state.get(r.key);if(i?.kind==="alert"&&(i.status==="pending"||i.status==="suppressed"))await this.deliverStoredAlert(r.key,i)})}async suppressPendingAlerts(e){let t=await this.state.list({keyPrefix:this.alertKeyPrefix(e)});for(let r of t)await this.alertOperations.run(r.key,async()=>{let i=await this.state.get(r.key);if(i?.kind==="alert"&&i.status==="pending")await this.state.set(r.key,{...i,status:"suppressed"})})}async recordAlert(e,t,r){let i=Ge.parse(t),n=this.alertKey(e,i.dedupeKey);await this.alertOperations.run(n,async()=>{let o=await this.state.get(n);if(o?.kind==="alert"){let 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,{idempotencyKey:Tp(e,t.observedAt)})===!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:${G(e)}`}alertKeyPrefix(e){return`alert:${G(e)}:`}alertKey(e,t){return`${this.alertKeyPrefix(e)}${G(t)}`}}function Tp(e,t){return`recurring-alert:${G(`${e}\x00${t}`)}`}function xt(e,t,r){let i=r==="daily"?qr:Ip,n=i/60000,o=G(`${e}\x00${t}\x00${r}`),s=Number.parseInt(o.slice(0,12),16)%n,a=s%60,l=Math.floor(s/60),d=l%24;return{expression:r==="daily"?`${a} ${d} * * *`:`${a} ${d} * * ${Math.floor(l/24)}`,offsetMs:s*60000,periodMs:i,anchorMs:r==="daily"?0:xp}}function Wr(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 Ep=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*:[a-z][a-z0-9-]*$/;function Ap(e){if(e.length<=200&&Ep.test(e))return;yo(e,"plugin ID")}function yo(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 x=vo("runtime_state_records",{namespace:Ct("namespace").notNull(),key:Ct("key").notNull(),value:Ct("value",{mode:"json"}).notNull(),createdAt:Jr("created_at").notNull(),updatedAt:Jr("updated_at").notNull()},(e)=>({pk:So({columns:[e.namespace,e.key]}),namespaceUpdatedAtIdx:bo("idx_runtime_state_namespace_updated_at").on(e.namespace,e.updatedAt)}));function wo(e){return Ro({url:e.url,schema:{runtimeStateRecords:x},authToken:e.authToken,authTokenEnv:"RUNTIME_STATE_DATABASE_AUTH_TOKEN"})}function Tt(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 kp}from"util";var jp=/^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,511}$/,To=512;class Gr{db;namespace;schema;now;constructor(e,t,r,i=()=>new Date){Dp(t),this.db=e,this.namespace=t,this.schema=r,this.now=i}async get(e){let t=ye(e),i=(await this.db.select().from(x).where(se(M(x.namespace,this.namespace),M(x.key,t))).limit(1))[0];if(!i)return null;return this.schema.parse(i.value)}async has(e){let t=ye(e);return(await this.db.select({key:x.key}).from(x).where(se(M(x.namespace,this.namespace),M(x.key,t))).limit(1)).length>0}async set(e,t){let r=ye(e),i=Tt(this.schema,t),n=i===null?ve`'null'`:i,o=this.now().getTime();await this.db.insert(x).values({namespace:this.namespace,key:r,value:n,createdAt:o,updatedAt:o}).onConflictDoUpdate({target:[x.namespace,x.key],set:{value:n,updatedAt:o}})}async setIfNotExists(e,t){let r=ye(e),i=Tt(this.schema,t),n=i===null?ve`'null'`:i,o=this.now().getTime(),s=await this.db.insert(x).values({namespace:this.namespace,key:r,value:n,createdAt:o,updatedAt:o}).onConflictDoNothing({target:[x.namespace,x.key]});return Number(s.rowsAffected)>0}async compareAndSet(e,t,r){let i=ye(e),n=Tt(this.schema,r),[o]=await this.db.select({value:x.value}).from(x).where(se(M(x.namespace,this.namespace),M(x.key,i))).limit(1);if(!o||!kp(this.schema.parse(o.value),t))return!1;let s=o.value===null?ve`'null'`:o.value,a=n===null?ve`'null'`:n,l=await this.db.update(x).set({value:a,updatedAt:this.now().getTime()}).where(se(M(x.namespace,this.namespace),M(x.key,i),M(x.value,s)));return Number(l.rowsAffected)===1}async delete(e){let t=ye(e),r=await this.db.delete(x).where(se(M(x.namespace,this.namespace),M(x.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(x).where(se(M(x.namespace,this.namespace),Io(e.keyPrefix)));return Number(t.rowsAffected)}async listRows(e){let{keyPrefix:t,afterKey:r,limit:i}=e;if(r!==void 0)ye(r);if(i!==void 0)c.number().int().min(1).max(1000).parse(i);let n=this.db.select({...xo(x),key:ve`CAST(${x.key} AS BLOB)`.mapWith((o)=>new TextDecoder("utf-8",{fatal:!0}).decode(o))}).from(x).where(se(M(x.namespace,this.namespace),Io(t),r!==void 0?Po(x.key,r):void 0)).orderBy(Co(x.key)).$dynamic();return i===void 0?n:n.limit(i)}}function Dp(e){if(!jp.test(e))throw Error(`Invalid runtime state namespace: ${e}. Use 1-512 alphanumeric, _, ., :, or - characters.`)}function ye(e){if(e.length===0||e.length>To)throw Error("Runtime state keys must be 1-512 characters long");return e}function Io(e){if(e===void 0)return;return Op(e),ve`substr(CAST(${x.key} AS BLOB), 1, length(CAST(${e} AS BLOB))) = CAST(${e} AS BLOB)`}function Op(e){if(e.length>To)throw Error("Runtime state key prefixes must be 512 characters or shorter");return e}class Et{db;client;logger;databaseUrl;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;static createFresh(e,t){return new Et(e,t??Ee.getInstance())}constructor(e,t){let{db:r,client:i,url:n}=wo(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 Eo(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 Gr(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 Qr=C.Service("@brains/runtime-state/RuntimeStateService");function Ao(e){return ne(Qr,()=>{let t=e.service??Et.createFresh(e.config,e.logger);return{service:t,close:()=>t.close()}})}async function Kr(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=Qe(r),t.warn(`Daemon ${e.name} failed to start: ${P(r)}`),r}}async function Vr(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=Qe(r),t.error(`Failed to stop daemon: ${e.name}`,r),r}}async function ko(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:P(t),lastCheck:new Date};return e.health=r,r}}function jo(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 Kr(t,this.logger);return}let r=w.runSync(D.make()),i=w.acquireRelease(w.promise(()=>Kr(t,this.logger)),()=>w.promise(()=>Vr(t,this.logger)));try{await w.runPromise(D.provide(i,r)),this.daemonScopes.set(e,r)}catch(n){throw await w.runPromise(D.close(r,j.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 Vr(t,this.logger);return}this.daemonScopes.delete(e),await w.runPromise(D.close(r,j.void))}async checkHealth(e){let t=this.daemons.get(e);if(!t)throw Error(`Daemon not registered: ${e}`);return ko(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(jo)}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??=Qe(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 zp=c.object({projectionId:c.string().min(1),reason:c.string().min(1),openedAt:c.number().int().nonnegative(),expiresAt:c.number().int().nonnegative()}),Mp=8,Lp=32,Up=128,Bp=5,$p=600000,_p=600000,Fp=1000,Np="shell.projection-circuits";class kt{operationContext;options;circuitStore;roots=new Map;reservedJobs=new Map;circuits=new Map;projections;static createFresh(e,t={}){return new kt(e,t)}constructor(e,t){this.operationContext=e,this.options={maxDerivationDepth:t.maxDerivationDepth??Mp,maxJobsPerRoot:t.maxJobsPerRoot??Lp,maxMutationsPerRoot:t.maxMutationsPerRoot??Up,repeatedTargetLimit:t.repeatedTargetLimit??Bp,retentionMs:t.retentionMs??$p,circuitOpenMs:t.circuitOpenMs??_p,maxTrackedRoots:t.maxTrackedRoots??Fp,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:Np,schema:zp})}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,l=(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:()=>l(!0),rollback:()=>l(!1)}}async assertMutationAdmission(e){let t=this.operationContext.current()?.provenance,r=t?.projectionId;if(!t||!r)return;let i=this.options.now();await this.prune(i),await this.requireProjection(r,i),await this.assertCircuitClosed(r,i);let n=this.getRootCounters(t.rootJobId,i);if(n.mutations++,n.updatedAt=i,n.mutations>this.options.maxMutationsPerRoot)await this.rejectAndOpen(r,`Root ${t.rootJobId} exceeded projection mutation budget ${this.options.maxMutationsPerRoot}`,i);let o=`${r}\x00${e.entityType}\x00${e.entityId}`,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,l])=>s.updatedAt-l.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 Zp={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 Ae(e){return Zp[e??"combined"]}var Do=[jt.created,jt.updated,jt.deleted];function Oo(e,t,r){let i=Do.map((o)=>e.subscribe(o,(s)=>(t.send({type:o,payload:s.payload}),{success:!0}))),n=t.onEvent((o)=>{if(!Do.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 Hp=20,Wp=0.5,qp=0.06,Jp=5;function Mo(e){return async({answer:t})=>{let i=(await e.entityService.search({query:t,options:{limit:Hp,minScore:Wp,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-qp).slice(0,Jp).map(({entity:o})=>zo(o,e))}}function Gp(e,t,r,i,n){return[$o,_o,Fo].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 l=o.name.replace("entity:","");n.debug(`${t} entity ${l}, cache refreshed`)}return{success:!0}}))}function Lo(e,t,r,i){return Gp(e,t,t,async()=>{await r(),await be(e,No,{entityType:t},"shell")},i)}async function Qp(e,t,r){let i=Kp(e.kind);if(!i)return null;try{let n=t.scoped({namespace:i,refKind:e.kind,routePath:""}),{record:o,content:s}=await n.read(e.id);return Go({...o,content:s,source:e})}catch(n){return r.debug("Skipped unavailable prior runtime upload",{uploadKind:e.kind,uploadId:e.id,error:P(n)}),null}}function Kp(e){return e===je.refKind?je.namespace:null}function Yo(e){let{config:t,entityService:r,logger:i,messageBus:n,aiService:o,mcpService:s,conversationService:a,runtimeUploadRegistry:l,disposables:d,executionOnly:u=!1}=e,p=Qo.createFresh(r,i,t.identity);d.push(...Lo(n,L.BRAIN_CHARACTER,()=>p.refreshCache(),i));let m=Ko.createFresh(r,i,t.profile),f=Vo.createFresh(i,async(v)=>{let R=await wt(n,"shell:canonical-identity-service",v).catch(()=>null);if(!R?.canonicalId)return null;return{userId:R.userId,canonicalId:R.canonicalId,displayName:R.displayName}}),g=Jo({guestPricing:Zo(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=Ho(t.name),S=new bt(t.entityDisplay),b={isCitable:(v)=>S.isCitable(v),urlFor:(v,R)=>S.generateUrl(v,R),siteBaseUrl:t.siteBaseUrl},y=Wo.createFresh(s,a,p,m,i,{agentFactory:g,turnEvents:qo(n),canonicalIdentityResolver:f,entityLinks:b,...e.generationUsage?{generationUsage:e.generationUsage}:{},...e.embeddingUsage?{embeddingUsage:e.embeddingUsage}:{},...t.embedding.enabled?{indexReadiness:r,guestAnswerSources:Mo({entityService:r,...b})}:{},uploadAttachmentResolver:(v)=>Qp(v,l,i),guestAskedBefore:async(v)=>{let R=await ke(n,Uo,v,"shell:agent-service");return R.status==="answered"?R.answers.find((I)=>I.hit)?.hit:void 0},agentContextProvider:async(v)=>{let R=await ke(n,Bo,v,"shell:agent-service");return R.status==="answered"?R.answers.flatMap((I)=>I.items):[]},...h?{assistantAgentId:h}:{},...t.agentInstructions&&{agentInstructions:t.agentInstructions}});if(d.push(...Lo(n,L.ANCHOR_PROFILE,()=>m.refreshCache(),i)),!u)d.push(n.subscribe(Ke.identityChanged,async()=>(y.invalidateAgent(),{success:!0})));return{identityService:p,profileService:m,canonicalIdentityService:f,agentService:y}}var Ve=C.Service("@brains/job-queue/JobQueueService"),Dt=C.Service("@brains/job-queue/BatchJobManager"),Ot=C.Service("@brains/job-queue/JobProgressMonitor"),zt=C.Service("@brains/job-queue/JobQueueWorker");function is(e){return ne(Ve,()=>{let t=e.service??Xo.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 ns(e){let t=!1,r=w.gen(function*(){let i=yield*Ve,n=e.batchJobManager??ts.createFresh(i,e.logger),o=e.jobProgressMonitor??rs.createFresh(i,e.messageBus,n,e.logger,e.progressMonitorMode),s=e.jobQueueWorker??es.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 C.make(Dt,n).pipe(C.add(Ot,o),C.add(zt,s))});return{layer:Q.effectContext(w.acquireRelease(r,(i)=>t?w.void:Vp(i))),abandon:()=>{t=!0}}}function Vp(e){let t=C.get(e,zt),r=C.get(e,Ot),i=C.get(e,Dt);return w.gen(function*(){let n=yield*w.exit(w.tryPromise({try:()=>t.stop(),catch:(l)=>l})),o=yield*w.exit(w.tryPromise({try:()=>r.stop(),catch:(l)=>l})),s=yield*w.exit(w.tryPromise({try:async()=>{await i.stop()},catch:(l)=>l})),a=[n,o,s].find(j.isFailure);if(a)yield*w.die(oe.squash(a.cause))})}function Yp(e,t=(r)=>process.exit(r)){return(r)=>{e.error("Job queue worker requires process restart",{reason:r,exitCode:1}),t(1)}}function Mt(e){let t=w.runSyncExit(D.close(e,j.void));if(j.isFailure(t))throw oe.squash(t.cause)}function os(e){let t=e.operationContext??Lt.createFresh(),r=w.runSync(D.make()),i,n;try{let o=w.runSync(Q.buildWithScope(is({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=C.get(o,Ve),a=w.runSync(D.make());i=a;let l=ns({messageBus:e.messageBus,logger:e.logger,operationContext:t,...e.projectionBatchScope&&{projectionBatchScope:e.projectionBatchScope},onWorkerUnhealthy:Yp(e.logger),workerConcurrency:e.workerConcurrency,...e.progressMonitorMode&&{progressMonitorMode:e.progressMonitorMode},...e.dependencies?.batchJobManager&&{batchJobManager:e.dependencies.batchJobManager},...e.dependencies?.jobProgressMonitor&&{jobProgressMonitor:e.dependencies.jobProgressMonitor},...e.dependencies?.jobQueueWorker&&{jobQueueWorker:e.dependencies.jobQueueWorker}});n=l;let d=w.runSync(Q.buildWithScope(l.layer.pipe(Q.provide(Q.succeed(Ve,s))),a)),u=C.get(d,Dt),p=C.get(d,Ot),m=C.get(d,zt),f,g=!1,h=!1;return{batchJobManager:u,jobProgressMonitor:p,jobQueueService:s,jobQueueWorker:m,closeRuntime:()=>(g=!0,f??=w.runPromise(D.close(a,j.void)),f),rollbackRuntime:()=>{if(g)return;g=!0,l.abandon(),Mt(a)},closeDatabase:()=>{if(h)return;h=!0,Mt(r)}}}catch(o){if(i)try{n?.abandon(),Mt(i)}catch(s){e.logger.warn("Failed to release partial job runtime acquisition",s)}try{Mt(r)}catch(s){e.logger.warn("Failed to release partial job database acquisition",s)}throw o}}function as(e){return{deliver:async(t,{idempotencyKey:r})=>{let i=await Rt(e,ss,{title:t.title,body:t.body,...t.html?{html:t.html}:{},...t.sensitivity?{sensitivity:t.sensitivity}:{},idempotencyKey:r},"shell.recurring-checks");if(i.status==="unavailable")return!1;if(i.status==="failed"||i.data.status!=="sent")throw Error("Recurring alert delivery failed");return!0}}}function ls(e){return{sourceId:"recurring-checks",displayName:"Recurring checks",list:async()=>(await e.listOpenAlerts()).map((t)=>({id:t.id,title:cs(t.title,160),summary:cs(t.body,1000),receivedAt:t.observedAt,urgency:"high",actions:[{id:"resolve",label:"Dismiss",confirm:!0}]})),act:async(t,r)=>{if(r!=="resolve")throw Error("Invalid recurring-check inbox action");await e.resolveOpenAlert(t)}}}function cs(e,t){return e.length<=t?e:e.slice(0,t)}function ds(e,t){if(t)return t;let r={debug:Ye.DEBUG,info:Ye.INFO,warn:Ye.WARN,error:Ye.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 Yr(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 Bs(e){let{config:t,dependencies:r,initializerLogger:i,lifecycle:n,processRole:o,peerChannel:s}=e;i.debug("Initializing Shell services");let a=Ae(o),l=ds(t,r?.logger),d=r?.operationContext??Lt.createFresh(),u=[],p=js.createFresh(!r?.embeddingService),m=r?.embeddingService??ks.createFresh({providerKeys:t.ai.providerKeys,profile:Es(t.ai.embeddingModel),runtimeUrl:t.ai.modelRuntimeUrl,logger:l,usage:p}),f=Ds.createFresh(),g=r?.aiService??As.createFresh(Yr(t),l,f),h=r?.entityRegistry??ms.createFresh(l),S=r?.messageBus??ps.createFresh(l,d);if(s)u.push(Oo(S,s,l));let b=r?.templateRegistry??gs.createFresh(l),y=r?.dataSourceRegistry??fs.createFresh(l),v=r?.renderService??ys.createFresh(b),R=r?.daemonRegistry??At.createFresh(l),I=r?.pluginManager??Ms.createFresh(l,R),E=r?.permissionService??new hs(t.permissions,{spaces:t.spaces,entityActionFloor:(q)=>h.getEntityTypeConfig(q).actionPolicy}),z=r?.profileKindRegistry??new zs(t.profileKind),Pe=r?.channelRegistry??new Rs,me=r?.inboxRegistry??new Is,te=r?.inboxFollowUpRegistry??new xs(l),du=r?.operationalHealthRegistry??new Os,uu=r?.accountSettingsRegistry??new Ss,pu=new ws,mu=new St,fu=r?.attachmentRegistry??Ps.createFresh(),yn=r?.runtimeUploadRegistry??Cs.createFresh({dataDir:t.dataDir,logger:l}),gu=n.buildLayer(Ao({config:De(t.runtimeStateDatabase),logger:l,...r?.runtimeStateService&&{service:r.runtimeStateService}})),Pr=C.get(gu,Qr),Cr=r?.projectionRuntimeSupervisor??kt.createFresh(d,{runtimeState:Pr}),vn=r?.mcpService??Ts.createFresh(S,l),Tr={},hu={runFreshBatchScope:(q)=>Tr.current?Tr.current.runFreshBatchScope(q):q()},ut=os({dependencies:r,jobQueueConfig:{...De(t.jobQueueDatabase),brainVersion:t.version},workerConcurrency:t.jobQueue.workerConcurrency,messageBus:S,operationContext:d,projectionBatchScope:hu,projectionAdmission:Cr,handlerRegistrationMode:a.handlerRegistrationMode,progressMonitorMode:a.progressMonitorMode,logger:l}),{batchJobManager:yu,jobProgressMonitor:vu,jobQueueService:Er,jobQueueWorker:bu}=ut;n.addSyncFinalizer(()=>ut.closeDatabase()),n.addSyncFinalizer(()=>ut.rollbackRuntime());let Ze=r?.recurringCheckService??new Pt({brainId:t.siteBaseUrl??t.dataDir,scheduler:new Ls,runtimeState:Pr,clock:w.runSync(us.Clock),jobQueue:Er,logger:l,delivery:as(S)});n.addSyncFinalizer(()=>Ze.abandon()),me.registerSource("shell.recurring-checks",ls(Ze)),n.addSyncFinalizer(()=>me.unregisterPlugin("shell.recurring-checks"));let bn=(q,kr)=>{if(!a.serves)return;R.register(q,kr,"shell"),n.addSyncFinalizer(()=>R.abandon(q))};bn("shell:recurring-checks",{start:()=>Ze.start(),stop:()=>Ze.stop()});let Su=n.buildLayer(po({embeddingService:m,embeddingsEnabled:t.embedding.enabled,entityRegistry:h,logger:l,jobQueueService:Er,messageBus:S,mutationAdmission:Cr,...r?.projectionRuntime?.now&&{projectionNow:r.projectionRuntime.now},dbConfig:De(t.database),embeddingDbConfig:De(t.embeddingDatabase),...r?.entityService&&{service:r.entityService}})),pt=C.get(Su,Zr);Tr.current=pt.getProjectionStore();let Ru=n.buildLayer(lo({dbConfig:De(t.conversationDatabase),logger:l,messageBus:S,...r?.conversationService&&{service:r.conversationService}})),Ar=C.get(Ru,Nr);bn("shell:guest-retention",Us({intervalMs:60000,logger:l,run:async()=>{await Ar.deleteExpiredGuestConversations(100)}})),n.addSyncFinalizer(()=>{for(let q of u.splice(0))try{q()}catch(kr){l.warn("Failed to dispose shell subscription",kr)}});let Sn=ao(E,S),wu=r?.contentService??new bs({logger:l,entityService:pt,aiService:g,templateRegistry:b,dataSourceRegistry:y,generationAuthorizer:new vs(E,Sn)}),{identityService:Iu,profileService:xu,canonicalIdentityService:Pu,agentService:Cu}=Yo({config:t,entityService:pt,embeddingService:m,embeddingUsage:p,...!r?.aiService?{generationUsage:f}:{},entityRegistry:h,logger:l,messageBus:S,aiService:g,mcpService:vn,conversationService:Ar,runtimeUploadRegistry:yn,disposables:u,executionOnly:!a.serves});return{logger:l,operationContext:d,projectionRuntimeSupervisor:Cr,disposables:u,entityRegistry:h,messageBus:S,renderService:v,daemonRegistry:R,pluginManager:I,templateRegistry:b,dataSourceRegistry:y,mcpService:vn,embeddingService:m,entityService:pt,aiService:g,conversationService:Ar,contentService:wu,callerAuthorizer:Sn,jobQueueService:Er,jobQueueWorker:bu,batchJobManager:yu,jobProgressMonitor:vu,jobServicesLifecycle:ut,permissionService:E,identityService:Iu,profileService:xu,canonicalIdentityService:Pu,profileKindRegistry:z,channelRegistry:Pe,inboxRegistry:me,inboxFollowUpRegistry:te,operationalHealthRegistry:du,accountSettingsRegistry:uu,authRegistry:pu,atprotoProjectionRegistry:mu,agentService:Cu,attachmentRegistry:fu,runtimeUploadRegistry:yn,runtimeStateService:Pr,recurringCheckService:Ze}}function Hs(e,t){e.register(Xr.name,Xr),t.debug("Shell system templates registered")}function Ws(e,t){e.register(Je.BASE_ENTITY_DISPLAY,{name:"base-entity-display",description:"Display template for base entities",schema:ei,formatter:new $s,requiredPermission:"public"}),t.debug("Base entity display template registered")}function qs(e,t){e.registerEntityType(L.NOTE,ei,new _s,{projectionSourceRole:"primary"}),t.debug("Fallback base entity adapter registered")}function Js(e,t){let r=new Fs;e.registerEntityType(L.BRAIN_CHARACTER,r.schema,r,{classification:"system",projectionSource:!1,projectionSourceRole:"excluded"}),t.debug("Brain character entity support registered")}function Gs(e,t){let r=new Ns;e.registerEntityType(L.ANCHOR_PROFILE,r.schema,r,{classification:"system",projectionSourceRole:"canonical"}),t.debug("Anchor profile entity support registered")}async function Qs(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:l}of r.getFailedPlugins()){let d=r.getPlugin(a);if(l instanceof Zs||d?.requiresDaemonStartup?.())throw l}i.debug("Plugin initialization complete")}class Ut{logger;config;processRole;peerChannel;static createFresh(e,t,r,i){return new Ut(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){Hs(e,this.logger)}registerBaseEntityDisplayTemplate(e){Ws(e,this.logger)}registerFallbackBaseEntity(e){qs(e,this.logger)}registerBrainCharacterSupport(e){Js(e,this.logger)}registerAnchorProfileSupport(e){Gs(e,this.logger)}async initializePlugins(e,t){await Qs({plugins:this.config.plugins,pluginManager:e,logger:this.logger,initOptions:t})}initializeServices(e,t){return Bs({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=Vs.createFresh(t,r);e.registerHandler(Ks.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 ti=c.strictObject({waveId:c.string().trim().min(1),ruleId:c.string().trim().min(1)});class ri{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=ti.safeParse(e);return t.success?t.data:null}async onTerminalError(e,t,r){let i=ti.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=ti.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,l,d]=await Promise.all([this.store.listWaveInputs(n.waveId),this.store.listWaveRules(n.waveId),this.store.getWave(n.waveId),this.getJobStatus(t)]);if(!l)throw Error(`Projection wave "${n.waveId}" does not exist`);if(l.status!=="running"&&l.status!=="superseded")throw Error(`Projection wave "${n.waveId}" is not active`);let u=a.find((I)=>I.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:l.cutoffGeneration};if(await this.recordDiagnostic({...p,event:"attempt-started"}),l.status==="superseded"){let I=await this.store.listPendingInputs();return await this.recordDiagnostic({...p,event:"apply-completed",applyOutcome:"superseded",highestPendingGeneration:Bt(I)}),{waveId:n.waveId,ruleId:o.id,outcome:"superseded",inputFingerprint:null,changedTargets:[]}}if(await this.store.supersedeWaveIfStale(n.waveId,this.now())){let I=await this.store.listPendingInputs();return await this.recordDiagnostic({...p,event:"apply-completed",applyOutcome:"superseded",highestPendingGeneration:Bt(I)}),await this.coordinator.continueAfterSupersession(n.waveId),{waveId:n.waveId,ruleId:o.id,outcome:"superseded",inputFingerprint:null,changedTargets:[]}}let m=tm(s,a,u.level),f=await o.selectInput({waveId:n.waveId,inputs:m},this.inputContext,i),g=o.fingerprint(f),h={...p,inputFingerprint:g,selectedSourceCount:em(f,m)};await this.recordDiagnostic({...h,event:"input-selected"});let S={ruleId:o.id,ruleVersion:o.version,inputFingerprint:g},b=await this.store.getRuleMemo(S);await this.recordDiagnostic({...h,event:"memo-resolved",memoHit:b!==null});let y;if(b)y=b.writeIntents;else{await this.recordDiagnostic({...h,event:"derive-started",memoHit:!1});try{y=await o.derive(f,this.executionContext,i),await this.recordDiagnostic({...h,event:"derive-completed",memoHit:!1})}catch(I){throw await this.recordDiagnostic({...h,event:i.aborted?"derive-cancelled":"derive-failed",memoHit:!1}),I}}let v=await this.store.applyRuleResult({waveId:n.waveId,ruleId:o.id,ruleVersion:o.version,inputFingerprint:g,writeIntents:y,completedAt:this.now()}),R=await this.store.listPendingInputs();if(!v)return await this.recordDiagnostic({...h,event:"apply-completed",memoHit:b!==null,applyOutcome:"superseded",highestPendingGeneration:Bt(R)}),await this.coordinator.continueAfterSupersession(n.waveId),{waveId:n.waveId,ruleId:o.id,outcome:"superseded",inputFingerprint:g,changedTargets:[]};return await this.recordDiagnostic({...h,event:"apply-completed",memoHit:b!==null,applyOutcome:"applied",highestPendingGeneration:Bt(R)}),await this.reconcileTargets(v.changedTargets),await this.coordinator.advanceActiveWave(n.waveId),{waveId:n.waveId,ruleId:o.id,outcome:"applied",inputFingerprint:g,changedTargets:v.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 em(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 tm(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 rm(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 Oe="shell:projection-rule";class ni{store;queue;graph;ruleById;graphFingerprint;createWaveId;beforeWaveCompletion;scheduleWakeup;onScheduledWakeupError;now;operationQueue=new Ys;scheduledWakeup;constructor(e){this.store=e.store,this.queue=e.queue,this.graph=e.graph,this.ruleById=om(e.graph,e.rules),this.graphFingerprint=sm(e.graph,e.rules),this.createWaveId=e.createWaveId,this.beforeWaveCompletion=e.beforeWaveCompletion??(async()=>{}),this.scheduleWakeup=e.scheduleWakeup??im,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(ii(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(ii(s))await this.startNextWaveInternal();return s}let t=await this.store.listPendingInputs();if(t.length===0)return this.cancelScheduledWakeup(),null;let r=nm(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(ii(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=ea(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:rm(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:Oe,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 ii(e){return e.status==="completed"||e.status==="superseded"}function im(e,t){let r=setTimeout(()=>{t()},e);return()=>clearTimeout(r)}function nm(e,t,r){let n=ea(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 om(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 sm(e,t){return Xs({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 ea(e,t,r){let i=new Map(e.projections.map((l)=>[l.id,l])),n=ta(e,(l)=>[l.from,l.to]),o=new Set(e.projections.filter((l)=>am(l,r)).map((l)=>l.id)),s=[...o];while(s.length>0){let l=s.flatMap((d)=>n.get(d)??[]).filter((d)=>i.has(d)&&!o.has(d));for(let d of l)o.add(d);s=[...new Set(l)].sort()}let a=cm(e,o);return[...o].map((l)=>{let d=i.get(l),u=t.get(l),p=a.get(l);if(!d||!u||p===void 0)throw Error(`Cannot plan projection rule "${l}"`);return{ruleId:l,targetType:d.targetType,level:p}}).sort((l,d)=>l.level-d.level||l.ruleId.localeCompare(d.ruleId))}function am(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 cm(e,t){let r=ta(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),l=a.length===0?0:Math.max(...a)+1;i.set(s,l),n.delete(s)}}return i}function ta(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 ra(e){let t=new ni({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 ri({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(Oe,r,"shell");let i=()=>{},n=()=>{};try{if(e.activationMode!=="executor"){let s=async(u)=>{if(u)await e.reconcileBatches?.();await t.startNextWave()},a,l=(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 l(!1)};i=e.setWakeup(d),await l(!0),n=(e.scheduleSweep??lm)(e.sweepIntervalMs??1000,async()=>{try{await l(!0)}catch(u){e.logger.error("Projection coordination sweep failed",u)}})}}catch(s){throw n(),i(),e.queue.unregisterHandler(Oe),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(Oe)}}}function lm(e,t){let r=setInterval(()=>{t()},e);return r.unref(),()=>clearInterval(r)}import{existsSync as Xm}from"fs";import{mkdir as ef,writeFile as tf}from"fs/promises";import{join as rf,resolve as Va}from"path";var ia=5000;async function na(e,t){let r=Promise.resolve(e.stop(!1)),i,n=new Promise((s)=>{i=setTimeout(()=>s("deadline"),Math.max(0,t.drainMs))});if(await Promise.race([r.then(()=>"drained"),n]).finally(()=>clearTimeout(i))==="drained")return;t.logger.warn(`${t.label} drain passed ${t.drainMs}ms with ${e.pendingRequests??"unknown"} request(s) in flight; closing them`),r.catch(()=>{return}),Promise.resolve(e.stop(!0)).catch(()=>{return})}function oa(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 Z,join as Qm,sep as Km}from"path";var sa=Symbol();var aa=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,(r)=>r.toLowerCase())}}).formData();var dm=1e4,$t=(e)=>("headers"in e),da=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 um(e,{all:r,dot:i});return{}};async function um(e,t){if(!$t(e)&&e.bodyCache.formData)return ca(await e.bodyCache.formData,t);let r=$t(e)?e.headers:e.raw.headers,i=await e.arrayBuffer(),n=aa(i,r.get("Content-Type")||"");if(!$t(e))e.bodyCache.formData=n;let o=await n;if(o)return ca(o,t);return{}}function ca(e,t){let r=Object.create(null),i={count:0};if(e.forEach((n,o)=>{if(!(t.all||o.endsWith("[]")))r[o]=n;else pm(r,o,n)}),t.dot)Object.entries(r).forEach(([n,o])=>{if(n.includes("."))mm(r,n,o,i),delete r[n]});return r}var pm=(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]},mm=(e,t,r,i)=>{if(/(?:^|\.)__proto__\./.test(t))return;let n=e,o=t.split(".",34);if(o.length>33)la();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++>=dm)la();n[s]=Object.create(null)}n=n[s]}})},la=()=>{throw Error("Nesting limit exceeded")};var si=(e)=>{let t=e.split("/");if(t[0]==="")t.shift();return t},ua=(e)=>{let{groups:t,path:r}=fm(e),i=si(r);return gm(i,t)},fm=(e)=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,i)=>{let n=`@${i}`;return t.push([n,r]),n}),{groups:t,path:e}},gm=(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},_t={},pa=(e,t)=>{if(e==="*")return"*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let i=`${e}#${t}`;if(!_t[i])if(r[2])_t[i]=t&&t[0]!==":"&&t[0]!=="*"?[i,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)];else _t[i]=[e,r[1],!0];return _t[i]}return null},ma=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,(r)=>{try{return t(r)}catch{return r}})}},ai=(e)=>ma(e,decodeURI),ci=(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),l=t.slice(r,a);return ai(l.includes("%25")?l.replace(/%25/g,"%2525"):l)}else if(n===63||n===35)break}return t.slice(r,i)};var fa=(e)=>{let t=ci(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},ae=(e,t,...r)=>{if(r.length)t=ae(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?ma(e,hm):e,oi=(e)=>{if(e.indexOf("+")!==-1)e=e.replace(/\+/g," ");return Nt(e)},ga=(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 l=e.charCodeAt(a+t.length+1);if(l===61){let d=a+t.length+2,u=e.indexOf("&",d);return oi(e.slice(d,u===-1?void 0:u))}else if(l==38||isNaN(l))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),l=e.indexOf("=",s);if(l>a&&a!==-1)l=-1;let d=e.slice(s+1,l===-1?a===-1?void 0:a:l);if(n)d=oi(d);if(s=a,d==="")continue;let u;if(l===-1)u="";else if(u=e.slice(l+1,a===-1?void 0:a),n)u=oi(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},ha=ga,ya=(e,t)=>ga(e,t,!0),hm=decodeURIComponent;var va=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 ha(this.url,e)}queries(e){return ya(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 da(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[sa](){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 ba={Stringify:1,BeforeStream:2,Stream:3},Sa=(e,t)=>{let r=new String(e);return r.isEscaped=!0,r.callbacks=t,r};var li=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((l)=>li(l,t,!1,i,n))).then(()=>n[0]));if(r)return Sa(await s,o);else return s};var ym="text/plain; charset=UTF-8",di=(e,t)=>({"Content-Type":e,...t}),Xe=(e,t)=>new Response(e,t),ui=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 va(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||=Xe(null,{headers:this.#a??=new Headers})}set res(e){if(this.#n&&e){e=Xe(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=Xe(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 Xe(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,di(ym,r));json=(e,t,r)=>this.#s(JSON.stringify(e),t,di("application/json",r));html=(e,t,r)=>{let i=(n)=>this.#s(n,t,di("text/html; charset=UTF-8",r));return typeof e==="object"?li(e,ba.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??=()=>Xe(),this.#l(this))};var pi=(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 l,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{l=await u(i,()=>s(a+1))}catch(p){if(p instanceof Error&&t)i.error=p,l=await t(p,i),d=!0;else throw p}else if(i.finalized===!1&&r)l=await r(i);if(l&&(i.finalized===!1||d))i.res=l;return i}};var Ra=["get","post","put","delete","options","patch","query"],Zt="Can not add a route since the matcher is already built.",Ht=class extends Error{};var mi="__COMPOSED_HANDLER";var vm=(e)=>e.text("404 Not Found",404),wa=(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)},Ia=class e{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...Ra,"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((l)=>{this.#o(a,this.#t,l)}),this}}),this.on=(n,o,...s)=>{for(let a of[o].flat()){this.#t=a;for(let l of[n].flat()){let d=l.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??ci:fa}#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=vm;errorHandler=wa;route(t,r){let i=this.basePath(t);return r.routes.map((n)=>{let o;if(r.errorHandler===wa)o=n.handler;else o=async(s,a)=>(await pi([],r.errorHandler)(s,()=>n.handler(s,a))).res,o[mi]=n.handler;i.#o(n.method,n.path,o,n.basePath)}),this}basePath(t){let r=this.#e();return r._basePath=ae(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=(l)=>l;else n=i.replaceRequest;let s=o?(l)=>{let d=o(l);return Array.isArray(d)?d:[d]}:(l)=>{let d=void 0;try{d=l.executionCtx}catch{}return[l.env,d]};n||=(()=>{let l=ae(this._basePath,t),d=l==="/"?0:l.length;return(u)=>{let p=new URL(u.url);return p.pathname=this.getPath(u).slice(d)||"/",new Request(p,u)}})();let a=async(l,d)=>{let u=await r(n(l.req.raw),...s(l));if(u)return u;await d()};return this.#o("ALL",ae(t,"*"),a),this}#o(t,r,i,n){r=ae(this._basePath,r);let o={basePath:n!==void 0?ae(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 ui(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 l=pi(s[0],this.errorHandler,this.#r);return(async()=>{try{let d=await l(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${ae("/",t)}`,r),i,n)};fire=()=>{addEventListener("fetch",(t)=>{t.respondWith(this.#n(t.request,t,void 0,t.request.method))})}};var k=()=>Object.create(null);var Wt=[];function fi(e,t){let r=this.buildAllMatchers(),i=(n,o)=>{let s=r[n]||r.ALL,a=s[2][o];if(a)return a;let l=o.match(s[0]);if(!l)return[[],Wt];let d=l.indexOf("",1);return[s[1][d],l]};return this.match=i,i(e,t)}var gi="[^/]+";var hi="(?:|/.*)",ce=Symbol(),xa=new Set(".\\+*[^]$()");function bm(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 Pa=class e{#t;#e;#r=k();insert(t,r,i,n,o){let s=this;for(let a=0,l=t.length;a<l;a++){let d=t[a],u=d.length===1?d==="*"?a===l-1?["","",".*"]:["","",gi]:null:d==="/*"?["","",hi]:d.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),p;if(u){let m=u[1],f=u[2]||"[^/]+";if(m&&u[2]){if(f===".*")throw ce;if(f=f.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(f))throw ce;if(f.length===1&&xa.has(f))throw ce}if(p=s.#r[f],!p){if(f!==".*"&&f!=="(?:|/.*)"){for(let g in s.#r)if((f.length>1||g.length>1)&&g!==".*"&&g!=="(?:|/.*)")throw ce}p=s.#r[f]=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 ce;p=s.#r[d]=new e}s=p}if(s.#t!==void 0)throw ce;s.#t=o?-1:r}buildRegExpStr(){let t=Object.keys(this.#r).sort(bm).map((r)=>{let i=this.#r[r],n=i.buildRegExpStr();return n===""?"":(typeof i.#e==="number"?`(${r})@${i.#e}`:xa.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 yi=class{#t={varIndex:0};#e=new Pa;#r=0;paths=k();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,(l)=>{let d=`@\\${s}`;return i[s]=[d,l],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 l=o.length-1;l>=0;l--)if(o[l].indexOf(a)!==-1){o[l]=o[l].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 Ca=k();function Ta(e){return Ca[e]??=new RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(t,r)=>r?`\\${r}`:t==="/*"?hi:t==="*"?".*":`/:${gi}`)}$`)}function qt(e,t){for(let r of Object.keys(e).sort((i,n)=>n.length-i.length))if(Ta(r).test(t))return[...e[r]]}var Jt=class{name="RegExpRouter";#t;#e;#r;constructor(){this.#t={["ALL"]:k()},this.#e={["ALL"]:k()},this.#r={["ALL"]:new yi}}#o(e,t){try{this.#r[e].insert(t,!/\*|\/:/.test(t))}catch(r){throw r===ce?new Ht(t):r}}add(e,t,r){let i=this.#t,n=this.#e;if(!i)throw Error(Zt);if(!i[e]){this.#r[e]=new yi;for(let a of[i,n]){a[e]=k();for(let l in a.ALL)a[e][l]=[...a.ALL[l]],this.#o(e,l)}}if(t==="/*")t="*";let o=e==="ALL"?Object.keys(i):[e];if(/\*$/.test(t)){let a=Ta(t);for(let l of o)if(!i[l][t])this.#o(l,t),i[l][t]=qt(i[l],t)||qt(i.ALL,t)||[];for(let l of[i,n])for(let d of o)for(let u in l[d])a.test(u)&&l[d][u].push([r,t]);return}let s=Ft(t)||[t];for(let a of s)for(let l of o){if(!n[l][a])this.#o(l,a),n[l][a]=qt(i[l],a)||qt(i.ALL,a)||[];n[l][a].push([r,a])}}match=fi;buildAllMatchers(){let e=k();for(let t of Object.keys(this.#e))e[t]=this.#i(t);return this.#t=this.#e=this.#r=void 0,Ca=k(),e}#i(e){let t=this.#t[e],r=this.#e[e],i=this.#r[e],n=k(),o=[],[s,a,l]=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(([f])=>[f,k()]),Wt];continue}o[m[0]]=p.map(([f,g])=>[f,i.paths[g][1].reduceRight((h,[S],b)=>(h[S]=l[m[1][b][1]],h),k())])}return[s,a.map((d)=>o[d]),n]}};var Ea=class{name="SmartRouter";#t=[];#e=[];constructor(e){this.#t=e.routers}add(e,t,r){if(!this.#e)throw Error(Zt);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 l=0,d=i.length;l<d;l++)a.add(...i[l]);s=a.match(e,t)}catch(l){if(l instanceof Ht)continue;throw l}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 vi=k(),Sm=0,Aa=class e{#t=[];#e=k();#r=[];#o;#i=vi;insert(t,r,i){let n=this,o=ua(r),s=new Set,a=0;for(let l of o){let d=o[++a],u=pa(l,d)||(d===void 0&&l&&l.indexOf("*")===l.length-1?l:null),p=Array.isArray(u),m=p?u[0]:u||l,f=n.#e[m]||=new e;if(u&&!f.#o)f.#o=u,n.#r.push(f);if(n=f,p)s.add(u[1])}n.#t.push({[t]:{handler:i,possibleKeys:[...s],score:++Sm}})}#n(t,r,i,n,o){for(let s=0,a=r.#t.length;s<a;s++){let l=r.#t[s],d=l[i]||l.ALL;if(d){d.params=k(),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=vi;let n=[this],o=si(r),s=[],a=o.length,l=null;for(let d=0;d<a;d++){let u=o[d],p=d===a-1,m=[];for(let g=0,h=n.length;g<h;g++){let S=n[g],b=S.#e[u];if(b)if(b.#i=S.#i,p){if(b.#e["*"])this.#n(i,b.#e["*"],t,S.#i);this.#n(i,b,t,S.#i)}else m.push(b);for(let y of S.#r){let v=y.#o,R=S.#i===vi?{}:{...S.#i};if(typeof v==="string"){if(v==="*"||u.startsWith(v.slice(0,-1))){if(this.#n(i,y,t,S.#i),v==="*")y.#i=R,m.push(y)}continue}let[,I,E]=v;if(!u&&E===!0)continue;if(E!==!0){if(!l){l=[];let me=r[0]==="/"?1:0;for(let te=0;te<a;te++)l[te]=me,me+=o[te].length+1}let z=r.slice(l[d]),Pe=E.exec(z);if(Pe){if(R[I]=Pe[0],this.#n(i,y,t,S.#i,R),Pe[0].length===z.length&&y.#e["*"])this.#n(i,y.#e["*"],t,S.#i,R);for(let me in y.#e){y.#i=R;let te=Pe[0].match(/\//g)?.length??0;(s[te]||=[]).push(y);break}continue}}if(E===!0||E.test(u))if(R[I]=u,p){if(this.#n(i,y,t,R,S.#i),y.#e["*"])this.#n(i,y.#e["*"],t,R,S.#i)}else y.#i=R,m.push(y)}}let f=s.shift();n=f?m.concat(f):m}if(i[1])i.sort((d,u)=>d.score-u.score);return[i.map(({handler:d,params:u})=>[d,u])]}};var bi=class{name="TrieRouter";#t=new Aa;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 Si=class extends Ia{constructor(e={}){super(e);this.router=e.router??new Ea({routers:[new Jt,new bi]})}};var Gt=(e)=>("server"in e.env)?e.env.server:e.env;var ze=/^\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 Ri=(e,t=Rm)=>{let r=e.match(/\.([a-zA-Z0-9]+?)$/);if(!r)return;return t[r[1].toLowerCase()]};var Rm={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 ka=(...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 ja={br:".br",zstd:".zst",gzip:".gz"},wm=Object.keys(ja),Im="index.html",Da=(e)=>{let t=e.root??"./",r=e.path,i=e.join??ka;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=ai(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,Im);let l=e.getContent,d=await l(a,n);if(d instanceof Response)return n.newResponse(d.body,d);if(d!=null){let u=e.mimes&&Ri(a,e.mimes)||Ri(a);if(n.header("Content-Type",u||"application/octet-stream"),e.precompressed&&(!u||ze.test(u))){let p=new Set(n.req.header("Accept-Encoding")?.split(",").map((m)=>m.trim()));for(let m of wm){if(!p.has(m))continue;let f=await l(a+ja[m],n);if(f){d=f,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 xm}from"fs/promises";import{join as Pm}from"path";var wi=(e={})=>async function(r,i){return Da({...e,getContent:async(s)=>{let a=Bun.file(s);return await a.exists()?a:null},join:Pm,isDir:async(s)=>{let a;try{a=(await xm(s)).isDirectory()}catch{}return a}})(r,i)};var Oa="x-hono-disable-ssg",rI=(()=>{try{return new Response("SSG is disabled",{status:404,headers:{[Oa]:"true"}})}catch{return null}})();var{write:WI}=Bun;var za=(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 Am=za((e,t)=>{let r=Gt(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 La=(e)=>e===32||e===9||e===10||e===13,Qt=(e,t)=>{while(t<e.length){if(!La(e.charCodeAt(t)))break;t++}return t},et=(e,t)=>{while(t>0){if(!La(e.charCodeAt(t-1)))break;t--}return t},Ma=(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]},km=(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},jm=(e,t)=>{t=Qt(e,t);let r=t,i,n,o=!1;while(r<e.length){let l=e.charCodeAt(r);if(l===61){i=e.slice(t,et(e,r)),r++;break}if(l===59)return[r+1,void 0,void 0,!0];if(l===44)return[r+1,void 0,void 0,!1];r++}if(i===void 0)return[r,void 0,void 0,!1];if(r=Qt(e,r),e.charCodeAt(r)===61){let l=Ma(e,r+1);return[l[0],i,void 0,l[1]]}let s=!1,a=r;while(r<e.length){let l=e.charCodeAt(r);if(s&&l===92)r++;else if(l===34){if(s){let d=Qt(e,r+1),u=e.charCodeAt(d);if(d<e.length&&!(u===59||u===44)){let p=Ma(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&&(l===59||l===44)){if(n=e.slice(a,et(e,r)),l===59)o=!0;r++;break}r++}return[r,i,n??e.slice(a,et(e,r)),o]},Dm=(e,t)=>{let r={type:"",params:Object.create(null),q:1};t=Qt(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,et(e,i)),i++,a===44)return[i,r.type?r:void 0];if(!r.type)return[km(e,i),void 0];break}i++}if(!r.type)return r.type=e.slice(t,et(e,e.length)),[e.length,r.type?r:void 0];let n,o,s;while(i<e.length){if([i,n,o,s]=jm(e,i),n&&o)r.params[n]=o;if(!s)break}return[i,r]},Ua=(e)=>{if(!e)return[];let t=[],r=0,i,n=!1,o;while(r<e.length)if([r,i]=Dm(e,r),i){if(i.q=Om(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},Om=(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 zm=["gzip","deflate"],Mm=/(?:^|,)\s*?no-transform\s*?(?:,|$)/i,Lm=(e,t)=>{if(e===void 0)return;let r=Ua(e),i=r.find((o)=>o.type==="*")?.q,n;for(let o of t){let s=r.find((l)=>l.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},Um=/(?:^|,)\s*accept-encoding\s*(?:,|$)/i,Ba=(e)=>{let t=e?.threshold??1024,r=e?.encoding?[e.encoding]:zm,i=e?.contentTypeFilter??ze,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 l=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"||l&&Number(l)<t||!n(s.res)||!Bm(s.res))return;let d=s.res.headers.get("Vary");if(d!=="*"&&!(d&&Um.test(d)))s.header("Vary",d?`${d}, Accept-Encoding`:"Accept-Encoding");let u=s.req.header("Accept-Encoding"),p=Lm(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 f=s.res.headers.get("ETag");if(f&&!f.startsWith("W/"))s.res.headers.set("ETag",`W/${f}`)}},Bm=(e)=>{let t=e.headers.get("Cache-Control");return!t||!Mm.test(t)};import{Readable as $a}from"stream";import{createDeflate as $m,createGzip as _m}from"zlib";var Fm=["gzip","deflate"],Nm=/(?:^|,)\s*?no-transform\s*?(?:,|$)/i,_a=(e)=>{if(typeof CompressionStream<"u")return Ba(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||!Zm(i.res)||!Hm(i.res))return;let s=i.req.header("Accept-Encoding"),a=e?.encoding??Fm.find((l)=>s?.includes(l));if(!a||!i.res.body)return;try{let l=a==="gzip"?_m():$m(),d=$a.fromWeb(i.res.body).pipe(l),u=$a.toWeb(d);i.res=new Response(u,i.res),i.res.headers.delete("Content-Length"),i.res.headers.set("Content-Encoding",a)}catch(l){console.error("Compression error:",l)}}},Zm=(e)=>{let t=e.headers.get("Content-Type");return t&&ze.test(t)},Hm=(e)=>{let t=e.headers.get("Cache-Control");return!t||!Nm.test(t)};var Wm=(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 Fa=async(e,t)=>{if(!e)return null;let r=void 0,i,n=0,o=async(a)=>{r=await t(Wm(r,a))},s=e.getReader();for(;;){let{value:a,done:l}=await s.read();if(l)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 f=new Uint8Array(new ArrayBuffer(Math.min(262144,Math.max(p,i.byteLength*2))));f.set(i.subarray(0,n)),i=f}i.set(a.subarray(d),n)}n=p;break}let m=262144-n;if(i?.byteLength!==262144){let f=new Uint8Array(new ArrayBuffer(262144));if(i)f.set(i.subarray(0,n));i=f}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 qm=["cache-control","content-location","date","etag","expires","vary"],Na=(e)=>e.replace(/^W\//,"");function Jm(e,t){return t!=null&&t.split(",").some((r)=>Na(r.trim())===Na(e))}function Gm(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??qm).map((n)=>n.toLowerCase())),r=e?.weak??!1,i=Gm(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 l=o.res,d=l.headers.get("ETag");if(!d){if(!i)return;let u=await Fa(l.clone().body,i);if(u===null)return;d=r?`W/"${u}"`:`"${u}"`}if(a==="*"||Jm(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[f,g]of m.entries())s[f]=g}let a=await t(e,s),l=typeof a==="object"&&a!==null&&"data"in a?a.data:a,d=Ha.safeParse(l),u=d.success?d.data:l,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 tt(e,t){return e===t||e.startsWith(t+Km)}var Wa="public, max-age=31536000, immutable";function Vm(e){return e.getRoutes?.()??[]}var Ym=255;class Vt{logger;options;routes=Object.freeze([]);productionServer=null;stopping=!1;transport=new WeakMap;async fillSitePage(e,t,r){let i=r.slot;if(!i)return;let n=Z(e,`.${t}`,"index.html");if(!tt(n,Z(e)))return;let o=Bun.file(n);if(!await o.exists())return;let s=`<div ${Ga}="${i.name}"></div>`,a=await o.text();if(!a.includes(s))return;let l=new Headers(r.headers);return l.delete("Content-Length"),l.delete("Content-Encoding"),l.delete("ETag"),l.set("Content-Type","text/html; charset=utf-8"),new Response(a.replace(s,()=>i.html),{status:r.status,headers:l})}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:Z(process.cwd(),e.productionDistDir),sharedImagesDir:Z(process.cwd(),e.sharedImagesDir),...e.previewDistDir&&{previewDistDir:Z(process.cwd(),e.previewDistDir)}}}async start(){if(this.productionServer){this.logger.warn("Webserver already running");return}this.stopping=!1,this.routes=Object.freeze([...Vm(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??Ym,fetch:async(i,n)=>{if(this.stopping)return new Response("Shutting down",{status:503,headers:{Connection:"close","Retry-After":"5"}});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(){let e=this.productionServer;if(e){this.stopping=!0;try{await na(e,{drainMs:this.options.shutdownDrainMs??ia,logger:this.logger,label:"Webserver"})}finally{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 Si;if(t.onError((r,i)=>{if(this.stopping)return this.logger.debug(`Request ended by the shutdown: ${i.req.method} ${i.req.path}: ${P(r)}`),i.text("Shutting down",503);if("getResponse"in r){let n=r.getResponse();return i.newResponse(n.body,n)}return console.error(r),i.text("Internal Server Error",500)}),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:P(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("/*",_a());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",Wa);else r.header("Cache-Control",e.defaultCache)}),t.use("/*",async(r,i)=>{if(r.req.path===Kt)return r.notFound();return i()}),t.use("/*",this.createCleanUrlMiddleware(e.distDir)),t.use("/*",wi({root:e.distDir})),t.get(qa,(r)=>r.body(Ja,200,{"Content-Type":"image/svg+xml; charset=utf-8","Cache-Control":"public, max-age=86400"})),t.notFound(async(r)=>{let i=Bun.file(Qm(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:P(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=oa(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 xi&&s.slot)return await this.fillSitePage(t.distDir,i,s)??s;if(r==="GET"&&s instanceof xi&&s.status===200){let a=Z(t.distDir,`.${i}`,"index.html");if(tt(a,Z(t.distDir))){let l=Bun.file(a);if(await l.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(l,{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=Z(this.options.sharedImagesDir,r);if(!tt(i,this.options.sharedImagesDir))return null;let n=Bun.file(i);if(!await n.exists())return null;return new Response(n,{headers:{"Cache-Control":Wa}})}createCleanUrlMiddleware(e){return async(t,r)=>{let i=t.req.path;if(i.includes(".")||i==="/"){await r();return}let n=Z(e,`.${i}`,"index.html");if(!tt(n,e)){await r();return}let o=Bun.file(n);if(await o.exists())return t.html(await o.text());let s=Z(e,`.${i}.html`);if(tt(s,e)){let a=Bun.file(s);if(await a.exists())return t.html(await a.text())}await r()}}}function Pi(e,t){return(r,i)=>e.send({type:Yt.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:Qa(t,"anonymous")}},sender:t})}var Ci=`<!DOCTYPE html>
10
+ `):Nu}formatRelevantEntity(e,t){let{entity:r,excerpt:i}=e,n=r.entityType,o=_u.safeParse(r.metadata),s=o.success?o.data.slug:r.id;if(this.siteBaseUrl&&t.hasRoute(n)){let a=t.generateUrl(n,s),l=`https://${this.siteBaseUrl}${a}`;return`[${n}] ${r.id}: ${i} (${l})`}return`[${n}] ${r.id}: ${i}`}}var Wu=c.object({entityType:c.string(),query:c.object({id:c.string()})});class vt{entityService;id=Ur.ENTITIES;name="Entity DataSource";description="Fetches entity content from the entity service";constructor(e){this.entityService=e}async fetch(e,t,r){let i=Wu.safeParse(e);if(!i.success){let a=i.error.issues.map((l)=>`${l.path.join(".")}: ${l.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 Dn(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 On(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 zn={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 Mn={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 Ln={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 Un={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 Bn={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"},updatedAt:{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 $n={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 _n={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 Fn={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 Nn={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=c.object({type:c.string()}).catchall(c.unknown()),tp=c.object({type:c.literal("object"),description:c.string().optional(),required:c.array(c.string()).optional(),properties:c.record(c.string(),Zn)}),rp=c.object({lexicon:c.literal(1),id:c.string(),defs:c.object({main:c.object({type:c.literal("record"),key:c.string().min(1),description:c.string().optional(),record:c.object({type:c.literal("object"),required:c.array(c.string()).optional(),properties:c.record(c.string(),Zn)})})}).catchall(tp)});function N(e){return rp.parse(e)}var O={"ai.rizom.brain.card":N(zn),"ai.rizom.brain.deck":N(Mn),"ai.rizom.brain.link":N(Ln),"ai.rizom.brain.note":N(Un),"ai.rizom.brain.post":N(Bn),"ai.rizom.brain.project":N($n),"ai.rizom.brain.series":N(_n),"ai.rizom.brain.socialPost":N(Fn),"ai.rizom.brain.topic":N(Nn)},ip="Additive optional fields are compatible; required-field, type, or constraint changes require a migration plan or new NSID.";function J(e){return{status:"approved",version:"1.0.0",revision:1,owner:"Rizom",steward:"Rizom protocol registry",projectionPackage:e,compatibility:ip}}var Hn={"ai.rizom.brain.card":J("@brains/atproto"),"ai.rizom.brain.deck":J("@brains/decks"),"ai.rizom.brain.link":J("@brains/link"),"ai.rizom.brain.note":J("@brains/note"),"ai.rizom.brain.post":J("@brains/blog"),"ai.rizom.brain.project":J("@brains/portfolio"),"ai.rizom.brain.series":J("@brains/series"),"ai.rizom.brain.socialPost":J("@brains/social-media"),"ai.rizom.brain.topic":J("@brains/topics")};function np(){return Object.values(O)}function op(e){if(!$r(O,e))return;return O[e]}function sp(){return Br(Hn).map(([e,t])=>({id:e,...t}))}var ap=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;function cp(e){let t=c.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)=>ap.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 lp(e,t){if(typeof e!=="string"||!e.startsWith("#"))return;let r=t[e.slice(1)];return r?.type==="object"?r:void 0}function qn(e,t){switch(e.type){case"string":return cp(e);case"integer":return c.number().int();case"boolean":return c.boolean();case"array":{let r=e.items?qn(e.items,t):c.unknown(),i=c.array(r);if(e.maxLength!==void 0)i=i.max(e.maxLength);return i}case"object":return Wn(e,t);case"ref":{let r=lp(e.ref,t);if(!r)return c.custom(()=>!1,{message:`unresolvable lexicon ref ${String(e.ref)}`});return c.lazy(()=>Wn(r,t))}case"blob":return c.custom(ie,{message:"expected blob"});default:return c.unknown()}}function Jn(e,t){let r=new Set(e.required??[]),i={};for(let[n,o]of Object.entries(e.properties??{})){let s=qn(o,t);i[n]=r.has(n)?s:s.optional()}return i}function Wn(e,t){return c.strictObject(Jn(e,t))}function U(e){return c.strictObject({...Jn(e.defs.main.record,e.defs),$type:c.literal(e.id).optional()})}var _r={"ai.rizom.brain.card":U(O["ai.rizom.brain.card"]),"ai.rizom.brain.deck":U(O["ai.rizom.brain.deck"]),"ai.rizom.brain.link":U(O["ai.rizom.brain.link"]),"ai.rizom.brain.note":U(O["ai.rizom.brain.note"]),"ai.rizom.brain.post":U(O["ai.rizom.brain.post"]),"ai.rizom.brain.project":U(O["ai.rizom.brain.project"]),"ai.rizom.brain.series":U(O["ai.rizom.brain.series"]),"ai.rizom.brain.socialPost":U(O["ai.rizom.brain.socialPost"]),"ai.rizom.brain.topic":U(O["ai.rizom.brain.topic"])};function dp(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(!ie(r))return;r=r[String(i)]}return r}function up(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"&&dp(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 pp(e,t){let r=U(e).safeParse(t);if(r.success)return;let i=r.error.issues[0];if(!i)throw r.error;throw Error(up(e,t,i))}var Gn="atproto:brain-card-discovered",Qn="atproto:brain-discovered",Kn="atproto:brain-card-refreshed",Vn="atproto:brain-card-unavailable",Yn="atproto:brain-card-conflict",Xn="atproto:jetstream-gap",mp=c.custom((e)=>_r["ai.rizom.brain.card"].safeParse(e).success),eo=c.object({repoDid:c.string().min(1),uri:c.string().min(1),cid:c.string().min(1),record:mp}).strict(),Fr=c.object({agentId:c.string().min(1),name:c.string().min(1),url:c.string().url(),status:c.enum(["discovered","approved","archived"]),repoDid:c.string().min(1).optional(),brainDid:c.string().min(1).optional(),anchorDid:c.string().min(1).optional(),cardUri:c.string().min(1).optional(),cardCid:c.string().min(1).optional()}).strict(),to=c.object({repoDid:c.string().startsWith("did:plc:"),observedAt:c.string().datetime(),staleAfter:c.string().datetime().optional(),reason:c.enum(["deleted","refresh-failed"]),error:c.string().min(1).optional()}).strict(),ro=c.object({domain:c.string().min(1),existingRepoDid:c.string().min(1).optional(),candidateRepoDid:c.string().startsWith("did:plc:"),observedAt:c.string().datetime(),reason:c.string().min(1)}).strict(),io=c.object({previousCursorTimeUs:c.number().int().nonnegative(),clampedCursorTimeUs:c.number().int().nonnegative(),observedAt:c.string().datetime()}).strict(),fp=ye(Gn,eo),gp=ye(Qn,Fr),hp=ye(Kn,Fr),yp=ye(Vn,to),vp=ye(Yn,ro),bp=ye(Xn,io);class St{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 Sp({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 wt(e,t,r){let i=await Rt(e,no,{actor:r},t);if(i.status==="unavailable")return null;if(i.status==="failed")throw oo(i.error,`Principal resolution failed: ${i.error.message}`);return i.data.principal}function ao(e,t){return new so(e,(r)=>wt(t,"shell:content-service",r))}var Nr=C.Service("@brains/conversation-service/ConversationService");function Rp(e){if(e.service){let r=e.service;return{service:r,close:()=>r.close()}}let t=co.createFreshFromConfig(e.logger,e.messageBus,e.dbConfig);try{return{service:t,close:()=>t.close()}}catch(r){throw t.close(),r}}function lo(e){return ne(Nr,()=>Rp(e))}var Zr=C.Service("@brains/entity-service/EntityService");function wp(e){return"close"in e&&typeof e.close==="function"}function po(e){return ne(Zr,()=>{let t=e.service??uo.createFresh(e);return{service:t,close:()=>{if(wp(t))t.close()}}})}var Ge=c.strictObject({dedupeKey:c.string().min(1).max(512),title:c.string().min(1),body:c.string().min(1),html:c.string().min(1).optional(),sensitivity:c.enum(["normal","secret"]).optional(),includeInInbox:c.boolean().optional()}),Hr=c.strictObject({alerts:c.array(Ge).optional()});var It="shell:recurring-check",qr=86400000,Ip=7*qr,xp=3*qr,Pp=c.strictObject({checkId:c.string().min(1)}),Cp=c.discriminatedUnion("kind",[c.strictObject({kind:c.literal("last-success"),checkId:c.string(),at:c.string().datetime()}),c.strictObject({kind:c.literal("alert"),checkId:c.string(),dedupeKey:c.string(),status:c.enum(["pending","suppressed","delivered","resolved"]),alert:Ge,observedAt:c.string().datetime(),includeInInbox:c.boolean().optional(),deliveredAt:c.string().datetime().optional(),resolvedAt:c.string().datetime().optional()})]);class Pt{brainId;scheduler;state;jobQueue;delivery;logger;clock;checks=new Map;pluginChecks=new Map;alertOperations=new ho;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:Cp});let t={validateAndParse:(r)=>{let i=Pp.safeParse(r);return i.success?i.data:null},process:async(r)=>{await this.runNow(r.checkId)}};this.jobQueue.registerHandler(It,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(It),this.handlerRegistered=!1}namespace(e){return{register:(t)=>this.register(e,t)}}register(e,t){Ap(e),yo(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 l=AbortSignal.any([t,a]),d=e.definition.deliverAlerts!==!1;if(d)await this.flushPendingAlerts(r);else await this.suppressPendingAlerts(r);l.throwIfAborted();let u=await e.definition.run({signal:l});l.throwIfAborted();let p=Hr.parse(u);for(let m of p.alerts??[])l.throwIfAborted(),await this.recordAlert(r,m,{deliver:d,includeInInbox:m.includeInInbox??e.definition.includeInInbox!==!1});l.throwIfAborted(),await this.state.set(this.lastSuccessKey(r),{kind:"last-success",checkId:r,at:this.currentTime().toISOString()})},o=w.tryPromise({try:(a)=>(i=n(a),i),catch:(a)=>a}),s=await w.runPromiseExit(o,{signal:t});if(i)await Promise.allSettled([i]);if(j.isSuccess(s))return!0;if(t.aborted)throw t.reason;throw oe.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=Wr(this.currentTime(),i).getTime()+i.periodMs,o=new AbortController,s={controller:o,settled:Promise.resolve()};e.enqueueRetry=s,s.settled=mo(()=>this.enqueue(r.id),t,{firstDelayMs:fo,maxDelayMs:go,giveUpAt:n,signal:o.signal,clock:this.clock,onRetry:(a,l)=>{this.logger.warn(`Failed to enqueue recurring check ${r.id}; retrying in ${l}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=Wr(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:It,data:{checkId:e},options:t})}async listOpenAlerts(){return(await this.state.list({keyPrefix:"alert:"})).flatMap((t)=>{let r=t.value;if(r.kind!=="alert"||r.status==="resolved")return[];if(!(r.includeInInbox??this.checks.get(r.checkId)?.definition.includeInInbox!==!1))return[];return[{id:t.key,checkId:r.checkId,title:r.alert.title,body:r.alert.body,observedAt:r.observedAt}]}).sort((t,r)=>t.observedAt.localeCompare(r.observedAt)||t.id.localeCompare(r.id))}async resolveOpenAlert(e){await this.alertOperations.run(e,async()=>{let t=await this.state.get(e),r=t?.kind==="alert"&&(t.includeInInbox??this.checks.get(t.checkId)?.definition.includeInInbox!==!1);if(t?.kind!=="alert"||t.status==="resolved"||!r)throw Error("Recurring-check inbox item is not open");await this.state.set(e,{...t,status:"resolved",resolvedAt:this.currentTime().toISOString()})})}async flushPendingAlerts(e){let t=await this.state.list({keyPrefix:this.alertKeyPrefix(e)});for(let r of t)await this.alertOperations.run(r.key,async()=>{let i=await this.state.get(r.key);if(i?.kind==="alert"&&(i.status==="pending"||i.status==="suppressed"))await this.deliverStoredAlert(r.key,i)})}async suppressPendingAlerts(e){let t=await this.state.list({keyPrefix:this.alertKeyPrefix(e)});for(let r of t)await this.alertOperations.run(r.key,async()=>{let i=await this.state.get(r.key);if(i?.kind==="alert"&&i.status==="pending")await this.state.set(r.key,{...i,status:"suppressed"})})}async recordAlert(e,t,r){let i=Ge.parse(t),n=this.alertKey(e,i.dedupeKey);await this.alertOperations.run(n,async()=>{let o=await this.state.get(n);if(o?.kind==="alert"){let 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,{idempotencyKey:Tp(e,t.observedAt)})===!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:${G(e)}`}alertKeyPrefix(e){return`alert:${G(e)}:`}alertKey(e,t){return`${this.alertKeyPrefix(e)}${G(t)}`}}function Tp(e,t){return`recurring-alert:${G(`${e}\x00${t}`)}`}function xt(e,t,r){let i=r==="daily"?qr:Ip,n=i/60000,o=G(`${e}\x00${t}\x00${r}`),s=Number.parseInt(o.slice(0,12),16)%n,a=s%60,l=Math.floor(s/60),d=l%24;return{expression:r==="daily"?`${a} ${d} * * *`:`${a} ${d} * * ${Math.floor(l/24)}`,offsetMs:s*60000,periodMs:i,anchorMs:r==="daily"?0:xp}}function Wr(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 Ep=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*:[a-z][a-z0-9-]*$/;function Ap(e){if(e.length<=200&&Ep.test(e))return;yo(e,"plugin ID")}function yo(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 x=vo("runtime_state_records",{namespace:Ct("namespace").notNull(),key:Ct("key").notNull(),value:Ct("value",{mode:"json"}).notNull(),createdAt:Jr("created_at").notNull(),updatedAt:Jr("updated_at").notNull()},(e)=>({pk:So({columns:[e.namespace,e.key]}),namespaceUpdatedAtIdx:bo("idx_runtime_state_namespace_updated_at").on(e.namespace,e.updatedAt)}));function wo(e){return Ro({url:e.url,schema:{runtimeStateRecords:x},authToken:e.authToken,authTokenEnv:"RUNTIME_STATE_DATABASE_AUTH_TOKEN"})}function Tt(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 kp}from"util";var jp=/^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,511}$/,To=512;class Gr{db;namespace;schema;now;constructor(e,t,r,i=()=>new Date){Dp(t),this.db=e,this.namespace=t,this.schema=r,this.now=i}async get(e){let t=ve(e),i=(await this.db.select().from(x).where(se(M(x.namespace,this.namespace),M(x.key,t))).limit(1))[0];if(!i)return null;return this.schema.parse(i.value)}async has(e){let t=ve(e);return(await this.db.select({key:x.key}).from(x).where(se(M(x.namespace,this.namespace),M(x.key,t))).limit(1)).length>0}async set(e,t){let r=ve(e),i=Tt(this.schema,t),n=i===null?be`'null'`:i,o=this.now().getTime();await this.db.insert(x).values({namespace:this.namespace,key:r,value:n,createdAt:o,updatedAt:o}).onConflictDoUpdate({target:[x.namespace,x.key],set:{value:n,updatedAt:o}})}async setIfNotExists(e,t){let r=ve(e),i=Tt(this.schema,t),n=i===null?be`'null'`:i,o=this.now().getTime(),s=await this.db.insert(x).values({namespace:this.namespace,key:r,value:n,createdAt:o,updatedAt:o}).onConflictDoNothing({target:[x.namespace,x.key]});return Number(s.rowsAffected)>0}async compareAndSet(e,t,r){let i=ve(e),n=Tt(this.schema,r),[o]=await this.db.select({value:x.value}).from(x).where(se(M(x.namespace,this.namespace),M(x.key,i))).limit(1);if(!o||!kp(this.schema.parse(o.value),t))return!1;let s=o.value===null?be`'null'`:o.value,a=n===null?be`'null'`:n,l=await this.db.update(x).set({value:a,updatedAt:this.now().getTime()}).where(se(M(x.namespace,this.namespace),M(x.key,i),M(x.value,s)));return Number(l.rowsAffected)===1}async delete(e){let t=ve(e),r=await this.db.delete(x).where(se(M(x.namespace,this.namespace),M(x.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(x).where(se(M(x.namespace,this.namespace),Io(e.keyPrefix)));return Number(t.rowsAffected)}async listRows(e){let{keyPrefix:t,afterKey:r,limit:i}=e;if(r!==void 0)ve(r);if(i!==void 0)c.number().int().min(1).max(1000).parse(i);let n=this.db.select({...xo(x),key:be`CAST(${x.key} AS BLOB)`.mapWith((o)=>new TextDecoder("utf-8",{fatal:!0}).decode(o))}).from(x).where(se(M(x.namespace,this.namespace),Io(t),r!==void 0?Po(x.key,r):void 0)).orderBy(Co(x.key)).$dynamic();return i===void 0?n:n.limit(i)}}function Dp(e){if(!jp.test(e))throw Error(`Invalid runtime state namespace: ${e}. Use 1-512 alphanumeric, _, ., :, or - characters.`)}function ve(e){if(e.length===0||e.length>To)throw Error("Runtime state keys must be 1-512 characters long");return e}function Io(e){if(e===void 0)return;return Op(e),be`substr(CAST(${x.key} AS BLOB), 1, length(CAST(${e} AS BLOB))) = CAST(${e} AS BLOB)`}function Op(e){if(e.length>To)throw Error("Runtime state key prefixes must be 512 characters or shorter");return e}class Et{db;client;logger;databaseUrl;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;static createFresh(e,t){return new Et(e,t??Ee.getInstance())}constructor(e,t){let{db:r,client:i,url:n}=wo(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 Eo(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 Gr(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 Qr=C.Service("@brains/runtime-state/RuntimeStateService");function Ao(e){return ne(Qr,()=>{let t=e.service??Et.createFresh(e.config,e.logger);return{service:t,close:()=>t.close()}})}async function Kr(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=Qe(r),t.warn(`Daemon ${e.name} failed to start: ${P(r)}`),r}}async function Vr(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=Qe(r),t.error(`Failed to stop daemon: ${e.name}`,r),r}}async function ko(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:P(t),lastCheck:new Date};return e.health=r,r}}function jo(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 Kr(t,this.logger);return}let r=w.runSync(D.make()),i=w.acquireRelease(w.promise(()=>Kr(t,this.logger)),()=>w.promise(()=>Vr(t,this.logger)));try{await w.runPromise(D.provide(i,r)),this.daemonScopes.set(e,r)}catch(n){throw await w.runPromise(D.close(r,j.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 Vr(t,this.logger);return}this.daemonScopes.delete(e),await w.runPromise(D.close(r,j.void))}async checkHealth(e){let t=this.daemons.get(e);if(!t)throw Error(`Daemon not registered: ${e}`);return ko(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(jo)}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??=Qe(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 zp=c.object({projectionId:c.string().min(1),reason:c.string().min(1),openedAt:c.number().int().nonnegative(),expiresAt:c.number().int().nonnegative()}),Mp=8,Lp=32,Up=128,Bp=5,$p=600000,_p=600000,Fp=1000,Np="shell.projection-circuits";class kt{operationContext;options;circuitStore;roots=new Map;reservedJobs=new Map;circuits=new Map;projections;static createFresh(e,t={}){return new kt(e,t)}constructor(e,t){this.operationContext=e,this.options={maxDerivationDepth:t.maxDerivationDepth??Mp,maxJobsPerRoot:t.maxJobsPerRoot??Lp,maxMutationsPerRoot:t.maxMutationsPerRoot??Up,repeatedTargetLimit:t.repeatedTargetLimit??Bp,retentionMs:t.retentionMs??$p,circuitOpenMs:t.circuitOpenMs??_p,maxTrackedRoots:t.maxTrackedRoots??Fp,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:Np,schema:zp})}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,l=(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:()=>l(!0),rollback:()=>l(!1)}}async assertMutationAdmission(e){let t=this.operationContext.current()?.provenance,r=t?.projectionId;if(!t||!r)return;let i=this.options.now();await this.prune(i),await this.requireProjection(r,i),await this.assertCircuitClosed(r,i);let n=this.getRootCounters(t.rootJobId,i);if(n.mutations++,n.updatedAt=i,n.mutations>this.options.maxMutationsPerRoot)await this.rejectAndOpen(r,`Root ${t.rootJobId} exceeded projection mutation budget ${this.options.maxMutationsPerRoot}`,i);let o=`${r}\x00${e.entityType}\x00${e.entityId}`,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,l])=>s.updatedAt-l.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 Zp={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 Ae(e){return Zp[e??"combined"]}var Do=[jt.created,jt.updated,jt.deleted];function Oo(e,t,r){let i=Do.map((o)=>e.subscribe(o,(s)=>(t.send({type:o,payload:s.payload}),{success:!0}))),n=t.onEvent((o)=>{if(!Do.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 Hp=20,Wp=0.5,qp=0.06,Jp=5;function Mo(e){return async({answer:t})=>{let i=(await e.entityService.search({query:t,options:{limit:Hp,minScore:Wp,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-qp).slice(0,Jp).map(({entity:o})=>zo(o,e))}}function Gp(e,t,r,i,n){return[$o,_o,Fo].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 l=o.name.replace("entity:","");n.debug(`${t} entity ${l}, cache refreshed`)}return{success:!0}}))}function Lo(e,t,r,i){return Gp(e,t,t,async()=>{await r(),await Se(e,No,{entityType:t},"shell")},i)}async function Qp(e,t,r){let i=Kp(e.kind);if(!i)return null;try{let n=t.scoped({namespace:i,refKind:e.kind,routePath:""}),{record:o,content:s}=await n.read(e.id);return Go({...o,content:s,source:e})}catch(n){return r.debug("Skipped unavailable prior runtime upload",{uploadKind:e.kind,uploadId:e.id,error:P(n)}),null}}function Kp(e){return e===je.refKind?je.namespace:null}function Yo(e){let{config:t,entityService:r,logger:i,messageBus:n,aiService:o,mcpService:s,conversationService:a,runtimeUploadRegistry:l,disposables:d,executionOnly:u=!1}=e,p=Qo.createFresh(r,i,t.identity);d.push(...Lo(n,L.BRAIN_CHARACTER,()=>p.refreshCache(),i));let m=Ko.createFresh(r,i,t.profile),f=Vo.createFresh(i,async(v)=>{let R=await wt(n,"shell:canonical-identity-service",v).catch(()=>null);if(!R?.canonicalId)return null;return{userId:R.userId,canonicalId:R.canonicalId,displayName:R.displayName}}),g=Jo({guestPricing:Zo(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=Ho(t.name),S=new bt(t.entityDisplay),b={isCitable:(v)=>S.isCitable(v),urlFor:(v,R)=>S.generateUrl(v,R),siteBaseUrl:t.siteBaseUrl},y=Wo.createFresh(s,a,p,m,i,{agentFactory:g,turnEvents:qo(n),canonicalIdentityResolver:f,entityLinks:b,...e.generationUsage?{generationUsage:e.generationUsage}:{},...e.embeddingUsage?{embeddingUsage:e.embeddingUsage}:{},...t.embedding.enabled?{indexReadiness:r,guestAnswerSources:Mo({entityService:r,...b})}:{},uploadAttachmentResolver:(v)=>Qp(v,l,i),guestAskedBefore:async(v)=>{let R=await ke(n,Uo,v,"shell:agent-service");return R.status==="answered"?R.answers.find((I)=>I.hit)?.hit:void 0},agentContextProvider:async(v)=>{let R=await ke(n,Bo,v,"shell:agent-service");return R.status==="answered"?R.answers.flatMap((I)=>I.items):[]},...h?{assistantAgentId:h}:{},...t.agentInstructions&&{agentInstructions:t.agentInstructions}});if(d.push(...Lo(n,L.ANCHOR_PROFILE,()=>m.refreshCache(),i)),!u)d.push(n.subscribe(Ke.identityChanged,async()=>(y.invalidateAgent(),{success:!0})));return{identityService:p,profileService:m,canonicalIdentityService:f,agentService:y}}var Ve=C.Service("@brains/job-queue/JobQueueService"),Dt=C.Service("@brains/job-queue/BatchJobManager"),Ot=C.Service("@brains/job-queue/JobProgressMonitor"),zt=C.Service("@brains/job-queue/JobQueueWorker");function is(e){return ne(Ve,()=>{let t=e.service??Xo.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 ns(e){let t=!1,r=w.gen(function*(){let i=yield*Ve,n=e.batchJobManager??ts.createFresh(i,e.logger),o=e.jobProgressMonitor??rs.createFresh(i,e.messageBus,n,e.logger,e.progressMonitorMode),s=e.jobQueueWorker??es.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 C.make(Dt,n).pipe(C.add(Ot,o),C.add(zt,s))});return{layer:Q.effectContext(w.acquireRelease(r,(i)=>t?w.void:Vp(i))),abandon:()=>{t=!0}}}function Vp(e){let t=C.get(e,zt),r=C.get(e,Ot),i=C.get(e,Dt);return w.gen(function*(){let n=yield*w.exit(w.tryPromise({try:()=>t.stop(),catch:(l)=>l})),o=yield*w.exit(w.tryPromise({try:()=>r.stop(),catch:(l)=>l})),s=yield*w.exit(w.tryPromise({try:async()=>{await i.stop()},catch:(l)=>l})),a=[n,o,s].find(j.isFailure);if(a)yield*w.die(oe.squash(a.cause))})}function Yp(e,t=(r)=>process.exit(r)){return(r)=>{e.error("Job queue worker requires process restart",{reason:r,exitCode:1}),t(1)}}function Mt(e){let t=w.runSyncExit(D.close(e,j.void));if(j.isFailure(t))throw oe.squash(t.cause)}function os(e){let t=e.operationContext??Lt.createFresh(),r=w.runSync(D.make()),i,n;try{let o=w.runSync(Q.buildWithScope(is({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=C.get(o,Ve),a=w.runSync(D.make());i=a;let l=ns({messageBus:e.messageBus,logger:e.logger,operationContext:t,...e.projectionBatchScope&&{projectionBatchScope:e.projectionBatchScope},onWorkerUnhealthy:Yp(e.logger),workerConcurrency:e.workerConcurrency,...e.progressMonitorMode&&{progressMonitorMode:e.progressMonitorMode},...e.dependencies?.batchJobManager&&{batchJobManager:e.dependencies.batchJobManager},...e.dependencies?.jobProgressMonitor&&{jobProgressMonitor:e.dependencies.jobProgressMonitor},...e.dependencies?.jobQueueWorker&&{jobQueueWorker:e.dependencies.jobQueueWorker}});n=l;let d=w.runSync(Q.buildWithScope(l.layer.pipe(Q.provide(Q.succeed(Ve,s))),a)),u=C.get(d,Dt),p=C.get(d,Ot),m=C.get(d,zt),f,g=!1,h=!1;return{batchJobManager:u,jobProgressMonitor:p,jobQueueService:s,jobQueueWorker:m,closeRuntime:()=>(g=!0,f??=w.runPromise(D.close(a,j.void)),f),rollbackRuntime:()=>{if(g)return;g=!0,l.abandon(),Mt(a)},closeDatabase:()=>{if(h)return;h=!0,Mt(r)}}}catch(o){if(i)try{n?.abandon(),Mt(i)}catch(s){e.logger.warn("Failed to release partial job runtime acquisition",s)}try{Mt(r)}catch(s){e.logger.warn("Failed to release partial job database acquisition",s)}throw o}}function as(e){return{deliver:async(t,{idempotencyKey:r})=>{let i=await Rt(e,ss,{title:t.title,body:t.body,...t.html?{html:t.html}:{},...t.sensitivity?{sensitivity:t.sensitivity}:{},idempotencyKey:r},"shell.recurring-checks");if(i.status==="unavailable")return!1;if(i.status==="failed"||i.data.status!=="sent")throw Error("Recurring alert delivery failed");return!0}}}function ls(e){return{sourceId:"recurring-checks",displayName:"Recurring checks",list:async()=>(await e.listOpenAlerts()).map((t)=>({id:t.id,title:cs(t.title,160),summary:cs(t.body,1000),receivedAt:t.observedAt,urgency:"high",actions:[{id:"resolve",label:"Dismiss",confirm:!0}]})),act:async(t,r)=>{if(r!=="resolve")throw Error("Invalid recurring-check inbox action");await e.resolveOpenAlert(t)}}}function cs(e,t){return e.length<=t?e:e.slice(0,t)}function ds(e,t){if(t)return t;let r={debug:Ye.DEBUG,info:Ye.INFO,warn:Ye.WARN,error:Ye.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 Yr(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 Bs(e){let{config:t,dependencies:r,initializerLogger:i,lifecycle:n,processRole:o,peerChannel:s}=e;i.debug("Initializing Shell services");let a=Ae(o),l=ds(t,r?.logger),d=r?.operationContext??Lt.createFresh(),u=[],p=js.createFresh(!r?.embeddingService),m=r?.embeddingService??ks.createFresh({providerKeys:t.ai.providerKeys,profile:Es(t.ai.embeddingModel),runtimeUrl:t.ai.modelRuntimeUrl,logger:l,usage:p}),f=Ds.createFresh(),g=r?.aiService??As.createFresh(Yr(t),l,f),h=r?.entityRegistry??ms.createFresh(l),S=r?.messageBus??ps.createFresh(l,d);if(s)u.push(Oo(S,s,l));let b=r?.templateRegistry??gs.createFresh(l),y=r?.dataSourceRegistry??fs.createFresh(l),v=r?.renderService??ys.createFresh(b),R=r?.daemonRegistry??At.createFresh(l),I=r?.pluginManager??Ms.createFresh(l,R),E=r?.permissionService??new hs(t.permissions,{spaces:t.spaces,entityActionFloor:(q)=>h.getEntityTypeConfig(q).actionPolicy}),z=r?.profileKindRegistry??new zs(t.profileKind),Pe=r?.channelRegistry??new Rs,fe=r?.inboxRegistry??new Is,te=r?.inboxFollowUpRegistry??new xs(l),du=r?.operationalHealthRegistry??new Os,uu=r?.accountSettingsRegistry??new Ss,pu=new ws,mu=new St,fu=r?.attachmentRegistry??Ps.createFresh(),yn=r?.runtimeUploadRegistry??Cs.createFresh({dataDir:t.dataDir,logger:l}),gu=n.buildLayer(Ao({config:De(t.runtimeStateDatabase),logger:l,...r?.runtimeStateService&&{service:r.runtimeStateService}})),Pr=C.get(gu,Qr),Cr=r?.projectionRuntimeSupervisor??kt.createFresh(d,{runtimeState:Pr}),vn=r?.mcpService??Ts.createFresh(S,l),Tr={},hu={runFreshBatchScope:(q)=>Tr.current?Tr.current.runFreshBatchScope(q):q()},ut=os({dependencies:r,jobQueueConfig:{...De(t.jobQueueDatabase),brainVersion:t.version},workerConcurrency:t.jobQueue.workerConcurrency,messageBus:S,operationContext:d,projectionBatchScope:hu,projectionAdmission:Cr,handlerRegistrationMode:a.handlerRegistrationMode,progressMonitorMode:a.progressMonitorMode,logger:l}),{batchJobManager:yu,jobProgressMonitor:vu,jobQueueService:Er,jobQueueWorker:bu}=ut;n.addSyncFinalizer(()=>ut.closeDatabase()),n.addSyncFinalizer(()=>ut.rollbackRuntime());let Ze=r?.recurringCheckService??new Pt({brainId:t.siteBaseUrl??t.dataDir,scheduler:new Ls,runtimeState:Pr,clock:w.runSync(us.Clock),jobQueue:Er,logger:l,delivery:as(S)});n.addSyncFinalizer(()=>Ze.abandon()),fe.registerSource("shell.recurring-checks",ls(Ze)),n.addSyncFinalizer(()=>fe.unregisterPlugin("shell.recurring-checks"));let bn=(q,kr)=>{if(!a.serves)return;R.register(q,kr,"shell"),n.addSyncFinalizer(()=>R.abandon(q))};bn("shell:recurring-checks",{start:()=>Ze.start(),stop:()=>Ze.stop()});let Su=n.buildLayer(po({embeddingService:m,embeddingsEnabled:t.embedding.enabled,entityRegistry:h,logger:l,jobQueueService:Er,messageBus:S,mutationAdmission:Cr,...r?.projectionRuntime?.now&&{projectionNow:r.projectionRuntime.now},dbConfig:De(t.database),embeddingDbConfig:De(t.embeddingDatabase),...r?.entityService&&{service:r.entityService}})),pt=C.get(Su,Zr);Tr.current=pt.getProjectionStore();let Ru=n.buildLayer(lo({dbConfig:De(t.conversationDatabase),logger:l,messageBus:S,...r?.conversationService&&{service:r.conversationService}})),Ar=C.get(Ru,Nr);bn("shell:guest-retention",Us({intervalMs:60000,logger:l,run:async()=>{await Ar.deleteExpiredGuestConversations(100)}})),n.addSyncFinalizer(()=>{for(let q of u.splice(0))try{q()}catch(kr){l.warn("Failed to dispose shell subscription",kr)}});let Sn=ao(E,S),wu=r?.contentService??new bs({logger:l,entityService:pt,aiService:g,templateRegistry:b,dataSourceRegistry:y,generationAuthorizer:new vs(E,Sn)}),{identityService:Iu,profileService:xu,canonicalIdentityService:Pu,agentService:Cu}=Yo({config:t,entityService:pt,embeddingService:m,embeddingUsage:p,...!r?.aiService?{generationUsage:f}:{},entityRegistry:h,logger:l,messageBus:S,aiService:g,mcpService:vn,conversationService:Ar,runtimeUploadRegistry:yn,disposables:u,executionOnly:!a.serves});return{logger:l,operationContext:d,projectionRuntimeSupervisor:Cr,disposables:u,entityRegistry:h,messageBus:S,renderService:v,daemonRegistry:R,pluginManager:I,templateRegistry:b,dataSourceRegistry:y,mcpService:vn,embeddingService:m,entityService:pt,aiService:g,conversationService:Ar,contentService:wu,callerAuthorizer:Sn,jobQueueService:Er,jobQueueWorker:bu,batchJobManager:yu,jobProgressMonitor:vu,jobServicesLifecycle:ut,permissionService:E,identityService:Iu,profileService:xu,canonicalIdentityService:Pu,profileKindRegistry:z,channelRegistry:Pe,inboxRegistry:fe,inboxFollowUpRegistry:te,operationalHealthRegistry:du,accountSettingsRegistry:uu,authRegistry:pu,atprotoProjectionRegistry:mu,agentService:Cu,attachmentRegistry:fu,runtimeUploadRegistry:yn,runtimeStateService:Pr,recurringCheckService:Ze}}function Hs(e,t){e.register(Xr.name,Xr),t.debug("Shell system templates registered")}function Ws(e,t){e.register(Je.BASE_ENTITY_DISPLAY,{name:"base-entity-display",description:"Display template for base entities",schema:ei,formatter:new $s,requiredPermission:"public"}),t.debug("Base entity display template registered")}function qs(e,t){e.registerEntityType(L.NOTE,ei,new _s,{projectionSourceRole:"primary"}),t.debug("Fallback base entity adapter registered")}function Js(e,t){let r=new Fs;e.registerEntityType(L.BRAIN_CHARACTER,r.schema,r,{classification:"system",projectionSource:!1,projectionSourceRole:"excluded"}),t.debug("Brain character entity support registered")}function Gs(e,t){let r=new Ns;e.registerEntityType(L.ANCHOR_PROFILE,r.schema,r,{classification:"system",projectionSourceRole:"canonical"}),t.debug("Anchor profile entity support registered")}async function Qs(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:l}of r.getFailedPlugins()){let d=r.getPlugin(a);if(l instanceof Zs||d?.requiresDaemonStartup?.())throw l}i.debug("Plugin initialization complete")}class Ut{logger;config;processRole;peerChannel;static createFresh(e,t,r,i){return new Ut(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){Hs(e,this.logger)}registerBaseEntityDisplayTemplate(e){Ws(e,this.logger)}registerFallbackBaseEntity(e){qs(e,this.logger)}registerBrainCharacterSupport(e){Js(e,this.logger)}registerAnchorProfileSupport(e){Gs(e,this.logger)}async initializePlugins(e,t){await Qs({plugins:this.config.plugins,pluginManager:e,logger:this.logger,initOptions:t})}initializeServices(e,t){return Bs({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=Vs.createFresh(t,r);e.registerHandler(Ks.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 ti=c.strictObject({waveId:c.string().trim().min(1),ruleId:c.string().trim().min(1)});class ri{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=ti.safeParse(e);return t.success?t.data:null}async onTerminalError(e,t,r){let i=ti.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=ti.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,l,d]=await Promise.all([this.store.listWaveInputs(n.waveId),this.store.listWaveRules(n.waveId),this.store.getWave(n.waveId),this.getJobStatus(t)]);if(!l)throw Error(`Projection wave "${n.waveId}" does not exist`);if(l.status!=="running"&&l.status!=="superseded")throw Error(`Projection wave "${n.waveId}" is not active`);let u=a.find((I)=>I.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:l.cutoffGeneration};if(await this.recordDiagnostic({...p,event:"attempt-started"}),l.status==="superseded"){let I=await this.store.listPendingInputs();return await this.recordDiagnostic({...p,event:"apply-completed",applyOutcome:"superseded",highestPendingGeneration:Bt(I)}),{waveId:n.waveId,ruleId:o.id,outcome:"superseded",inputFingerprint:null,changedTargets:[]}}if(await this.store.supersedeWaveIfStale(n.waveId,this.now())){let I=await this.store.listPendingInputs();return await this.recordDiagnostic({...p,event:"apply-completed",applyOutcome:"superseded",highestPendingGeneration:Bt(I)}),await this.coordinator.continueAfterSupersession(n.waveId),{waveId:n.waveId,ruleId:o.id,outcome:"superseded",inputFingerprint:null,changedTargets:[]}}let m=tm(s,a,u.level),f=await o.selectInput({waveId:n.waveId,inputs:m},this.inputContext,i),g=o.fingerprint(f),h={...p,inputFingerprint:g,selectedSourceCount:em(f,m)};await this.recordDiagnostic({...h,event:"input-selected"});let S={ruleId:o.id,ruleVersion:o.version,inputFingerprint:g},b=await this.store.getRuleMemo(S);await this.recordDiagnostic({...h,event:"memo-resolved",memoHit:b!==null});let y;if(b)y=b.writeIntents;else{await this.recordDiagnostic({...h,event:"derive-started",memoHit:!1});try{y=await o.derive(f,this.executionContext,i),await this.recordDiagnostic({...h,event:"derive-completed",memoHit:!1})}catch(I){throw await this.recordDiagnostic({...h,event:i.aborted?"derive-cancelled":"derive-failed",memoHit:!1}),I}}let v=await this.store.applyRuleResult({waveId:n.waveId,ruleId:o.id,ruleVersion:o.version,inputFingerprint:g,writeIntents:y,completedAt:this.now()}),R=await this.store.listPendingInputs();if(!v)return await this.recordDiagnostic({...h,event:"apply-completed",memoHit:b!==null,applyOutcome:"superseded",highestPendingGeneration:Bt(R)}),await this.coordinator.continueAfterSupersession(n.waveId),{waveId:n.waveId,ruleId:o.id,outcome:"superseded",inputFingerprint:g,changedTargets:[]};return await this.recordDiagnostic({...h,event:"apply-completed",memoHit:b!==null,applyOutcome:"applied",highestPendingGeneration:Bt(R)}),await this.reconcileTargets(v.changedTargets),await this.coordinator.advanceActiveWave(n.waveId),{waveId:n.waveId,ruleId:o.id,outcome:"applied",inputFingerprint:g,changedTargets:v.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 em(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 tm(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 rm(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 Oe="shell:projection-rule";class ni{store;queue;graph;ruleById;graphFingerprint;createWaveId;beforeWaveCompletion;scheduleWakeup;onScheduledWakeupError;now;operationQueue=new Ys;scheduledWakeup;constructor(e){this.store=e.store,this.queue=e.queue,this.graph=e.graph,this.ruleById=om(e.graph,e.rules),this.graphFingerprint=sm(e.graph,e.rules),this.createWaveId=e.createWaveId,this.beforeWaveCompletion=e.beforeWaveCompletion??(async()=>{}),this.scheduleWakeup=e.scheduleWakeup??im,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(ii(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(ii(s))await this.startNextWaveInternal();return s}let t=await this.store.listPendingInputs();if(t.length===0)return this.cancelScheduledWakeup(),null;let r=nm(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(ii(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=ea(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:rm(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:Oe,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 ii(e){return e.status==="completed"||e.status==="superseded"}function im(e,t){let r=setTimeout(()=>{t()},e);return()=>clearTimeout(r)}function nm(e,t,r){let n=ea(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 om(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 sm(e,t){return Xs({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 ea(e,t,r){let i=new Map(e.projections.map((l)=>[l.id,l])),n=ta(e,(l)=>[l.from,l.to]),o=new Set(e.projections.filter((l)=>am(l,r)).map((l)=>l.id)),s=[...o];while(s.length>0){let l=s.flatMap((d)=>n.get(d)??[]).filter((d)=>i.has(d)&&!o.has(d));for(let d of l)o.add(d);s=[...new Set(l)].sort()}let a=cm(e,o);return[...o].map((l)=>{let d=i.get(l),u=t.get(l),p=a.get(l);if(!d||!u||p===void 0)throw Error(`Cannot plan projection rule "${l}"`);return{ruleId:l,targetType:d.targetType,level:p}}).sort((l,d)=>l.level-d.level||l.ruleId.localeCompare(d.ruleId))}function am(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 cm(e,t){let r=ta(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),l=a.length===0?0:Math.max(...a)+1;i.set(s,l),n.delete(s)}}return i}function ta(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 ra(e){let t=new ni({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 ri({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(Oe,r,"shell");let i=()=>{},n=()=>{};try{if(e.activationMode!=="executor"){let s=async(u)=>{if(u)await e.reconcileBatches?.();await t.startNextWave()},a,l=(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 l(!1)};i=e.setWakeup(d),await l(!0),n=(e.scheduleSweep??lm)(e.sweepIntervalMs??1000,async()=>{try{await l(!0)}catch(u){e.logger.error("Projection coordination sweep failed",u)}})}}catch(s){throw n(),i(),e.queue.unregisterHandler(Oe),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(Oe)}}}function lm(e,t){let r=setInterval(()=>{t()},e);return r.unref(),()=>clearInterval(r)}import{existsSync as Xm}from"fs";import{mkdir as ef,writeFile as tf}from"fs/promises";import{join as rf,resolve as Va}from"path";var ia=5000;async function na(e,t){let r=Promise.resolve(e.stop(!1)),i,n=new Promise((s)=>{i=setTimeout(()=>s("deadline"),Math.max(0,t.drainMs))});if(await Promise.race([r.then(()=>"drained"),n]).finally(()=>clearTimeout(i))==="drained")return;t.logger.warn(`${t.label} drain passed ${t.drainMs}ms with ${e.pendingRequests??"unknown"} request(s) in flight; closing them`),r.catch(()=>{return}),Promise.resolve(e.stop(!0)).catch(()=>{return})}function oa(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 Z,join as Qm,sep as Km}from"path";var sa=Symbol();var aa=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,(r)=>r.toLowerCase())}}).formData();var dm=1e4,$t=(e)=>("headers"in e),da=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 um(e,{all:r,dot:i});return{}};async function um(e,t){if(!$t(e)&&e.bodyCache.formData)return ca(await e.bodyCache.formData,t);let r=$t(e)?e.headers:e.raw.headers,i=await e.arrayBuffer(),n=aa(i,r.get("Content-Type")||"");if(!$t(e))e.bodyCache.formData=n;let o=await n;if(o)return ca(o,t);return{}}function ca(e,t){let r=Object.create(null),i={count:0};if(e.forEach((n,o)=>{if(!(t.all||o.endsWith("[]")))r[o]=n;else pm(r,o,n)}),t.dot)Object.entries(r).forEach(([n,o])=>{if(n.includes("."))mm(r,n,o,i),delete r[n]});return r}var pm=(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]},mm=(e,t,r,i)=>{if(/(?:^|\.)__proto__\./.test(t))return;let n=e,o=t.split(".",34);if(o.length>33)la();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++>=dm)la();n[s]=Object.create(null)}n=n[s]}})},la=()=>{throw Error("Nesting limit exceeded")};var si=(e)=>{let t=e.split("/");if(t[0]==="")t.shift();return t},ua=(e)=>{let{groups:t,path:r}=fm(e),i=si(r);return gm(i,t)},fm=(e)=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,i)=>{let n=`@${i}`;return t.push([n,r]),n}),{groups:t,path:e}},gm=(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},_t={},pa=(e,t)=>{if(e==="*")return"*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let i=`${e}#${t}`;if(!_t[i])if(r[2])_t[i]=t&&t[0]!==":"&&t[0]!=="*"?[i,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)];else _t[i]=[e,r[1],!0];return _t[i]}return null},ma=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,(r)=>{try{return t(r)}catch{return r}})}},ai=(e)=>ma(e,decodeURI),ci=(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),l=t.slice(r,a);return ai(l.includes("%25")?l.replace(/%25/g,"%2525"):l)}else if(n===63||n===35)break}return t.slice(r,i)};var fa=(e)=>{let t=ci(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},ae=(e,t,...r)=>{if(r.length)t=ae(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?ma(e,hm):e,oi=(e)=>{if(e.indexOf("+")!==-1)e=e.replace(/\+/g," ");return Nt(e)},ga=(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 l=e.charCodeAt(a+t.length+1);if(l===61){let d=a+t.length+2,u=e.indexOf("&",d);return oi(e.slice(d,u===-1?void 0:u))}else if(l==38||isNaN(l))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),l=e.indexOf("=",s);if(l>a&&a!==-1)l=-1;let d=e.slice(s+1,l===-1?a===-1?void 0:a:l);if(n)d=oi(d);if(s=a,d==="")continue;let u;if(l===-1)u="";else if(u=e.slice(l+1,a===-1?void 0:a),n)u=oi(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},ha=ga,ya=(e,t)=>ga(e,t,!0),hm=decodeURIComponent;var va=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 ha(this.url,e)}queries(e){return ya(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 da(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[sa](){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 ba={Stringify:1,BeforeStream:2,Stream:3},Sa=(e,t)=>{let r=new String(e);return r.isEscaped=!0,r.callbacks=t,r};var li=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((l)=>li(l,t,!1,i,n))).then(()=>n[0]));if(r)return Sa(await s,o);else return s};var ym="text/plain; charset=UTF-8",di=(e,t)=>({"Content-Type":e,...t}),Xe=(e,t)=>new Response(e,t),ui=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 va(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||=Xe(null,{headers:this.#a??=new Headers})}set res(e){if(this.#n&&e){e=Xe(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=Xe(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 Xe(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,di(ym,r));json=(e,t,r)=>this.#s(JSON.stringify(e),t,di("application/json",r));html=(e,t,r)=>{let i=(n)=>this.#s(n,t,di("text/html; charset=UTF-8",r));return typeof e==="object"?li(e,ba.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??=()=>Xe(),this.#l(this))};var pi=(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 l,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{l=await u(i,()=>s(a+1))}catch(p){if(p instanceof Error&&t)i.error=p,l=await t(p,i),d=!0;else throw p}else if(i.finalized===!1&&r)l=await r(i);if(l&&(i.finalized===!1||d))i.res=l;return i}};var Ra=["get","post","put","delete","options","patch","query"],Zt="Can not add a route since the matcher is already built.",Ht=class extends Error{};var mi="__COMPOSED_HANDLER";var vm=(e)=>e.text("404 Not Found",404),wa=(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)},Ia=class e{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...Ra,"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((l)=>{this.#o(a,this.#t,l)}),this}}),this.on=(n,o,...s)=>{for(let a of[o].flat()){this.#t=a;for(let l of[n].flat()){let d=l.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??ci:fa}#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=vm;errorHandler=wa;route(t,r){let i=this.basePath(t);return r.routes.map((n)=>{let o;if(r.errorHandler===wa)o=n.handler;else o=async(s,a)=>(await pi([],r.errorHandler)(s,()=>n.handler(s,a))).res,o[mi]=n.handler;i.#o(n.method,n.path,o,n.basePath)}),this}basePath(t){let r=this.#e();return r._basePath=ae(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=(l)=>l;else n=i.replaceRequest;let s=o?(l)=>{let d=o(l);return Array.isArray(d)?d:[d]}:(l)=>{let d=void 0;try{d=l.executionCtx}catch{}return[l.env,d]};n||=(()=>{let l=ae(this._basePath,t),d=l==="/"?0:l.length;return(u)=>{let p=new URL(u.url);return p.pathname=this.getPath(u).slice(d)||"/",new Request(p,u)}})();let a=async(l,d)=>{let u=await r(n(l.req.raw),...s(l));if(u)return u;await d()};return this.#o("ALL",ae(t,"*"),a),this}#o(t,r,i,n){r=ae(this._basePath,r);let o={basePath:n!==void 0?ae(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 ui(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 l=pi(s[0],this.errorHandler,this.#r);return(async()=>{try{let d=await l(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${ae("/",t)}`,r),i,n)};fire=()=>{addEventListener("fetch",(t)=>{t.respondWith(this.#n(t.request,t,void 0,t.request.method))})}};var k=()=>Object.create(null);var Wt=[];function fi(e,t){let r=this.buildAllMatchers(),i=(n,o)=>{let s=r[n]||r.ALL,a=s[2][o];if(a)return a;let l=o.match(s[0]);if(!l)return[[],Wt];let d=l.indexOf("",1);return[s[1][d],l]};return this.match=i,i(e,t)}var gi="[^/]+";var hi="(?:|/.*)",ce=Symbol(),xa=new Set(".\\+*[^]$()");function bm(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 Pa=class e{#t;#e;#r=k();insert(t,r,i,n,o){let s=this;for(let a=0,l=t.length;a<l;a++){let d=t[a],u=d.length===1?d==="*"?a===l-1?["","",".*"]:["","",gi]:null:d==="/*"?["","",hi]:d.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),p;if(u){let m=u[1],f=u[2]||"[^/]+";if(m&&u[2]){if(f===".*")throw ce;if(f=f.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(f))throw ce;if(f.length===1&&xa.has(f))throw ce}if(p=s.#r[f],!p){if(f!==".*"&&f!=="(?:|/.*)"){for(let g in s.#r)if((f.length>1||g.length>1)&&g!==".*"&&g!=="(?:|/.*)")throw ce}p=s.#r[f]=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 ce;p=s.#r[d]=new e}s=p}if(s.#t!==void 0)throw ce;s.#t=o?-1:r}buildRegExpStr(){let t=Object.keys(this.#r).sort(bm).map((r)=>{let i=this.#r[r],n=i.buildRegExpStr();return n===""?"":(typeof i.#e==="number"?`(${r})@${i.#e}`:xa.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 yi=class{#t={varIndex:0};#e=new Pa;#r=0;paths=k();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,(l)=>{let d=`@\\${s}`;return i[s]=[d,l],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 l=o.length-1;l>=0;l--)if(o[l].indexOf(a)!==-1){o[l]=o[l].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 Ca=k();function Ta(e){return Ca[e]??=new RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(t,r)=>r?`\\${r}`:t==="/*"?hi:t==="*"?".*":`/:${gi}`)}$`)}function qt(e,t){for(let r of Object.keys(e).sort((i,n)=>n.length-i.length))if(Ta(r).test(t))return[...e[r]]}var Jt=class{name="RegExpRouter";#t;#e;#r;constructor(){this.#t={["ALL"]:k()},this.#e={["ALL"]:k()},this.#r={["ALL"]:new yi}}#o(e,t){try{this.#r[e].insert(t,!/\*|\/:/.test(t))}catch(r){throw r===ce?new Ht(t):r}}add(e,t,r){let i=this.#t,n=this.#e;if(!i)throw Error(Zt);if(!i[e]){this.#r[e]=new yi;for(let a of[i,n]){a[e]=k();for(let l in a.ALL)a[e][l]=[...a.ALL[l]],this.#o(e,l)}}if(t==="/*")t="*";let o=e==="ALL"?Object.keys(i):[e];if(/\*$/.test(t)){let a=Ta(t);for(let l of o)if(!i[l][t])this.#o(l,t),i[l][t]=qt(i[l],t)||qt(i.ALL,t)||[];for(let l of[i,n])for(let d of o)for(let u in l[d])a.test(u)&&l[d][u].push([r,t]);return}let s=Ft(t)||[t];for(let a of s)for(let l of o){if(!n[l][a])this.#o(l,a),n[l][a]=qt(i[l],a)||qt(i.ALL,a)||[];n[l][a].push([r,a])}}match=fi;buildAllMatchers(){let e=k();for(let t of Object.keys(this.#e))e[t]=this.#i(t);return this.#t=this.#e=this.#r=void 0,Ca=k(),e}#i(e){let t=this.#t[e],r=this.#e[e],i=this.#r[e],n=k(),o=[],[s,a,l]=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(([f])=>[f,k()]),Wt];continue}o[m[0]]=p.map(([f,g])=>[f,i.paths[g][1].reduceRight((h,[S],b)=>(h[S]=l[m[1][b][1]],h),k())])}return[s,a.map((d)=>o[d]),n]}};var Ea=class{name="SmartRouter";#t=[];#e=[];constructor(e){this.#t=e.routers}add(e,t,r){if(!this.#e)throw Error(Zt);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 l=0,d=i.length;l<d;l++)a.add(...i[l]);s=a.match(e,t)}catch(l){if(l instanceof Ht)continue;throw l}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 vi=k(),Sm=0,Aa=class e{#t=[];#e=k();#r=[];#o;#i=vi;insert(t,r,i){let n=this,o=ua(r),s=new Set,a=0;for(let l of o){let d=o[++a],u=pa(l,d)||(d===void 0&&l&&l.indexOf("*")===l.length-1?l:null),p=Array.isArray(u),m=p?u[0]:u||l,f=n.#e[m]||=new e;if(u&&!f.#o)f.#o=u,n.#r.push(f);if(n=f,p)s.add(u[1])}n.#t.push({[t]:{handler:i,possibleKeys:[...s],score:++Sm}})}#n(t,r,i,n,o){for(let s=0,a=r.#t.length;s<a;s++){let l=r.#t[s],d=l[i]||l.ALL;if(d){d.params=k(),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=vi;let n=[this],o=si(r),s=[],a=o.length,l=null;for(let d=0;d<a;d++){let u=o[d],p=d===a-1,m=[];for(let g=0,h=n.length;g<h;g++){let S=n[g],b=S.#e[u];if(b)if(b.#i=S.#i,p){if(b.#e["*"])this.#n(i,b.#e["*"],t,S.#i);this.#n(i,b,t,S.#i)}else m.push(b);for(let y of S.#r){let v=y.#o,R=S.#i===vi?{}:{...S.#i};if(typeof v==="string"){if(v==="*"||u.startsWith(v.slice(0,-1))){if(this.#n(i,y,t,S.#i),v==="*")y.#i=R,m.push(y)}continue}let[,I,E]=v;if(!u&&E===!0)continue;if(E!==!0){if(!l){l=[];let fe=r[0]==="/"?1:0;for(let te=0;te<a;te++)l[te]=fe,fe+=o[te].length+1}let z=r.slice(l[d]),Pe=E.exec(z);if(Pe){if(R[I]=Pe[0],this.#n(i,y,t,S.#i,R),Pe[0].length===z.length&&y.#e["*"])this.#n(i,y.#e["*"],t,S.#i,R);for(let fe in y.#e){y.#i=R;let te=Pe[0].match(/\//g)?.length??0;(s[te]||=[]).push(y);break}continue}}if(E===!0||E.test(u))if(R[I]=u,p){if(this.#n(i,y,t,R,S.#i),y.#e["*"])this.#n(i,y.#e["*"],t,R,S.#i)}else y.#i=R,m.push(y)}}let f=s.shift();n=f?m.concat(f):m}if(i[1])i.sort((d,u)=>d.score-u.score);return[i.map(({handler:d,params:u})=>[d,u])]}};var bi=class{name="TrieRouter";#t=new Aa;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 Si=class extends Ia{constructor(e={}){super(e);this.router=e.router??new Ea({routers:[new Jt,new bi]})}};var Gt=(e)=>("server"in e.env)?e.env.server:e.env;var ze=/^\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 Ri=(e,t=Rm)=>{let r=e.match(/\.([a-zA-Z0-9]+?)$/);if(!r)return;return t[r[1].toLowerCase()]};var Rm={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 ka=(...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 ja={br:".br",zstd:".zst",gzip:".gz"},wm=Object.keys(ja),Im="index.html",Da=(e)=>{let t=e.root??"./",r=e.path,i=e.join??ka;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=ai(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,Im);let l=e.getContent,d=await l(a,n);if(d instanceof Response)return n.newResponse(d.body,d);if(d!=null){let u=e.mimes&&Ri(a,e.mimes)||Ri(a);if(n.header("Content-Type",u||"application/octet-stream"),e.precompressed&&(!u||ze.test(u))){let p=new Set(n.req.header("Accept-Encoding")?.split(",").map((m)=>m.trim()));for(let m of wm){if(!p.has(m))continue;let f=await l(a+ja[m],n);if(f){d=f,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 xm}from"fs/promises";import{join as Pm}from"path";var wi=(e={})=>async function(r,i){return Da({...e,getContent:async(s)=>{let a=Bun.file(s);return await a.exists()?a:null},join:Pm,isDir:async(s)=>{let a;try{a=(await xm(s)).isDirectory()}catch{}return a}})(r,i)};var Oa="x-hono-disable-ssg",rI=(()=>{try{return new Response("SSG is disabled",{status:404,headers:{[Oa]:"true"}})}catch{return null}})();var{write:WI}=Bun;var za=(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 Am=za((e,t)=>{let r=Gt(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 La=(e)=>e===32||e===9||e===10||e===13,Qt=(e,t)=>{while(t<e.length){if(!La(e.charCodeAt(t)))break;t++}return t},et=(e,t)=>{while(t>0){if(!La(e.charCodeAt(t-1)))break;t--}return t},Ma=(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]},km=(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},jm=(e,t)=>{t=Qt(e,t);let r=t,i,n,o=!1;while(r<e.length){let l=e.charCodeAt(r);if(l===61){i=e.slice(t,et(e,r)),r++;break}if(l===59)return[r+1,void 0,void 0,!0];if(l===44)return[r+1,void 0,void 0,!1];r++}if(i===void 0)return[r,void 0,void 0,!1];if(r=Qt(e,r),e.charCodeAt(r)===61){let l=Ma(e,r+1);return[l[0],i,void 0,l[1]]}let s=!1,a=r;while(r<e.length){let l=e.charCodeAt(r);if(s&&l===92)r++;else if(l===34){if(s){let d=Qt(e,r+1),u=e.charCodeAt(d);if(d<e.length&&!(u===59||u===44)){let p=Ma(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&&(l===59||l===44)){if(n=e.slice(a,et(e,r)),l===59)o=!0;r++;break}r++}return[r,i,n??e.slice(a,et(e,r)),o]},Dm=(e,t)=>{let r={type:"",params:Object.create(null),q:1};t=Qt(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,et(e,i)),i++,a===44)return[i,r.type?r:void 0];if(!r.type)return[km(e,i),void 0];break}i++}if(!r.type)return r.type=e.slice(t,et(e,e.length)),[e.length,r.type?r:void 0];let n,o,s;while(i<e.length){if([i,n,o,s]=jm(e,i),n&&o)r.params[n]=o;if(!s)break}return[i,r]},Ua=(e)=>{if(!e)return[];let t=[],r=0,i,n=!1,o;while(r<e.length)if([r,i]=Dm(e,r),i){if(i.q=Om(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},Om=(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 zm=["gzip","deflate"],Mm=/(?:^|,)\s*?no-transform\s*?(?:,|$)/i,Lm=(e,t)=>{if(e===void 0)return;let r=Ua(e),i=r.find((o)=>o.type==="*")?.q,n;for(let o of t){let s=r.find((l)=>l.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},Um=/(?:^|,)\s*accept-encoding\s*(?:,|$)/i,Ba=(e)=>{let t=e?.threshold??1024,r=e?.encoding?[e.encoding]:zm,i=e?.contentTypeFilter??ze,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 l=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"||l&&Number(l)<t||!n(s.res)||!Bm(s.res))return;let d=s.res.headers.get("Vary");if(d!=="*"&&!(d&&Um.test(d)))s.header("Vary",d?`${d}, Accept-Encoding`:"Accept-Encoding");let u=s.req.header("Accept-Encoding"),p=Lm(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 f=s.res.headers.get("ETag");if(f&&!f.startsWith("W/"))s.res.headers.set("ETag",`W/${f}`)}},Bm=(e)=>{let t=e.headers.get("Cache-Control");return!t||!Mm.test(t)};import{Readable as $a}from"stream";import{createDeflate as $m,createGzip as _m}from"zlib";var Fm=["gzip","deflate"],Nm=/(?:^|,)\s*?no-transform\s*?(?:,|$)/i,_a=(e)=>{if(typeof CompressionStream<"u")return Ba(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||!Zm(i.res)||!Hm(i.res))return;let s=i.req.header("Accept-Encoding"),a=e?.encoding??Fm.find((l)=>s?.includes(l));if(!a||!i.res.body)return;try{let l=a==="gzip"?_m():$m(),d=$a.fromWeb(i.res.body).pipe(l),u=$a.toWeb(d);i.res=new Response(u,i.res),i.res.headers.delete("Content-Length"),i.res.headers.set("Content-Encoding",a)}catch(l){console.error("Compression error:",l)}}},Zm=(e)=>{let t=e.headers.get("Content-Type");return t&&ze.test(t)},Hm=(e)=>{let t=e.headers.get("Cache-Control");return!t||!Nm.test(t)};var Wm=(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 Fa=async(e,t)=>{if(!e)return null;let r=void 0,i,n=0,o=async(a)=>{r=await t(Wm(r,a))},s=e.getReader();for(;;){let{value:a,done:l}=await s.read();if(l)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 f=new Uint8Array(new ArrayBuffer(Math.min(262144,Math.max(p,i.byteLength*2))));f.set(i.subarray(0,n)),i=f}i.set(a.subarray(d),n)}n=p;break}let m=262144-n;if(i?.byteLength!==262144){let f=new Uint8Array(new ArrayBuffer(262144));if(i)f.set(i.subarray(0,n));i=f}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 qm=["cache-control","content-location","date","etag","expires","vary"],Na=(e)=>e.replace(/^W\//,"");function Jm(e,t){return t!=null&&t.split(",").some((r)=>Na(r.trim())===Na(e))}function Gm(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??qm).map((n)=>n.toLowerCase())),r=e?.weak??!1,i=Gm(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 l=o.res,d=l.headers.get("ETag");if(!d){if(!i)return;let u=await Fa(l.clone().body,i);if(u===null)return;d=r?`W/"${u}"`:`"${u}"`}if(a==="*"||Jm(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[f,g]of m.entries())s[f]=g}let a=await t(e,s),l=typeof a==="object"&&a!==null&&"data"in a?a.data:a,d=Ha.safeParse(l),u=d.success?d.data:l,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 tt(e,t){return e===t||e.startsWith(t+Km)}var Wa="public, max-age=31536000, immutable";function Vm(e){return e.getRoutes?.()??[]}var Ym=255;class Vt{logger;options;routes=Object.freeze([]);productionServer=null;stopping=!1;transport=new WeakMap;async fillSitePage(e,t,r){let i=r.slot;if(!i)return;let n=Z(e,`.${t}`,"index.html");if(!tt(n,Z(e)))return;let o=Bun.file(n);if(!await o.exists())return;let s=`<div ${Ga}="${i.name}"></div>`,a=await o.text();if(!a.includes(s))return;let l=new Headers(r.headers);return l.delete("Content-Length"),l.delete("Content-Encoding"),l.delete("ETag"),l.set("Content-Type","text/html; charset=utf-8"),new Response(a.replace(s,()=>i.html),{status:r.status,headers:l})}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:Z(process.cwd(),e.productionDistDir),sharedImagesDir:Z(process.cwd(),e.sharedImagesDir),...e.previewDistDir&&{previewDistDir:Z(process.cwd(),e.previewDistDir)}}}async start(){if(this.productionServer){this.logger.warn("Webserver already running");return}this.stopping=!1,this.routes=Object.freeze([...Vm(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??Ym,fetch:async(i,n)=>{if(this.stopping)return new Response("Shutting down",{status:503,headers:{Connection:"close","Retry-After":"5"}});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(){let e=this.productionServer;if(e){this.stopping=!0;try{await na(e,{drainMs:this.options.shutdownDrainMs??ia,logger:this.logger,label:"Webserver"})}finally{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 Si;if(t.onError((r,i)=>{if(this.stopping)return this.logger.debug(`Request ended by the shutdown: ${i.req.method} ${i.req.path}: ${P(r)}`),i.text("Shutting down",503);if("getResponse"in r){let n=r.getResponse();return i.newResponse(n.body,n)}return console.error(r),i.text("Internal Server Error",500)}),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:P(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("/*",_a());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",Wa);else r.header("Cache-Control",e.defaultCache)}),t.use("/*",async(r,i)=>{if(r.req.path===Kt)return r.notFound();return i()}),t.use("/*",this.createCleanUrlMiddleware(e.distDir)),t.use("/*",wi({root:e.distDir})),t.get(qa,(r)=>r.body(Ja,200,{"Content-Type":"image/svg+xml; charset=utf-8","Cache-Control":"public, max-age=86400"})),t.notFound(async(r)=>{let i=Bun.file(Qm(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:P(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=oa(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 xi&&s.slot)return await this.fillSitePage(t.distDir,i,s)??s;if(r==="GET"&&s instanceof xi&&s.status===200){let a=Z(t.distDir,`.${i}`,"index.html");if(tt(a,Z(t.distDir))){let l=Bun.file(a);if(await l.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(l,{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=Z(this.options.sharedImagesDir,r);if(!tt(i,this.options.sharedImagesDir))return null;let n=Bun.file(i);if(!await n.exists())return null;return new Response(n,{headers:{"Cache-Control":Wa}})}createCleanUrlMiddleware(e){return async(t,r)=>{let i=t.req.path;if(i.includes(".")||i==="/"){await r();return}let n=Z(e,`.${i}`,"index.html");if(!tt(n,e)){await r();return}let o=Bun.file(n);if(await o.exists())return t.html(await o.text());let s=Z(e,`.${i}.html`);if(tt(s,e)){let a=Bun.file(s);if(await a.exists())return t.html(await a.text())}await r()}}}function Pi(e,t){return(r,i)=>e.send({type:Yt.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:Qa(t,"anonymous")}},sender:t})}var Ci=`<!DOCTYPE html>
11
11
  <html lang="en">
12
12
  <head>
13
13
  <meta charset="UTF-8">
@@ -74,12 +74,12 @@ ${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 Ka=c.strictObject({productionOutputDir:c.string().min(1),previewOutputDir:c.string().min(1),sharedImagesDir:c.string().min(1)});var H="webserver",K=`${H}:${H}`,nf="./dist/site-production",of="./dist/site-preview",sf="./dist/images";function af(e){return[...e].flatMap((t)=>{let r=t.getStaticSiteOutput?.();return r?[{...Ka.parse(r),ownerPluginId:t.id}]:[]})}function cf(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,l)=>{let d=e[o];if(r&&s!==void 0&&d!==void 0&&Va(d)!==Va(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??l};return{productionDistDir:n("productionDistDir",r?.productionOutputDir,"production site",nf),previewDistDir:n("previewDistDir",r?.previewOutputDir,"preview site",of),sharedImagesDir:n("sharedImagesDir",r?.sharedImagesDir,"shared images",sf)}}async function lf(e,t,r){let i=[e.productionDistDir,...t?[e.previewDistDir]:[]];for(let n of i){if(Xm(n))continue;await ef(n,{recursive:!0}),await tf(rf(n,"index.html"),Ci),r.debug(`Created site directory at ${n}`)}}function Xa(e){return e?{siteUrl:`https://${e}`,previewUrl:`https://${Ya(e)}`}:{siteUrl:void 0,previewUrl:void 0}}function ec(e){let{config:t,logger:r}=e,{siteUrl:i,previewUrl:n}=Xa(e.domain),o;return{start:async()=>{let s=cf(t,af(e.getPlugins()));await lf(s,t.preview,r),o??=new Vt({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:Pi(e.messageBus,H)}),await o.start()},stop:async()=>{await o?.stop()},healthCheck:async()=>{let s=o?.getStatus(),a=s?.running??!1,l=i??s?.productionUrl??`http://localhost:${t.port}`,d=n??s?.previewUrl??`http://localhost:${t.port}`,u=[];if(a){if(u.push(`Production: ${l}`),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?l:void 0}}}}}function tc(e,t){let{siteUrl:r,previewUrl:i}=Xa(t);if(!r)return{endpoints:[],interactions:[]};let n=e.preview&&i?i:void 0;return{endpoints:[{pluginId:H,label:"Site",url:r,priority:10},...n?[{pluginId:H,label:"Preview",url:n,priority:20,visibility:"admin"}]:[]],interactions:[{pluginId:H,id:"site",label:"Public site",description:"Visit the published public site for this brain.",href:r,kind:"human",priority:10},...n?[{pluginId:H,id:"preview",label:"Preview site",description:"Open the private preview build.",href:n,kind:"admin",priority:20,visibility:"admin"}]:[]]}}var df=["shell.legacy-binary-content"];async function rc(e,t){for(let r of df){let i=await e.scoped({namespace:r,schema:c.unknown()}).clear();if(i>0)t.info("Deleted retired runtime state",{namespace:r,cleared:i})}}var uf=250,pf=c.object({projectionBatch:c.object({operationId:c.string().min(1),childKey:c.string().min(1)})});class Ti{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=Ae(n),this.hooks=o}async boot(e){this.services.logger.debug("Starting Shell boot");let t=this.initializer;await Xt([()=>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 ra({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 ke(this.services.messageBus,ic,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:oc,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((l)=>{let d=pf.safeParse(JSON.parse(l.data));if(!d.success||d.data.projectionBatch.operationId!==s)return[];return[{jobId:l.id,childKey:d.data.projectionBatch.childKey,status:l.status,terminalAt:l.completedAt}]})),activationMode:this.role.projectionActivation});this.services.disposables.push(()=>n.dispose())}if(this.services.jobQueueService.finalizeHandlerRegistrations(),this.hooks.registerCoreDataSources(),this.role.serves)this.hooks.registerSystemCapabilities();if(e?.mode==="register-only"){this.services.logger.debug("Shell boot complete (register-only mode)");return}if(await rc(this.services.runtimeStateService,this.services.logger),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=uc();if(this.services.disposables.push(this.services.messageBus.subscribe(Ke.initialSyncCompleted,async(l)=>(s.resolve(cc.safeParse(l.payload).data?.success===!0),{success:!0}))),await this.emitPluginsRegistered())i=s.promise.then(async(l)=>{if(l)return this.settleStartupContent();this.services.logger.warn("Initial sync failed; ready-state defaults are not created")}).catch((l)=>{this.services.logger.error("Failed to settle startup content",l)});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(K))return;await this.services.daemonRegistry.start(K),this.services.logger.debug("Started the HTTP host before initial sync")}async emitPluginsRegistered(){let e=await this.services.messageBus.collect({type:Ke.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)&&ac.safeParse(t.data).data?.initialSyncPending===!0)}async settleStartupContent(){let e=await this.services.entityService.rewriteStoredForms();if(e.rewritten>0)this.services.logger.info("Brought stored entities to their stored form",{rewritten:e.rewritten});let t=await ke(this.services.messageBus,nc,{},"shell"),r=[...e.restated,...t.status==="unavailable"?[]:t.answers.flatMap((i)=>i.restated)];if(t.status!=="unavailable"&&t.failures.length>0)this.services.logger.warn("A plugin could not restate its stored content",{failures:t.failures.length});if(r.length>0)await be(this.services.messageBus,lc,{entities:r},"shell");await this.prepareReadyState(),await be(this.services.messageBus,dc,{timestamp:new Date().toISOString()},"shell"),this.services.logger.debug("Emitted startup content settled event")}async loadIdentityServices(){await Xt([()=>this.services.identityService.refreshCache(),()=>this.services.profileService.refreshCache(),()=>this.services.canonicalIdentityService.refreshCache()]),this.services.logger.debug("Identity services loaded")}async initializeIdentityServices(){await Xt([()=>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 sc(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 w.tryPromise({try:()=>e.backfillMissingEmbeddings(),catch:(i)=>i}).pipe(w.tap((i)=>w.sync(()=>{t.debug("Queued missing embedding backfill jobs",i)})),w.catch((i)=>w.sync(()=>{t.warn("Embedding backfill failed",i)}))).pipe(w.andThen(w.tryPromise({try:(i)=>e.awaitIndexReady({intervalMs:uf,signal:i}),catch:(i)=>i}).pipe(w.tap((i)=>w.sync(()=>{if(i.degraded)t.warn("Semantic index ready with degraded embeddings",i);else t.debug("Semantic index ready",i)})),w.catch((i)=>w.sync(()=>{t.warn("Semantic index readiness monitor stopped",i)})))))}}var mf=c.object({}),pc=c.string().regex(/^\d{4}-(0[1-9]|1[0-2])$/,"Expected YYYY-MM"),fc=c.array(c.string().min(1)).min(1).optional().describe("Only these entity types"),ff=c.object({entityTypes:fc,from:pc.optional().describe("First month, YYYY-MM"),to:pc.optional().describe("Last month, YYYY-MM")}),gf=c.object({staleDays:c.number().int().min(1).max(3650).default(90).describe("Days without an update before content counts as stale"),entityTypes:fc});function gc(e){let t=new mc;return t.register(er({type:"overview",description:"Entity counts by type, recent activity, and draft and published totals.",params:mf,handler:async(r,{entityService:i,visibilityScope:n})=>hf(i,n)})),t.register(er({type:"publishing-cadence",description:"Pieces per month, by type: counted in the month they were published, or created when never published.",params:ff,handler:async(r,{entityService:i,visibilityScope:n})=>vf(i,n,r)})),t.register(er({type:"content-health",description:"Drafts and content not updated for a long time.",params:gf,handler:async(r,{entityService:i,visibilityScope:n})=>bf(i,n,e,r)})),t}async function hf(e,t){let r=await e.getEntityCounts(t),i={},n=0;for(let{entityType:f,count:g}of r)i[f]=g,n+=g;let o=await Ei(e,t),s=Date.now(),a=s-604800000,l=s-2592000000,d=0,u=0;for(let f of o){let g=new Date(f.created).getTime();if(g>=a)d++;if(g>=l)u++}let p=yc(o),m=o.filter((f)=>f.metadata.status==="published");return{entityCounts:i,totalEntities:n,recentActivity:{last7days:d,last30days:u},contentHealth:{drafts:p.length,published:m.length}}}function yf(e){let t=e.metadata.publishedAt;return new Date(typeof t==="string"&&t?t:e.created)}function hc(e,t){return t?e.filter((r)=>t.includes(r.entityType)):e}async function vf(e,t,r){let i=hc(await Ei(e,t),r.entityTypes),n=new Map;for(let s of i){let a=yf(s);if(isNaN(a.getTime()))continue;let l=`${a.getUTCFullYear()}-${String(a.getUTCMonth()+1).padStart(2,"0")}`;if(r.from&&l<r.from||r.to&&l>r.to)continue;let d=n.get(l);if(!d)d={},n.set(l,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 l=0;for(let d of Object.values(a))l+=d;return{month:s,counts:a,total:l}})}}async function bf(e,t,r,i){let n=hc(await Ei(e,t),i.entityTypes),o=yc(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,l=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:l}}function yc(e){return e.filter((t)=>t.metadata.status==="draft")}async function Ei(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 rt{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 Ai extends rt{constructor(){super((e)=>vc.parse(e),(e)=>e.url)}}class ki extends rt{constructor(){super((e)=>bc.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 Sf=["/health","/images"],Rf=new Set([Kt]),wf=new Set(Rc),If=new Set(["GET","POST","PUT","DELETE"]);function wc(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 Ic(e){return Rf.has(e)||Sf.some((t)=>e===t||e.startsWith(`${t}/`))}function ji(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&&Ic(e))throw Error(`Invalid HTTP route path "${e}" declared by plugin "${t}"`)}function xc(e,t,r){if(!e.has(t))throw Error(`Invalid HTTP route method "${t}" declared by plugin "${r}"`)}function xf(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 Pf(e,t){ji(t.path,e.pluginId);let r=t.method??"GET";xc(wf,r,e.pluginId);let i=t.match??"exact";xf(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)=>!Ic(o)&&n(o)}:{},handler:t.handler})}function Cf(e,t){ji(t.path,e.pluginId,!1);let r=`/api/${e.pluginId}${t.path}`;if(ji(r,e.pluginId),xc(If,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 Tf(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 Ef(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 tr{routes;manifest;apiRoutes;webRoutes;static createFresh(){return new tr}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(Pf(n,o)),r.push(Object.freeze({pluginId:n.pluginId,fullPath:o.path,definition:Object.freeze({...o})}));for(let o of n.apiRoutes){let s=Cf(n,o);t.push(s),i.push(Object.freeze({pluginId:n.pluginId,fullPath:s.fullPath,definition:s.definition}))}}return Tf(t),this.routes=Object.freeze(t),this.manifest=Ef(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(async()=>{let{entityService:r}=t;if(Af(r))await r.releaseDatabaseLease()}),e.addFinalizer(()=>t.pluginManager.shutdownPlugins()),e.addFinalizer(async()=>{if(t.daemonRegistry.has(K))await t.daemonRegistry.unregister(K)}),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"))}function Af(e){return"releaseDatabaseLease"in e&&typeof e.releaseDatabaseLease==="function"}function Cc(e){return Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength)}var kf=c.discriminatedUnion("kind",[c.object({kind:c.literal("all")}).strict().describe("Search across all entity types"),c.object({kind:c.literal("type"),entityType:c.string().min(1).describe("Entity type to search")}).strict().describe("Search within one entity type")]),Ec=c.object({query:c.string().describe("Search term"),scope:kf.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:c.number().optional().describe("Maximum number of results"),minScore:c.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:c.boolean().optional().describe("Include queued/failed generation stubs in results")}),Ac=c.object({entityType:c.string().describe("Entity type"),id:c.string().describe("Entity ID, slug, or title"),part:c.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.")}),kc=c.object({entityType:c.string().describe("Entity type to list"),status:c.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:c.number().optional().describe("Maximum number of results (default: 20)")}),jc=c.string().min(1).describe("Upload id from the conversation's upload refs"),Dc=c.object({kind:c.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:c.string().optional().describe("Stored user message ID in this conversation; omit for the latest user message."),boundaryMode:c.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:c.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:c.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:c.string().optional().describe("Internal source hash returned with the confirmation; omit on the initial request.")}).strict(),Oc=c.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."),nt=c.object({kind:c.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:c.array(c.strictObject({id:jc,transform:Oc,title:c.string().optional().describe("Only a title the user named for this file."),fields:c.record(c.string(),c.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(),Di=c.discriminatedUnion("kind",[c.object({kind:c.literal("text").describe("Store exact/direct user-provided content without generation"),content:c.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(),Dc,c.object({kind:c.literal("url").describe("Create URL/domain-backed entities such as links"),url:c.string().min(1).describe("URL or domain to create from; preserve a bare domain as provided instead of adding a scheme.")}).strict(),c.strictObject({kind:c.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:jc,transform:Oc},{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}),nt,c.object({kind:c.literal("prior-response").describe("Save a previous assistant response as durable content, especially an assistant summary or answer about an upload."),messageId:c.string().min(1).optional().describe("Stored assistant message ID; omit for latest savable")}).strict(),c.object({kind:c.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:c.string().min(1).describe("Source entity type, such as note"),entityId:c.string().min(1).describe("Source entity ID, slug, or exact title copied from the user's request or a prior tool result")}).strict()]),jf=c.discriminatedUnion("kind",[c.object({kind:c.literal("prompt").describe("A new non-image entity from a broad prompt; this branch has no source field."),entityType:c.string().min(1).describe("Entity type to generate from the prompt. Do not use image here; use standalone-image or cover-image."),title:c.string().optional().describe("Title for the generated entity"),prompt:c.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(),c.object({kind:c.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:c.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:c.string().optional().describe("Title for the generated entity"),source:c.object({entityType:c.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:c.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."),additionalSourceIds:c.array(c.string().min(1)).optional().describe("More source IDs of the same type."),prompt:c.string().min(1).optional().describe("Direction from the user's request, without added voice, tone or engagement directions; the style guide supplies the voice. Omit if none is given.")}).strict(),c.object({kind:c.literal("standalone-image").describe("An unattached image; never a substitute for a requested cover."),title:c.string().optional().describe("Title for the generated image"),prompt:c.string().min(1).describe("Prompt for creating an unattached image. Not for cover images requested for a generated post/entity.")}).strict(),c.object({kind:c.literal("cover-image").describe("An image attached as coverImageId to an existing entity whose real id is known."),target:c.object({entityType:c.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:c.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:c.string().optional().describe("Title for the generated image"),prompt:c.string().min(1).describe("Prompt for creating the cover image")}).strict(),c.object({kind:c.literal("attachment").describe("Generate a deterministic durable artifact from an existing entity attachment provider"),source:c.object({entityType:c.string().min(1).describe("Source entity type"),entityId:c.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:c.string().min(1).describe('Source artifact type such as "carousel", "printable", or "og-image"'),title:c.string().optional().describe("Title for the generated artifact"),replace:c.boolean().optional().describe("Set true for regenerate, replace, refresh, or update requests so a deterministic artifact is regenerated instead of reused")}).strict()]),rr=c.object({entityType:c.string().describe("Entity type to create. Use wish for explicitly saved or tracked unmet requested capabilities or outcomes."),title:c.string().optional().describe("Title for a new entity. For an upload, give only a title the user named; otherwise leave it out, so the first heading of the file titles it. Leave it out when saving several uploads: each item in source.items takes its own title."),visibility:Tc.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:Di.describe("Concrete source selector. Use exactly one source branch. For AI generation or source-derived artifacts, use system_generate instead."),fields:c.record(c.string(),c.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:c.boolean().optional().describe("Create a new copy intentionally"),confirmed:c.literal(!0).optional().describe("Confirm the creation"),confirmationToken:c.string().optional().describe("Internal confirmation token returned by the confirmation flow")}).strict(),zc=c.object({operation:jf.describe("Exactly one generation operation."),confirmed:c.literal(!0).optional().describe("Confirm generation"),confirmationToken:c.string().optional().describe("Internal confirmation token returned by the confirmation flow")}).strict(),Df=c.object({oldText:c.string().min(1).describe("Exact text occurring once in the original stored Markdown. Include enough context to be unique."),newText:c.string().describe("Literal replacement text; empty string deletes oldText.")}).strict(),it="An update operation is exactly one of `fields`, `content`, `edits` or `source`.",Oi=c.strictObject({fields:c.record(c.string(),c.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:c.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:c.array(Df).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:Dc.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 ie(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(", ")}: ${it}`}}).refine((e)=>[e.fields,e.content,e.edits,e.source].filter((t)=>t!==void 0).length===1,{message:it}).describe(it),ir=c.object({entityType:c.string().describe("Entity type"),id:c.string().describe("Entity ID, slug, or title"),operation:Oi.describe("Exactly one update operation"),confirmed:c.literal(!0).optional().describe("Confirm the update"),confirmationToken:c.string().optional().describe("Internal confirmation token returned by the confirmation flow"),contentHash:c.string().optional().describe("Content hash for optimistic concurrency")}).strict(),Mc=c.object({entityType:c.string().describe("Entity type"),id:c.string().describe("Entity ID"),confirmed:c.literal(!0).optional().describe("Confirm the deletion"),confirmationToken:c.string().optional().describe("Internal confirmation token returned by the confirmation flow")}),OP=c.object({entityType:c.string().describe("Entity type to extract"),source:c.string().optional().describe("Source entity ID \u2014 omit for batch"),mode:c.enum(["derive","rebuild"]).optional().describe("Batch mode: project incrementally or rebuild from scratch"),confirmed:c.literal(!0).optional().describe("Confirm destructive rebuild"),confirmationToken:c.string().optional().describe("Internal confirmation token returned by the confirmation flow")}),Lc=c.object({batchId:c.string().optional().describe("Specific batch ID to check"),jobTypes:c.array(c.string()).optional().describe("Filter by job types")}),Of=c.object({entityType:c.string().optional(),entityId:c.string().optional(),attachmentType:c.string().optional()}),zf=c.object({mediaType:c.string(),url:c.string(),downloadUrl:c.string().optional(),previewUrl:c.string().optional(),filename:c.string().optional(),sizeBytes:c.number().optional(),source:Of.optional()}),zP=c.object({entityId:c.string().optional(),status:c.enum(["created","generating"]),jobId:c.string().optional(),attachment:zf.optional()}),MP=c.object({status:c.literal("extracting"),jobId:c.string(),entityType:c.string(),source:c.string().optional(),mode:c.enum(["derive","rebuild"]).optional()});function $c(e,t,r){return r==="create"?e.getCreateFieldsSchema(t):e.getEditableFieldsSchema(t)}function _c(e){if(e instanceof c.ZodOptional||e instanceof c.ZodNullable||e instanceof c.ZodDefault)return _c(e.unwrap());return e instanceof c.ZodType?e:void 0}function Uc(e){try{let{$schema:t,...r}=c.toJSONSchema(e,{target:"draft-7",io:"input"});return r}catch{return}}function Mf(e){return Bc({type:"object",properties:{value:e},required:["value"]})!==void 0}function Fc(e,t){let r=new Map,i=new Map,n=e.getAllEntityTypes().filter((d)=>!t.neverWrites?.(d,t.on));for(let d of n){let u=$c(e,d,t.on);for(let[p,m]of Object.entries(u?.shape??{})){if(t.omit?.includes(p))continue;let f=_c(m),g=f&&Uc(f);if(!f||!g||!Mf(g))continue;let h=r.get(p)??new Map;h.set(JSON.stringify(g),f),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 f=m.length>0?c.union([p,...m]):p,g=JSON.stringify(Uc(f)),h=o.get(g)??{value:f,names:[]};h.names.push(d),o.set(g,h)}let s=[...o.values()].map(({value:d,names:u})=>{let[p,...m]=u,f=u.map((g)=>{let h=i.get(g)??[];return`${g} (${h.length===n.length?"every type":h.join(", ")})`}).join("; ");return c.strictObject({name:(m.length>0&&p!==void 0?c.enum([p,...m]):c.literal(p??"")).describe(`The field, set only on the entity types named: ${f}.`),value:t.on==="update"?d.nullable():d})}),[a,...l]=s;return c.array(a?l.length>0?c.union([a,...l]):a:c.never())}function Lf(e){return Object.fromEntries((Array.isArray(e)?e:[]).flatMap((t)=>V(t)&&typeof t.name==="string"?[[t.name,t.value]]:[]))}function nr(e,t,r,i){if(!r)return;let{allow:n}=i,o=new Set(Object.keys($c(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(", "),l=[...o].join(", ")||"none";return`A ${t} has no ${s.length>1?"fields":"field"} ${a} a caller can set; its fields are ${l}.`}function Mi(e){return"fields"in e&&e.fields!==void 0?{...e,fields:Lf(e.fields)}:e}function Nc(e,t){return{prepare:()=>e.ensureGroupingsCurrent(),inputSchema:()=>{let r=Fc(e,{on:"create",omit:["visibility"],...t&&{neverWrites:t}}),i=nt.shape.items.element,n=nt.extend({items:c.array(i.extend({fields:r.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)}),[o,...s]=Di.options.map((a)=>a===nt?n:a);if(!o)throw Error("system_create has no source branches");return{...rr.shape,source:c.discriminatedUnion("kind",[o,...s]).describe("Concrete source selector. Use exactly one source branch. For AI generation or source-derived artifacts, use system_generate instead."),fields:r.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, and never fill in one the user did not state, such as a default section: leave it out, and the tool asks for it.")}},toToolInput:(r)=>{let i=r.source;return Mi({...r,...V(i)&&Array.isArray(i.items)&&{source:{...i,items:i.items.map((n)=>V(n)?Mi(n):n)}}})}}}function zi(e){let t=e.unwrap();return e.description?t.describe(e.description):t}function Zc(e,t){let{content:r,edits:i,source:n}=Oi.shape;return{prepare:()=>e.ensureGroupingsCurrent(),inputSchema:()=>({...ir.shape,operation:c.union([c.strictObject({fields:Fc(e,{on:"update",...t&&{neverWrites:t}}).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.")}),c.strictObject({content:zi(r)}),c.strictObject({edits:zi(i)}),c.strictObject({source:zi(n)})]).describe("Exactly one update operation")}),toToolInput:(o)=>{let s=o.operation;return V(s)?{...o,operation:Mi(s)}:o}}}function B(e,t,r,i){try{e.permissionService.assertEntityActionAllowed(t,r,i.userPermissionLevel);return}catch(n){if(n instanceof Error)return{success:!1,error:n.message};throw n}}function Me(e){return(t,r)=>e.getEntityActionRequiredLevel(t,r)==="never"}var Uf="system";function X(e){return{kind:"error",result:e}}function T(e,t){return X({success:!1,error:e,...t!==void 0&&{code:t}})}function W(e,t,r,i,n={}){let{visibility:o="admin",sideEffects:s}=n;return{name:`${Uf}_${e}`,description:t,inputSchema:r.shape,handler:async(a,l)=>{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,l)}catch(u){return{success:!1,error:P(u)}}},visibility:o,...s?{sideEffects:s}:{}}}function sr(e){return{interfaceType:e.interfaceType,actor:e.actor,userPermissionLevel:e.userPermissionLevel??"public",...e.channelId&&{channelId:e.channelId},...e.channelName&&{channelName:e.channelName}}}async function Hc(e,t,r,i){let n=await t(r,sr(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=B(e,o.entityType,"create",i);if(s)return{kind:"error",result:s};return{kind:"continue",createInput:o}}function Le(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 Ue(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 Li(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 ar(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var Bf={base:"note"};function Wc(e){return Bf[e]??e.replaceAll("-"," ")}function Be(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 qc(e){return!!e&&Object.keys(e.shape).length>0}async function Jc(e,t,r){if(!r)return!1;let i=await e.conversationService.getMessages(r,{limit:100});for(let n of i){let s=or(n.metadata)?.attachments;if(!Array.isArray(s))continue;for(let a of s){if(!ie(a))continue;let l=a.source;if(!ie(l))continue;if(l.kind===t.kind&&l.id===t.id)return!0}}return!1}async function cr(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"&&!B(e,t.entityType,"delete",r))return{kind:"ok",value:{entityType:i.entityType,id:i.id}};return T(`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 Gc(e){return`Replaces: failed ${e.entityType} "${e.id}"`}async function Qc(e,t){if(!t)return;try{await e.entityService.deleteEntity(t);return}catch(r){return{success:!1,error:P(r,"Failed to replace the failed entity")}}}function lr(e,t,r){let i=Le(e,t);if(i)return X(i);let n=B(e,t,"create",r);if(n)return X(n);return{kind:"ok",value:{interceptor:e.entityRegistry.getCreateInterceptor(t)}}}async function dr(e){let{gate:t,input:r,replacesFailed:i}=e;if(r.confirmed){let d=t.validateConfirmed(r.confirmationToken,r);if(d)return d;return e.run()}let{toolName:n,summary:o,completionSummary:s,preview:a,args:l}=e.confirmation();return{needsConfirmation:!0,toolName:n,summary:o,...s!==void 0&&{completionSummary:s},preview:i?`${a}
77
+ </html>`;var Ka=c.strictObject({productionOutputDir:c.string().min(1),previewOutputDir:c.string().min(1),sharedImagesDir:c.string().min(1)});var H="webserver",K=`${H}:${H}`,nf="./dist/site-production",of="./dist/site-preview",sf="./dist/images";function af(e){return[...e].flatMap((t)=>{let r=t.getStaticSiteOutput?.();return r?[{...Ka.parse(r),ownerPluginId:t.id}]:[]})}function cf(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,l)=>{let d=e[o];if(r&&s!==void 0&&d!==void 0&&Va(d)!==Va(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??l};return{productionDistDir:n("productionDistDir",r?.productionOutputDir,"production site",nf),previewDistDir:n("previewDistDir",r?.previewOutputDir,"preview site",of),sharedImagesDir:n("sharedImagesDir",r?.sharedImagesDir,"shared images",sf)}}async function lf(e,t,r){let i=[e.productionDistDir,...t?[e.previewDistDir]:[]];for(let n of i){if(Xm(n))continue;await ef(n,{recursive:!0}),await tf(rf(n,"index.html"),Ci),r.debug(`Created site directory at ${n}`)}}function Xa(e){return e?{siteUrl:`https://${e}`,previewUrl:`https://${Ya(e)}`}:{siteUrl:void 0,previewUrl:void 0}}function ec(e){let{config:t,logger:r}=e,{siteUrl:i,previewUrl:n}=Xa(e.domain),o;return{start:async()=>{let s=cf(t,af(e.getPlugins()));await lf(s,t.preview,r),o??=new Vt({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:Pi(e.messageBus,H)}),await o.start()},stop:async()=>{await o?.stop()},healthCheck:async()=>{let s=o?.getStatus(),a=s?.running??!1,l=i??s?.productionUrl??`http://localhost:${t.port}`,d=n??s?.previewUrl??`http://localhost:${t.port}`,u=[];if(a){if(u.push(`Production: ${l}`),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?l:void 0}}}}}function tc(e,t){let{siteUrl:r,previewUrl:i}=Xa(t);if(!r)return{endpoints:[],interactions:[]};let n=e.preview&&i?i:void 0;return{endpoints:[{pluginId:H,label:"Site",url:r,priority:10},...n?[{pluginId:H,label:"Preview",url:n,priority:20,visibility:"admin"}]:[]],interactions:[{pluginId:H,id:"site",label:"Public site",description:"Visit the published public site for this brain.",href:r,kind:"human",priority:10},...n?[{pluginId:H,id:"preview",label:"Preview site",description:"Open the private preview build.",href:n,kind:"admin",priority:20,visibility:"admin"}]:[]]}}var df=["shell.legacy-binary-content"];async function rc(e,t){for(let r of df){let i=await e.scoped({namespace:r,schema:c.unknown()}).clear();if(i>0)t.info("Deleted retired runtime state",{namespace:r,cleared:i})}}var uf=250,pf=c.object({projectionBatch:c.object({operationId:c.string().min(1),childKey:c.string().min(1)})});class Ti{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=Ae(n),this.hooks=o}async boot(e){this.services.logger.debug("Starting Shell boot");let t=this.initializer;await Xt([()=>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 ra({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 ke(this.services.messageBus,ic,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:oc,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((l)=>{let d=pf.safeParse(JSON.parse(l.data));if(!d.success||d.data.projectionBatch.operationId!==s)return[];return[{jobId:l.id,childKey:d.data.projectionBatch.childKey,status:l.status,terminalAt:l.completedAt}]})),activationMode:this.role.projectionActivation});this.services.disposables.push(()=>n.dispose())}if(this.services.jobQueueService.finalizeHandlerRegistrations(),this.hooks.registerCoreDataSources(),this.role.serves)this.hooks.registerSystemCapabilities();if(e?.mode==="register-only"){this.services.logger.debug("Shell boot complete (register-only mode)");return}if(await rc(this.services.runtimeStateService,this.services.logger),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=uc();if(this.services.disposables.push(this.services.messageBus.subscribe(Ke.initialSyncCompleted,async(l)=>(s.resolve(cc.safeParse(l.payload).data?.success===!0),{success:!0}))),await this.emitPluginsRegistered())i=s.promise.then(async(l)=>{if(l)return this.settleStartupContent();this.services.logger.warn("Initial sync failed; ready-state defaults are not created")}).catch((l)=>{this.services.logger.error("Failed to settle startup content",l)});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(K))return;await this.services.daemonRegistry.start(K),this.services.logger.debug("Started the HTTP host before initial sync")}async emitPluginsRegistered(){let e=await this.services.messageBus.collect({type:Ke.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)&&ac.safeParse(t.data).data?.initialSyncPending===!0)}async settleStartupContent(){let e=await this.services.entityService.rewriteStoredForms();if(e.rewritten>0)this.services.logger.info("Brought stored entities to their stored form",{rewritten:e.rewritten});let t=await ke(this.services.messageBus,nc,{},"shell"),r=[...e.restated,...t.status==="unavailable"?[]:t.answers.flatMap((i)=>i.restated)];if(t.status!=="unavailable"&&t.failures.length>0)this.services.logger.warn("A plugin could not restate its stored content",{failures:t.failures.length});if(r.length>0)await Se(this.services.messageBus,lc,{entities:r},"shell");await this.prepareReadyState(),await Se(this.services.messageBus,dc,{timestamp:new Date().toISOString()},"shell"),this.services.logger.debug("Emitted startup content settled event")}async loadIdentityServices(){await Xt([()=>this.services.identityService.refreshCache(),()=>this.services.profileService.refreshCache(),()=>this.services.canonicalIdentityService.refreshCache()]),this.services.logger.debug("Identity services loaded")}async initializeIdentityServices(){await Xt([()=>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 sc(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 w.tryPromise({try:()=>e.backfillMissingEmbeddings(),catch:(i)=>i}).pipe(w.tap((i)=>w.sync(()=>{t.debug("Queued missing embedding backfill jobs",i)})),w.catch((i)=>w.sync(()=>{t.warn("Embedding backfill failed",i)}))).pipe(w.andThen(w.tryPromise({try:(i)=>e.awaitIndexReady({intervalMs:uf,signal:i}),catch:(i)=>i}).pipe(w.tap((i)=>w.sync(()=>{if(i.degraded)t.warn("Semantic index ready with degraded embeddings",i);else t.debug("Semantic index ready",i)})),w.catch((i)=>w.sync(()=>{t.warn("Semantic index readiness monitor stopped",i)})))))}}var mf=c.object({}),pc=c.string().regex(/^\d{4}-(0[1-9]|1[0-2])$/,"Expected YYYY-MM"),fc=c.array(c.string().min(1)).min(1).optional().describe("Only these entity types"),ff=c.object({entityTypes:fc,from:pc.optional().describe("First month, YYYY-MM"),to:pc.optional().describe("Last month, YYYY-MM")}),gf=c.object({staleDays:c.number().int().min(1).max(3650).default(90).describe("Days without an update before content counts as stale"),entityTypes:fc});function gc(e){let t=new mc;return t.register(er({type:"overview",description:"Entity counts by type, recent activity, and draft and published totals.",params:mf,handler:async(r,{entityService:i,visibilityScope:n})=>hf(i,n)})),t.register(er({type:"publishing-cadence",description:"Pieces per month, by type: counted in the month they were published, or created when never published.",params:ff,handler:async(r,{entityService:i,visibilityScope:n})=>vf(i,n,r)})),t.register(er({type:"content-health",description:"Drafts and content not updated for a long time.",params:gf,handler:async(r,{entityService:i,visibilityScope:n})=>bf(i,n,e,r)})),t}async function hf(e,t){let r=await e.getEntityCounts(t),i={},n=0;for(let{entityType:f,count:g}of r)i[f]=g,n+=g;let o=await Ei(e,t),s=Date.now(),a=s-604800000,l=s-2592000000,d=0,u=0;for(let f of o){let g=new Date(f.created).getTime();if(g>=a)d++;if(g>=l)u++}let p=yc(o),m=o.filter((f)=>f.metadata.status==="published");return{entityCounts:i,totalEntities:n,recentActivity:{last7days:d,last30days:u},contentHealth:{drafts:p.length,published:m.length}}}function yf(e){let t=e.metadata.publishedAt;return new Date(typeof t==="string"&&t?t:e.created)}function hc(e,t){return t?e.filter((r)=>t.includes(r.entityType)):e}async function vf(e,t,r){let i=hc(await Ei(e,t),r.entityTypes),n=new Map;for(let s of i){let a=yf(s);if(isNaN(a.getTime()))continue;let l=`${a.getUTCFullYear()}-${String(a.getUTCMonth()+1).padStart(2,"0")}`;if(r.from&&l<r.from||r.to&&l>r.to)continue;let d=n.get(l);if(!d)d={},n.set(l,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 l=0;for(let d of Object.values(a))l+=d;return{month:s,counts:a,total:l}})}}async function bf(e,t,r,i){let n=hc(await Ei(e,t),i.entityTypes),o=yc(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,l=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:l}}function yc(e){return e.filter((t)=>t.metadata.status==="draft")}async function Ei(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 rt{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 Ai extends rt{constructor(){super((e)=>vc.parse(e),(e)=>e.url)}}class ki extends rt{constructor(){super((e)=>bc.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 Sf=["/health","/images"],Rf=new Set([Kt]),wf=new Set(Rc),If=new Set(["GET","POST","PUT","DELETE"]);function wc(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 Ic(e){return Rf.has(e)||Sf.some((t)=>e===t||e.startsWith(`${t}/`))}function ji(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&&Ic(e))throw Error(`Invalid HTTP route path "${e}" declared by plugin "${t}"`)}function xc(e,t,r){if(!e.has(t))throw Error(`Invalid HTTP route method "${t}" declared by plugin "${r}"`)}function xf(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 Pf(e,t){ji(t.path,e.pluginId);let r=t.method??"GET";xc(wf,r,e.pluginId);let i=t.match??"exact";xf(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)=>!Ic(o)&&n(o)}:{},handler:t.handler})}function Cf(e,t){ji(t.path,e.pluginId,!1);let r=`/api/${e.pluginId}${t.path}`;if(ji(r,e.pluginId),xc(If,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 Tf(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 Ef(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 tr{routes;manifest;apiRoutes;webRoutes;static createFresh(){return new tr}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(Pf(n,o)),r.push(Object.freeze({pluginId:n.pluginId,fullPath:o.path,definition:Object.freeze({...o})}));for(let o of n.apiRoutes){let s=Cf(n,o);t.push(s),i.push(Object.freeze({pluginId:n.pluginId,fullPath:s.fullPath,definition:s.definition}))}}return Tf(t),this.routes=Object.freeze(t),this.manifest=Ef(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(async()=>{let{entityService:r}=t;if(Af(r))await r.releaseDatabaseLease()}),e.addFinalizer(()=>t.pluginManager.shutdownPlugins()),e.addFinalizer(async()=>{if(t.daemonRegistry.has(K))await t.daemonRegistry.unregister(K)}),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"))}function Af(e){return"releaseDatabaseLease"in e&&typeof e.releaseDatabaseLease==="function"}function Cc(e){return Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength)}var kf=c.discriminatedUnion("kind",[c.object({kind:c.literal("all")}).strict().describe("Search across all entity types"),c.object({kind:c.literal("type"),entityType:c.string().min(1).describe("Entity type to search")}).strict().describe("Search within one entity type")]),Ec=c.object({query:c.string().describe("Search term"),scope:kf.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:c.number().optional().describe("Maximum number of results"),minScore:c.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:c.boolean().optional().describe("Include queued/failed generation stubs in results")}),Ac=c.object({entityType:c.string().describe("Entity type"),id:c.string().describe("Entity ID, slug, or title"),part:c.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.")}),kc=c.object({entityType:c.string().describe("Entity type to list"),status:c.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:c.number().optional().describe("Maximum number of results (default: 20)")}),jc=c.string().min(1).describe("Upload id from the conversation's upload refs"),Dc=c.object({kind:c.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:c.string().optional().describe("Stored user message ID in this conversation; omit for the latest user message."),boundaryMode:c.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:c.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:c.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:c.string().optional().describe("Internal source hash returned with the confirmation; omit on the initial request.")}).strict(),Oc=c.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."),nt=c.object({kind:c.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:c.array(c.strictObject({id:jc,transform:Oc,title:c.string().optional().describe("Only a title the user named for this file."),fields:c.record(c.string(),c.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(),Di=c.discriminatedUnion("kind",[c.object({kind:c.literal("text").describe("Store exact/direct user-provided content without generation"),content:c.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(),Dc,c.object({kind:c.literal("url").describe("Create URL/domain-backed entities such as links"),url:c.string().min(1).describe("URL or domain to create from; preserve a bare domain as provided instead of adding a scheme.")}).strict(),c.strictObject({kind:c.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:jc,transform:Oc},{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}),nt,c.object({kind:c.literal("prior-response").describe("Save a previous assistant response as durable content, especially an assistant summary or answer about an upload."),messageId:c.string().min(1).optional().describe("Stored assistant message ID; omit for latest savable")}).strict(),c.object({kind:c.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:c.string().min(1).describe("Source entity type, such as note"),entityId:c.string().min(1).describe("Source entity ID, slug, or exact title copied from the user's request or a prior tool result")}).strict()]),jf=c.discriminatedUnion("kind",[c.object({kind:c.literal("prompt").describe("A new non-image entity from a broad prompt; this branch has no source field."),entityType:c.string().min(1).describe("Entity type to generate from the prompt. Do not use image here; use standalone-image or cover-image."),title:c.string().optional().describe("Title for the generated entity"),prompt:c.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(),c.object({kind:c.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:c.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:c.string().optional().describe("Title for the generated entity"),source:c.object({entityType:c.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:c.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."),additionalSourceIds:c.array(c.string().min(1)).optional().describe("More source IDs of the same type."),prompt:c.string().min(1).optional().describe("Direction from the user's request, without added voice, tone or engagement directions; the style guide supplies the voice. Omit if none is given.")}).strict(),c.object({kind:c.literal("standalone-image").describe("An unattached image; never a substitute for a requested cover."),title:c.string().optional().describe("Title for the generated image"),prompt:c.string().min(1).describe("Prompt for creating an unattached image. Not for cover images requested for a generated post/entity.")}).strict(),c.object({kind:c.literal("cover-image").describe("An image attached as coverImageId to an existing entity whose real id is known."),target:c.object({entityType:c.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:c.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:c.string().optional().describe("Title for the generated image"),prompt:c.string().min(1).describe("Prompt for creating the cover image")}).strict(),c.object({kind:c.literal("attachment").describe("Generate a deterministic durable artifact from an existing entity attachment provider"),source:c.object({entityType:c.string().min(1).describe("Source entity type"),entityId:c.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:c.string().min(1).describe('Source artifact type such as "carousel", "printable", or "og-image"'),title:c.string().optional().describe("Title for the generated artifact"),replace:c.boolean().optional().describe("Set true for regenerate, replace, refresh, or update requests so a deterministic artifact is regenerated instead of reused")}).strict()]),rr=c.object({entityType:c.string().describe("Entity type to create. Use wish for explicitly saved or tracked unmet requested capabilities or outcomes."),title:c.string().optional().describe("Title for a new entity. For an upload, give only a title the user named; otherwise leave it out, so the first heading of the file titles it. Leave it out when saving several uploads: each item in source.items takes its own title."),visibility:Tc.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:Di.describe("Concrete source selector. Use exactly one source branch. For AI generation or source-derived artifacts, use system_generate instead."),fields:c.record(c.string(),c.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:c.boolean().optional().describe("Create a new copy intentionally"),confirmed:c.literal(!0).optional().describe("Confirm the creation"),confirmationToken:c.string().optional().describe("Internal confirmation token returned by the confirmation flow")}).strict(),zc=c.object({operation:jf.describe("Exactly one generation operation."),confirmed:c.literal(!0).optional().describe("Confirm generation"),confirmationToken:c.string().optional().describe("Internal confirmation token returned by the confirmation flow")}).strict(),Df=c.object({oldText:c.string().min(1).describe("Exact text occurring once in the original stored Markdown. Include enough context to be unique."),newText:c.string().describe("Literal replacement text; empty string deletes oldText.")}).strict(),it="An update operation is exactly one of `fields`, `content`, `edits` or `source`.",Oi=c.strictObject({fields:c.record(c.string(),c.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:c.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:c.array(Df).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:Dc.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 ie(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(", ")}: ${it}`}}).refine((e)=>[e.fields,e.content,e.edits,e.source].filter((t)=>t!==void 0).length===1,{message:it}).describe(it),ir=c.object({entityType:c.string().describe("Entity type"),id:c.string().describe("Entity ID, slug, or title"),operation:Oi.describe("Exactly one update operation"),confirmed:c.literal(!0).optional().describe("Confirm the update"),confirmationToken:c.string().optional().describe("Internal confirmation token returned by the confirmation flow"),contentHash:c.string().optional().describe("Content hash for optimistic concurrency")}).strict(),Mc=c.object({entityType:c.string().describe("Entity type"),id:c.string().describe("Entity ID"),confirmed:c.literal(!0).optional().describe("Confirm the deletion"),confirmationToken:c.string().optional().describe("Internal confirmation token returned by the confirmation flow")}),OP=c.object({entityType:c.string().describe("Entity type to extract"),source:c.string().optional().describe("Source entity ID \u2014 omit for batch"),mode:c.enum(["derive","rebuild"]).optional().describe("Batch mode: project incrementally or rebuild from scratch"),confirmed:c.literal(!0).optional().describe("Confirm destructive rebuild"),confirmationToken:c.string().optional().describe("Internal confirmation token returned by the confirmation flow")}),Lc=c.object({batchId:c.string().optional().describe("Specific batch ID to check"),jobTypes:c.array(c.string()).optional().describe("Filter by job types")}),Of=c.object({entityType:c.string().optional(),entityId:c.string().optional(),attachmentType:c.string().optional()}),zf=c.object({mediaType:c.string(),url:c.string(),downloadUrl:c.string().optional(),previewUrl:c.string().optional(),filename:c.string().optional(),sizeBytes:c.number().optional(),source:Of.optional()}),zP=c.object({entityId:c.string().optional(),status:c.enum(["created","generating"]),jobId:c.string().optional(),attachment:zf.optional()}),MP=c.object({status:c.literal("extracting"),jobId:c.string(),entityType:c.string(),source:c.string().optional(),mode:c.enum(["derive","rebuild"]).optional()});function $c(e,t,r){return r==="create"?e.getCreateFieldsSchema(t):e.getEditableFieldsSchema(t)}function _c(e){if(e instanceof c.ZodOptional||e instanceof c.ZodNullable||e instanceof c.ZodDefault)return _c(e.unwrap());return e instanceof c.ZodType?e:void 0}function Uc(e){try{let{$schema:t,...r}=c.toJSONSchema(e,{target:"draft-7",io:"input"});return r}catch{return}}function Mf(e){return Bc({type:"object",properties:{value:e},required:["value"]})!==void 0}function Fc(e,t){let r=new Map,i=new Map,n=e.getAllEntityTypes().filter((d)=>!t.neverWrites?.(d,t.on));for(let d of n){let u=$c(e,d,t.on);for(let[p,m]of Object.entries(u?.shape??{})){if(t.omit?.includes(p))continue;let f=_c(m),g=f&&Uc(f);if(!f||!g||!Mf(g))continue;let h=r.get(p)??new Map;h.set(JSON.stringify(g),f),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 f=m.length>0?c.union([p,...m]):p,g=JSON.stringify(Uc(f)),h=o.get(g)??{value:f,names:[]};h.names.push(d),o.set(g,h)}let s=[...o.values()].map(({value:d,names:u})=>{let[p,...m]=u,f=u.map((g)=>{let h=i.get(g)??[];return`${g} (${h.length===n.length?"every type":h.join(", ")})`}).join("; ");return c.strictObject({name:(m.length>0&&p!==void 0?c.enum([p,...m]):c.literal(p??"")).describe(`The field, set only on the entity types named: ${f}.`),value:t.on==="update"?d.nullable():d})}),[a,...l]=s;return c.array(a?l.length>0?c.union([a,...l]):a:c.never())}function Lf(e){return Object.fromEntries((Array.isArray(e)?e:[]).flatMap((t)=>V(t)&&typeof t.name==="string"?[[t.name,t.value]]:[]))}function nr(e,t,r,i){if(!r)return;let{allow:n}=i,o=new Set(Object.keys($c(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(", "),l=[...o].join(", ")||"none";return`A ${t} has no ${s.length>1?"fields":"field"} ${a} a caller can set; its fields are ${l}.`}function Mi(e){return"fields"in e&&e.fields!==void 0?{...e,fields:Lf(e.fields)}:e}function Nc(e,t){return{prepare:()=>e.ensureGroupingsCurrent(),inputSchema:()=>{let r=Fc(e,{on:"create",omit:["visibility"],...t&&{neverWrites:t}}),i=nt.shape.items.element,n=nt.extend({items:c.array(i.extend({fields:r.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)}),[o,...s]=Di.options.map((a)=>a===nt?n:a);if(!o)throw Error("system_create has no source branches");return{...rr.shape,source:c.discriminatedUnion("kind",[o,...s]).describe("Concrete source selector. Use exactly one source branch. For AI generation or source-derived artifacts, use system_generate instead."),fields:r.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, and never fill in one the user did not state, such as a default section: leave it out, and the tool asks for it.")}},toToolInput:(r)=>{let i=r.source;return Mi({...r,...V(i)&&Array.isArray(i.items)&&{source:{...i,items:i.items.map((n)=>V(n)?Mi(n):n)}}})}}}function zi(e){let t=e.unwrap();return e.description?t.describe(e.description):t}function Zc(e,t){let{content:r,edits:i,source:n}=Oi.shape;return{prepare:()=>e.ensureGroupingsCurrent(),inputSchema:()=>({...ir.shape,operation:c.union([c.strictObject({fields:Fc(e,{on:"update",...t&&{neverWrites:t}}).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.")}),c.strictObject({content:zi(r)}),c.strictObject({edits:zi(i)}),c.strictObject({source:zi(n)})]).describe("Exactly one update operation")}),toToolInput:(o)=>{let s=o.operation;return V(s)?{...o,operation:Mi(s)}:o}}}function B(e,t,r,i){try{e.permissionService.assertEntityActionAllowed(t,r,i.userPermissionLevel);return}catch(n){if(n instanceof Error)return{success:!1,error:n.message};throw n}}function Me(e){return(t,r)=>e.getEntityActionRequiredLevel(t,r)==="never"}var Uf="system";function X(e){return{kind:"error",result:e}}function T(e,t){return X({success:!1,error:e,...t!==void 0&&{code:t}})}function W(e,t,r,i,n={}){let{visibility:o="admin",sideEffects:s}=n;return{name:`${Uf}_${e}`,description:t,inputSchema:r.shape,handler:async(a,l)=>{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,l)}catch(u){return{success:!1,error:P(u)}}},visibility:o,...s?{sideEffects:s}:{}}}function sr(e){return{interfaceType:e.interfaceType,actor:e.actor,userPermissionLevel:e.userPermissionLevel??"public",...e.channelId&&{channelId:e.channelId},...e.channelName&&{channelName:e.channelName}}}async function Hc(e,t,r,i){let n=await t(r,sr(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=B(e,o.entityType,"create",i);if(s)return{kind:"error",result:s};return{kind:"continue",createInput:o}}function Le(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 Ue(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 Li(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 ar(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var Bf={base:"note"};function Wc(e){return Bf[e]??e.replaceAll("-"," ")}function Be(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 qc(e){return!!e&&Object.keys(e.shape).length>0}async function Jc(e,t,r){if(!r)return!1;let i=await e.conversationService.getMessages(r,{limit:100});for(let n of i){let s=or(n.metadata)?.attachments;if(!Array.isArray(s))continue;for(let a of s){if(!ie(a))continue;let l=a.source;if(!ie(l))continue;if(l.kind===t.kind&&l.id===t.id)return!0}}return!1}async function cr(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"&&!B(e,t.entityType,"delete",r))return{kind:"ok",value:{entityType:i.entityType,id:i.id}};return T(`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 Gc(e){return`Replaces: failed ${e.entityType} "${e.id}"`}async function Qc(e,t){if(!t)return;try{await e.entityService.deleteEntity(t);return}catch(r){return{success:!1,error:P(r,"Failed to replace the failed entity")}}}function lr(e,t,r){let i=Le(e,t);if(i)return X(i);let n=B(e,t,"create",r);if(n)return X(n);return{kind:"ok",value:{interceptor:e.entityRegistry.getCreateInterceptor(t)}}}async function dr(e){let{gate:t,input:r,replacesFailed:i}=e;if(r.confirmed){let d=t.validateConfirmed(r.confirmationToken,r);if(d)return d;return e.run()}let{toolName:n,summary:o,completionSummary:s,preview:a,args:l}=e.confirmation();return{needsConfirmation:!0,toolName:n,summary:o,...s!==void 0&&{completionSummary:s},preview:i?`${a}
78
78
  ${Gc(i)}`:a,args:t.buildArgs((d)=>({...l,confirmed:!0,confirmationToken:d}))}}async function ot(e,t,r){let i=await Qc(e,r.replacesFailed);if(i)return i;if(!r.interceptor)return r.persist(r.createInput);let n=await Hc(e,r.interceptor,r.createInput,t);if(n.kind!=="continue")return n.result;return r.persist(n.createInput)}async function ur(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((b)=>{if(b.role!=="user")return!1;let y=r.userPermissionLevel??"public";if(y==="admin")return!0;let v=or(b.metadata)?.userPermissionLevel;return(v==="public"||v==="trusted"||v==="admin")&&e.permissionService.hasPermission(y,v)}):o.filter(Vc),l=t.messageId?a.find((b)=>b.id===t.messageId):a.at(-1);if(!l)return{success:!1,error:"Conversation message is not accessible in this conversation or does not exist."};if(!s)return{success:!0,messageId:l.id,content:l.content};let d=Nf(Ff(t,l.content),l.content),u=(b,y,v,R)=>{if(!y)return{offset:v};let I=`${b} ${JSON.stringify(y)}`;if(d.boundaryMode==="lines"&&/[\r\n]/.test(y))return{problem:`${I} contains a newline; in lines mode give the marker line's text only`};let E=$f(l.content,y,d.boundaryMode==="lines"?"lines":"literal",R),[z]=E;if(E.length===1&&z!==void 0)return{offset:z};return{problem:E.length===0?`${I} does not occur in the message`:`${I} occurs ${E.length} times in the message`}},p=u("startAfter",d.startAfter,0,!0),m=d.boundaryMode==="frontmatter"&&"offset"in p?Hf(l.content,p.offset):p,f=u("endBefore",d.endBefore,l.content.length,!1),g=[m,f].flatMap((b)=>("problem"in b)?[b.problem]:[]);if(g.length===0&&"offset"in m&&"offset"in f&&m.offset>=f.offset)g.push("startAfter must come before endBefore with content between them");if(!("offset"in m)||!("offset"in f)||g.length>0)return{success:!1,error:`User-message boundary ${g.join("; ")}; each boundary must occur exactly once. ${Zf(l.content)}`};let h=l.content.slice(m.offset,f.offset).replace(/^(?:[ \t]*\r?\n)+(?=---\r?\n)/,""),S=i?t.contentHash:void 0;if(S&&S!==G(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:l.id,content:h,source:d}}function pr(e,t){let{startAfter:r,endBefore:i,...n}=t.source??e;return{...n,...r?{startAfter:r}:{},...i?{endBefore:i}:{},messageId:t.messageId,contentHash:G(t.content)}}function $f(e,t,r,i){if(r==="lines"){let o=Ui(e,t,i);return o.length>0||!t.trim()?o:Ui(e,t,i,_f)}let n=Yc(e,t,i);return n.length>0?n:Wf(e,t,i)}function _f(e){return e.trim().replace(/\s+/g," ")}function Ff(e,t){let r=(a)=>a?.trim()==="---";if(!r(e.startAfter)&&!r(e.endBefore))return e;if((t.match(/^---\r?$/gm)?.length??0)!==2||Bi(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 Nf(e,t){let{startAfter:r,endBefore:i}=e;if(e.boundaryMode!==void 0||!r||!i)return e;let n=(o)=>!/[\r\n]/.test(o)&&Ui(t,o,!0).length===1;return n(r)&&n(i)?{...e,boundaryMode:"lines"}:e}function Zf(e){return Bi(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 Hf(e,t){let r=Bi(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 Bi(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 Ui(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 Wf(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(Kc).join("\\s+")+n(/\s$/.test(t)),"g");return Array.from(e.matchAll(o),(s)=>s.index+(r?s[0].length:0))}function Yc(e,t,r,i=0){let n=e.indexOf(t,i);if(n<0)return[];return[n+(r?t.length:0),...Yc(e,t,r,n+1)]}var qf=/^[ \t]*---[ \t]*$/gm;function Xc(e){return e.replace(/\s+/g," ").trim()}function Jf(e){return e.kind==="user-message"?e.messageId:void 0}class $i{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=Jf(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&&Xc(t.content.replace(qf,""))===Xc(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 _i(e,t){return e?`${e}\x00${t}`:void 0}function el(e){if(e.kind!=="user-message")return e;let{contentHash:t,...r}=e;return r}function Fi(e){return`${e.entityType} "${e.title}"`}function Gf(e){return Object.entries(e).map(([t,r])=>`${t}: ${typeof r==="string"?r:JSON.stringify(r)}`).join(", ")}function tl(e){return"error"in e?e.error:"the save was not completed"}function Qf(e){let t=new Map;for(let r of e){let i=`${r.entityType}:${ee(r.title)}`,n=t.get(i);if(n)return`${n.filename} and ${r.filename} would both be saved as ${Fi(r)}. Give them different titles in source.items.`;t.set(i,r)}return}function Kf(e,t){return{summary:`Save ${e.length} uploaded files?`,completionSummary:`Saved ${e.length} uploaded files: ${e.map(Fi).join(", ")}.`,preview:[...e.map((r,i)=>[`${i+1}. ${r.filename} \u2192 ${Fi(r)}`,...r.fields?[` ${Gf(r.fields)}`]:[],...r.replacesFailed?[` Replaces failed ${r.replacesFailed}`]:[]].join(`
79
79
  `)),`Visibility: ${t??"public"}`].join(`
80
80
  `)}}async function Vf(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,...V(n.data)?n.data:{}});else r.push(`${i.filename}: ${tl(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 rl(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,l]of t.source.items.entries()){let d=await e.prepare(l);if(d.kind==="error")return{success:!1,error:`Upload ${a+1} of ${t.source.items.length} (${l.id}): ${tl(d.result)}`};i.push(d.value)}let n=Qf(i);if(n)return{success:!1,error:n};if(t.confirmed){let a=r.validateConfirmed(t.confirmationToken,t);if(a)return a;return Vf(i)}let o=Kf(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((l,d)=>({id:l.id,transform:l.transform,title:i[d]?.title??l.title,...(i[d]?.fields??l.fields)&&{fields:i[d]?.fields??l.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 Yf(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(`
81
81
  `)}}function Xf(e){let{entityType:t,title:r,visibility:i,content:n,url:o,from:s,fields:a}=e,d=`Create${r?` "${r}"`:` ${t}`}?`,u=[`Entity type: ${t}`,`Visibility: ${i??"public"}`,...r?[`Title: ${r}`]:[],...o?[`URL: ${o}`]:[],...s?.kind==="upload"?["Upload: uploaded file"]:[],...Object.entries(a??{}).map(([p,m])=>`${p}: ${typeof m==="string"?m:JSON.stringify(m)}`),...n?[`Content preview: ${n.slice(0,500)}`]:[]];return{summary:d,preview:u.join(`
82
- `)}}function eg(e){let t=e.title?` "${e.title}"`:"";return`Saved ${e.entityType}${t}.`}function tg(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 rg(e,t,r){let i=await _(e.entityService,{entityType:t.entityType,identifier:t.entityId},{visibilityScope:A(r.userPermissionLevel),logger:e.logger,label:"Source entity"});if(!i.ok)return T(i.error);let{entity:n}=i,o=$e(n.content,{trim:!0,keepEmptyBlock:!0});if(!o)return T(`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 ig(e,{source:t,retry:r},i){if(r.kind==="pinned")return r.source;if(e.kind==="user-message"){if(!t.resolvedMessageId||i===void 0)throw Error("User-message source was not resolved before confirmation");return pr(e,{messageId:t.resolvedMessageId,content:i,...t.resolvedUserSource&&{source:t.resolvedUserSource}})}if(e.kind==="prior-response"){let n=e.messageId??t.resolvedMessageId;return{kind:"prior-response",...n?{messageId:n}:{}}}if(e.kind==="entity"&&t.entitySource)return{kind:"entity",...t.entitySource.ref};return e}async function ng(e,t){let r=sr(t);return e.handler({upload:e.upload,...e.title&&{title:e.title},...e.visibility!==void 0?{visibility:e.visibility}:{}},r)}function og(e,t,r){let i=Se(t),n=i.content.match(/^#\s+(.+)$/m)?.[1]?.trim(),o=e.fields?.title!==void 0||i.frontmatter.title!==void 0||n!==void 0&&n===e.title?.trim(),s=r&&!o?e.title:void 0,a={...s!==void 0&&{title:s},...e.fields};return Object.keys(a).length>0?mr(a,t):t}async function sg(e,t,r){let{entityService:i,entityRegistry:n}=e,o=ee(t.title??`${t.entityType}-${Date.now()}`),s=n.getEffectiveFrontmatterSchema(t.entityType),a=t.content!==void 0&&qc(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 l={deduplicateId:!0,...r?{eventContext:r}:{}};return{success:!0,data:{entityId:(t.content&&a?await i.createEntityFromMarkdown({input:{entityType:t.entityType,id:o,markdown:og(t,t.content,"title"in(s?.shape??{})),...t.visibility!==void 0?{visibility:t.visibility}:{}},options:l}):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:l})).entityId,status:"created"}}}catch(l){return{success:!1,error:P(l,"Failed to create entity")}}}async function ag(e,t,r){let{content:i,url:n,from:o,uploadRef:s,conversationMessageRef:a,entityRef:l,transform:d}=tg(t.source),u=l?await rg(e,l,r):void 0;if(u?.kind==="error")return u;let p=a?await ur(e,a,r,{confirmed:t.confirmed===!0}):void 0;if(p&&!p.success)return X(p);let m=p?.success===!0?p.content:u?.value.content??i;if(d==="extract-markdown"&&!s)return T('Transform "extract-markdown" requires an upload ref.');if(!m&&!n&&!o)return T('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 cg(e,t){if(!Ni(t.mediaType))return;let{content:r}=await e.runtimeUploads.scoped(je).read(t.id);return Cc(r).toString("utf8")}async function lg(e,t,r){if(!await Jc(e,t.uploadRef,r.conversationId??r.channelId))return T("Upload ref is not accessible in this conversation or no longer exists.");let n,o;try{n=await e.runtimeUploads.scoped(je).readRecord(t.uploadRef.id),o=t.transform==="extract-markdown"?await cg(e,{id:t.uploadRef.id,mediaType:n.mediaType}):void 0}catch{return T("Upload ref not found")}let s=nl({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 l=Ni(n.mediaType)?' Keep a text upload as a note: entityType "note" with transform "extract-markdown".':"";return T(`No installed plugin can save uploads with media type "${n.mediaType}".${l}`)}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 dg(e,t,r){let i=t?gr(t):void 0;if(e!==void 0&&i!==void 0&&e!==i)return T(`Conflicting entity visibility: system_create requested "${e}" but the source frontmatter declares "${i}".`);let n=e??i,o=n??"public";if(!fr(r.userPermissionLevel,o))return T(`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 ug(e,t,r){return cr(e,{entityType:t.entityType,candidateId:t.title?ee(t.title):void 0,replace:t.replace===!0,copyHint:"create a new copy intentionally"},r)}function pg(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 T(`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 mg(e,t,r){let i=e.entityRegistry.getCreateCheck(t.entityType);if(!i)return{kind:"ready"};try{return await i(t,sr(r))}catch(n){return{kind:"error",error:P(n,`Could not check the ${t.entityType}`)}}}function fg(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(el(t))}.`,e.answerWith].join(" ")}function gg(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}}}var ol='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.';async function hg(e,t,r,i,n){let o=await ag(e,t,r);if(o.kind==="error"){let a=n?i.resolveUnresolvable(n,t.source):void 0;if(!a)return o;return{kind:"ok",value:{source:{content:a.content,url:void 0,from:void 0,uploadRef:void 0,transform:void 0,resolvedMessageId:void 0,resolvedUserSource:void 0,entitySource:void 0},retry:a}}}let s=n?i.resolve(n,{source:t.source,content:o.value.content,resolvedMessageId:o.value.resolvedMessageId}):{kind:"as-given"};return{kind:"ok",value:{source:o.value,retry:s}}}async function yg(e,t,{source:r,retry:i},n){let o=r.uploadRef?await lg(e,{entityType:t.entityType,uploadRef:r.uploadRef,transform:r.transform},n):void 0;if(o?.kind==="error")return o;let s=o?.value.entityType??t.entityType,a=pg(e,s,r,o?.value);if(a.kind==="error")return a;return{kind:"ok",value:{entityType:s,content:i.kind==="pinned"?i.content:a.value.content,from:a.value.from,transform:a.value.transform,upload:o?.value}}}function vg(e,{url:t,entitySource:r},{entityType:i,content:n,from:o,transform:s,upload:a},l){let d=r&&r.visibility!=="public"?r.visibility:void 0,u=dg(e.visibility??d,n,l);if(u.kind==="error")return u;if(e.fields&&"visibility"in e.fields)return T("Set visibility with the typed `visibility` input, not in `fields`.");let p=e.fields&&Object.keys(e.fields).length>0?e.fields:void 0,m=ar(e.title),f=(a&&il(m,a.filename)?void 0:m)??r?.title??a?.title,g=e.replace===!0;return{kind:"ok",value:{entityType:i,...f&&{title:f},...u.value!==void 0?{visibility:u.value}:{},...n&&{content:n},...t&&{url:t},...o&&{from:o},...s&&{transform:s},...p&&{fields:p},...g&&{replace:g}}}}async function bg(e,t,r,i){let n=await mg(e,t,r);if(n.kind==="error")return T(n.error);if(n.kind==="question"){if(i.pendingKey&&i.pinnable!==void 0)i.pending.pin(i.pendingKey,{source:i.source,content:i.pinnable,question:n.asks});return T(fg(n,i.source,i.several))}return{kind:"ok",value:gg(t,n)}}async function sl(e,t,r,i,n){if(!(t.source.kind==="upload"&&t.source.transform==="preserve")){let I=Le(e,t.entityType);if(I)return X(I)}let s=_i(r.conversationId??r.channelId,t.entityType),a=await hg(e,t,r,i,s);if(a.kind==="error")return a;let{source:l}=a.value,d=await yg(e,t,a.value,r);if(d.kind==="error")return d;let{content:u,upload:p}=d.value,m=p?.uploadPreserve,f=vg(t,l,d.value,r);if(f.kind==="error")return f;let g=f.value,h=lr(e,g.entityType,r);if(h.kind==="error")return h;let{interceptor:S}=h.value;if(!g.content&&!S&&!m)return T(ol);let b=ig(t.source,a.value,u),y=t.confirmed||m?{kind:"ok",value:g}:await bg(e,g,r,{source:b,several:n,pinnable:l.uploadRef?void 0:u,pending:i,pendingKey:s});if(y.kind==="error")return y;let v=y.value,R=await ug(e,v,r);if(R.kind==="error")return R;return{kind:"ok",value:{createInput:v,confirmationSource:b,interceptor:S,eventContext:Ue(r),...p&&{uploadFilename:p.filename},...l.uploadRef&&{uploadId:l.uploadRef.id},...R.value&&{replacesFailed:R.value},...m&&{uploadPreserve:m}}}}async function al(e,t,r,i){let n=await Sg(e,t,r,i),{uploadId:o}=t;if(o===void 0||!("success"in n)||!n.success)return n;if(!V(n.data))return n;return{...n,data:{entityType:t.createInput.entityType,...n.data,uploadId:o}}}async function Sg(e,t,r,i){let{createInput:n,eventContext:o,uploadPreserve:s,replacesFailed:a}=t;if(s)return ot(e,r,{createInput:n,interceptor:void 0,replacesFailed:a,persist:()=>ng({upload:s.upload,...n.title&&{title:n.title},...n.visibility!==void 0?{visibility:n.visibility}:{},handler:s.handler},r)});let l=await ot(e,r,{createInput:n,interceptor:t.interceptor,replacesFailed:a,persist:async(u)=>u.content?sg(e,u,o):{success:!1,error:ol}}),d=_i(r.conversationId??r.channelId,n.entityType);if(d&&"success"in l&&l.success)i.clear(d);return l}async function Rg(e,t,r,i,n){let o={...t.fields,...r.fields},s=await sl(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 a=s.value;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:()=>al(e,a,i,n)}}}function wg(e){let{createInput:t,uploadPreserve:r}=e,{summary:i,preview:n}=r?Yf({...t.title&&{title:t.title},filename:r.filename,mediaType:r.mediaType,entityType:t.entityType,visibility:t.visibility}):Xf(t);return{toolName:"system_create",summary:i,completionSummary:eg(t),preview:n,args:{entityType:t.entityType,...t.title&&{title:t.title},...t.visibility!==void 0?{visibility:t.visibility}:{},source:e.confirmationSource,...t.fields&&{fields:t.fields},...t.replace&&{replace:t.replace}}}}function cl(e){let t=Y({label:"create",requestNoun:"creation"}),r=new $i;return{...W("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.",rr,async(n,o)=>{await e.entityRegistry.ensureGroupingsCurrent(n.entityType);let s=[n.fields,...n.source.kind==="uploads"?n.source.items.map((d)=>d.fields):[]].map((d)=>nr(e.entityRegistry,n.entityType,d,{on:"create",allow:["visibility"]})).find((d)=>d!==void 0);if(s)return{success:!1,error:s};if(n.source.kind==="uploads")return rl({input:{...n,source:n.source},gate:t,prepare:(d)=>Rg(e,n,d,o,r)});let a=await sl(e,n,o,r);if(a.kind==="error")return a.result;let l=a.value;return dr({gate:t,input:n,replacesFailed:l.replacesFailed,confirmation:()=>wg(l),run:()=>al(e,l,o,r)})},{visibility:"trusted",sideEffects:"writes"}),modelInput:Nc(e.entityRegistry,Me(e.permissionService))}}function Ig(e){let t=e.map((r)=>`"${r}"`);return t.length<=1?t.join(""):`${t.slice(0,-1).join(", ")} and ${t.at(-1)??""}`}function Zi(e){return Ig(e.entries.map(({label:t})=>t))}function xg(e,t,r){let i=e.title?` "${e.title}"`:` ${e.entityType}`,n=e.from?.kind==="entity-attachment"?e.from:void 0,o=t?.usedUp?t:void 0,s=[`Entity type: ${e.entityType}`,...e.title?[`Title: ${e.title}`]:[],...r?[`Prompt: ${r}`]:[],...o?.entries.map(({entityId:a})=>`Removes: ${o.entityType}/${a}`)??[],...n?[`Source attachment: ${n.sourceEntityType}/${n.sourceEntityId} (${n.attachmentType})`]:[],...e.targetEntityType&&e.targetEntityId?[`Target: ${e.targetEntityType}/${e.targetEntityId}`]:[]];return{summary:o?`Generate${i} from ${Zi(o)}? ${o.entries.length===1?"It":"They"} will be removed.`:`Generate${i}?`,...o&&{completionSummary:`Generating${i} from ${Zi(o)}, which will be removed once it is saved.`},preview:s.join(`
82
+ `)}}function eg(e){let t=e.title?` "${e.title}"`:"";return`Saved ${e.entityType}${t}.`}function tg(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 rg(e,t,r){let i=await _(e.entityService,{entityType:t.entityType,identifier:t.entityId},{visibilityScope:A(r.userPermissionLevel),logger:e.logger,label:"Source entity"});if(!i.ok)return T(i.error);let{entity:n}=i,o=$e(n.content,{trim:!0,keepEmptyBlock:!0});if(!o)return T(`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 ig(e,{source:t,retry:r},i){if(r.kind==="pinned")return r.source;if(e.kind==="user-message"){if(!t.resolvedMessageId||i===void 0)throw Error("User-message source was not resolved before confirmation");return pr(e,{messageId:t.resolvedMessageId,content:i,...t.resolvedUserSource&&{source:t.resolvedUserSource}})}if(e.kind==="prior-response"){let n=e.messageId??t.resolvedMessageId;return{kind:"prior-response",...n?{messageId:n}:{}}}if(e.kind==="entity"&&t.entitySource)return{kind:"entity",...t.entitySource.ref};return e}async function ng(e,t){let r=sr(t);return e.handler({upload:e.upload,...e.title&&{title:e.title},...e.visibility!==void 0?{visibility:e.visibility}:{}},r)}function og(e,t,r){let i=Re(t),n=i.content.match(/^#\s+(.+)$/m)?.[1]?.trim(),o=e.fields?.title!==void 0||i.frontmatter.title!==void 0||n!==void 0&&n===e.title?.trim(),s=r&&!o?e.title:void 0,a={...s!==void 0&&{title:s},...e.fields};return Object.keys(a).length>0?mr(a,t):t}async function sg(e,t,r){let{entityService:i,entityRegistry:n}=e,o=ee(t.title??`${t.entityType}-${Date.now()}`),s=n.getEffectiveFrontmatterSchema(t.entityType),a=t.content!==void 0&&qc(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 l={deduplicateId:!0,...r?{eventContext:r}:{}};return{success:!0,data:{entityId:(t.content&&a?await i.createEntityFromMarkdown({input:{entityType:t.entityType,id:o,markdown:og(t,t.content,"title"in(s?.shape??{})),...t.visibility!==void 0?{visibility:t.visibility}:{}},options:l}):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:l})).entityId,status:"created"}}}catch(l){return{success:!1,error:P(l,"Failed to create entity")}}}async function ag(e,t,r){let{content:i,url:n,from:o,uploadRef:s,conversationMessageRef:a,entityRef:l,transform:d}=tg(t.source),u=l?await rg(e,l,r):void 0;if(u?.kind==="error")return u;let p=a?await ur(e,a,r,{confirmed:t.confirmed===!0}):void 0;if(p&&!p.success)return X(p);let m=p?.success===!0?p.content:u?.value.content??i;if(d==="extract-markdown"&&!s)return T('Transform "extract-markdown" requires an upload ref.');if(!m&&!n&&!o)return T('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 cg(e,t){if(!Ni(t.mediaType))return;let{content:r}=await e.runtimeUploads.scoped(je).read(t.id);return Cc(r).toString("utf8")}async function lg(e,t,r){if(!await Jc(e,t.uploadRef,r.conversationId??r.channelId))return T("Upload ref is not accessible in this conversation or no longer exists.");let n,o;try{n=await e.runtimeUploads.scoped(je).readRecord(t.uploadRef.id),o=t.transform==="extract-markdown"?await cg(e,{id:t.uploadRef.id,mediaType:n.mediaType}):void 0}catch{return T("Upload ref not found")}let s=nl({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 l=Ni(n.mediaType)?' Keep a text upload as a note: entityType "note" with transform "extract-markdown".':"";return T(`No installed plugin can save uploads with media type "${n.mediaType}".${l}`)}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 dg(e,t,r){let i=t?gr(t):void 0;if(e!==void 0&&i!==void 0&&e!==i)return T(`Conflicting entity visibility: system_create requested "${e}" but the source frontmatter declares "${i}".`);let n=e??i,o=n??"public";if(!fr(r.userPermissionLevel,o))return T(`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 ug(e,t,r){return cr(e,{entityType:t.entityType,candidateId:t.title?ee(t.title):void 0,replace:t.replace===!0,copyHint:"create a new copy intentionally"},r)}function pg(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 T(`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 mg(e,t,r){let i=e.entityRegistry.getCreateCheck(t.entityType);if(!i)return{kind:"ready"};try{return await i(t,sr(r))}catch(n){return{kind:"error",error:P(n,`Could not check the ${t.entityType}`)}}}function fg(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(el(t))}.`,e.answerWith].join(" ")}function gg(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}}}var ol='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.';async function hg(e,t,r,i,n){let o=await ag(e,t,r);if(o.kind==="error"){let a=n?i.resolveUnresolvable(n,t.source):void 0;if(!a)return o;return{kind:"ok",value:{source:{content:a.content,url:void 0,from:void 0,uploadRef:void 0,transform:void 0,resolvedMessageId:void 0,resolvedUserSource:void 0,entitySource:void 0},retry:a}}}let s=n?i.resolve(n,{source:t.source,content:o.value.content,resolvedMessageId:o.value.resolvedMessageId}):{kind:"as-given"};return{kind:"ok",value:{source:o.value,retry:s}}}async function yg(e,t,{source:r,retry:i},n){let o=r.uploadRef?await lg(e,{entityType:t.entityType,uploadRef:r.uploadRef,transform:r.transform},n):void 0;if(o?.kind==="error")return o;let s=o?.value.entityType??t.entityType,a=pg(e,s,r,o?.value);if(a.kind==="error")return a;return{kind:"ok",value:{entityType:s,content:i.kind==="pinned"?i.content:a.value.content,from:a.value.from,transform:a.value.transform,upload:o?.value}}}function vg(e,{url:t,entitySource:r},{entityType:i,content:n,from:o,transform:s,upload:a},l){let d=r&&r.visibility!=="public"?r.visibility:void 0,u=dg(e.visibility??d,n,l);if(u.kind==="error")return u;if(e.fields&&"visibility"in e.fields)return T("Set visibility with the typed `visibility` input, not in `fields`.");let p=e.fields&&Object.keys(e.fields).length>0?e.fields:void 0,m=ar(e.title),f=(a&&il(m,a.filename)?void 0:m)??r?.title??a?.title,g=e.replace===!0;return{kind:"ok",value:{entityType:i,...f&&{title:f},...u.value!==void 0?{visibility:u.value}:{},...n&&{content:n},...t&&{url:t},...o&&{from:o},...s&&{transform:s},...p&&{fields:p},...g&&{replace:g}}}}async function bg(e,t,r,i){let n=await mg(e,t,r);if(n.kind==="error")return T(n.error);if(n.kind==="question"){if(i.pendingKey&&i.pinnable!==void 0)i.pending.pin(i.pendingKey,{source:i.source,content:i.pinnable,question:n.asks});return T(fg(n,i.source,i.several))}return{kind:"ok",value:gg(t,n)}}async function sl(e,t,r,i,n){if(!(t.source.kind==="upload"&&t.source.transform==="preserve")){let I=Le(e,t.entityType);if(I)return X(I)}let s=_i(r.conversationId??r.channelId,t.entityType),a=await hg(e,t,r,i,s);if(a.kind==="error")return a;let{source:l}=a.value,d=await yg(e,t,a.value,r);if(d.kind==="error")return d;let{content:u,upload:p}=d.value,m=p?.uploadPreserve,f=vg(t,l,d.value,r);if(f.kind==="error")return f;let g=f.value,h=lr(e,g.entityType,r);if(h.kind==="error")return h;let{interceptor:S}=h.value;if(!g.content&&!S&&!m)return T(ol);let b=ig(t.source,a.value,u),y=t.confirmed||m?{kind:"ok",value:g}:await bg(e,g,r,{source:b,several:n,pinnable:l.uploadRef?void 0:u,pending:i,pendingKey:s});if(y.kind==="error")return y;let v=y.value,R=await ug(e,v,r);if(R.kind==="error")return R;return{kind:"ok",value:{createInput:v,confirmationSource:b,interceptor:S,eventContext:Ue(r),...p&&{uploadFilename:p.filename},...l.uploadRef&&{uploadId:l.uploadRef.id},...R.value&&{replacesFailed:R.value},...m&&{uploadPreserve:m}}}}async function al(e,t,r,i){let n=await Sg(e,t,r,i),{uploadId:o}=t;if(o===void 0||!("success"in n)||!n.success)return n;if(!V(n.data))return n;return{...n,data:{entityType:t.createInput.entityType,...n.data,uploadId:o}}}async function Sg(e,t,r,i){let{createInput:n,eventContext:o,uploadPreserve:s,replacesFailed:a}=t;if(s)return ot(e,r,{createInput:n,interceptor:void 0,replacesFailed:a,persist:()=>ng({upload:s.upload,...n.title&&{title:n.title},...n.visibility!==void 0?{visibility:n.visibility}:{},handler:s.handler},r)});let l=await ot(e,r,{createInput:n,interceptor:t.interceptor,replacesFailed:a,persist:async(u)=>u.content?sg(e,u,o):{success:!1,error:ol}}),d=_i(r.conversationId??r.channelId,n.entityType);if(d&&"success"in l&&l.success)i.clear(d);return l}async function Rg(e,t,r,i,n){let o={...t.fields,...r.fields},s=await sl(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 a=s.value;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:()=>al(e,a,i,n)}}}function wg(e){let{createInput:t,uploadPreserve:r}=e,{summary:i,preview:n}=r?Yf({...t.title&&{title:t.title},filename:r.filename,mediaType:r.mediaType,entityType:t.entityType,visibility:t.visibility}):Xf(t);return{toolName:"system_create",summary:i,completionSummary:eg(t),preview:n,args:{entityType:t.entityType,...t.title&&{title:t.title},...t.visibility!==void 0?{visibility:t.visibility}:{},source:e.confirmationSource,...t.fields&&{fields:t.fields},...t.replace&&{replace:t.replace}}}}function cl(e){let t=Y({label:"create",requestNoun:"creation"}),r=new $i;return{...W("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.",rr,async(n,o)=>{await e.entityRegistry.ensureGroupingsCurrent(n.entityType);let s=[n.fields,...n.source.kind==="uploads"?n.source.items.map((d)=>d.fields):[]].map((d)=>nr(e.entityRegistry,n.entityType,d,{on:"create",allow:["visibility"]})).find((d)=>d!==void 0);if(s)return{success:!1,error:s};if(n.source.kind==="uploads")return rl({input:{...n,source:n.source},gate:t,prepare:(d)=>Rg(e,n,d,o,r)});let a=await sl(e,n,o,r);if(a.kind==="error")return a.result;let l=a.value;return dr({gate:t,input:n,replacesFailed:l.replacesFailed,confirmation:()=>wg(l),run:()=>al(e,l,o,r)})},{visibility:"trusted",sideEffects:"writes"}),modelInput:Nc(e.entityRegistry,Me(e.permissionService))}}function Ig(e){let t=e.map((r)=>`"${r}"`);return t.length<=1?t.join(""):`${t.slice(0,-1).join(", ")} and ${t.at(-1)??""}`}function Zi(e){return Ig(e.entries.map(({label:t})=>t))}function xg(e,t,r){let i=e.title?` "${e.title}"`:` ${e.entityType}`,n=e.from?.kind==="entity-attachment"?e.from:void 0,o=t?.usedUp?t:void 0,s=[`Entity type: ${e.entityType}`,...e.title?[`Title: ${e.title}`]:[],...r?[`Prompt: ${r}`]:[],...o?.entries.map(({entityId:a})=>`Removes: ${o.entityType}/${a}`)??[],...n?[`Source attachment: ${n.sourceEntityType}/${n.sourceEntityId} (${n.attachmentType})`]:[],...e.targetEntityType&&e.targetEntityId?[`Target: ${e.targetEntityType}/${e.targetEntityId}`]:[]];return{summary:o?`Generate${i} from ${Zi(o)}? ${o.entries.length===1?"It":"They"} will be removed.`:`Generate${i}?`,...o&&{completionSummary:`Generating${i} from ${Zi(o)}, which will be removed once it is saved.`},preview:s.join(`
83
83
  `)}}async function Pg(e,t,r,i){let n=await Promise.all(r.map((a)=>_(e.entityService,{entityType:t,identifier:a},{visibilityScope:i,logger:e.logger}))),o=n.find((a)=>!a.ok);if(o)return T(o.error,"source-not-found");let s=n.flatMap((a)=>a.ok?[{entityId:a.entity.id,label:Be(a.entity)}]:[]);return{kind:"ok",value:s.filter(({entityId:a},l)=>s.findIndex((d)=>d.entityId===a)===l)}}function dl(e,t){return e.entityRegistry.getEntityTypeConfig(t).consumesSources??[]}function Cg(e,t,r){if(t.kind!=="prompt"&&t.kind!=="prompt-from-source")return;let i=dl(e,t.entityType);if(i.length===0)return;let n=`A ${t.entityType} is written from ${i.join(" or ")} entries`;if(t.kind==="prompt")return{success:!1,error:`${n}. Use operation.kind prompt-from-source and name the source.`,code:"unsupported-generation"};if(!i.includes(t.source.entityType))return{success:!1,error:`${n}, and '${t.source.entityType}' is not one of them.`,code:"unsupported-generation"};return B(e,t.source.entityType,"delete",r)}async function ul(e,t,r,i){let n=await _(e.entityService,{entityType:t.entityType,identifier:t.entityId},{visibilityScope:r,logger:e.logger});if(!n.ok)return T(n.error,i);return{kind:"ok",value:{...t,entityId:n.entity.id}}}async function Tg(e,t,r,i){let n=await ul(e,t,i,"source-not-found");if(n.kind==="error")return n;let o={sourceEntityType:t.entityType,sourceEntityId:n.value.entityId,attachmentType:r};if(!e.attachments.hasProvider(t.entityType,r))return T(`No attachment provider found for ${t.entityType}/${r}.`,"no-provider");let s=e.attachments.getProviderMetadata(t.entityType,r);if(!s)return T(`Attachment provider for ${t.entityType}/${r} is missing output metadata.`,"provider-missing-metadata");return{kind:"ok",value:{sourceAttachment:o,metadata:s}}}async function Eg(e,t,r,i,n,o){let{entityService:s,jobs:a}=e,l=Hi(ee(pl(t,i,r)),100);if(!l)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 d=t.title??l,u=ll(e.entityRegistry,{entityType:t.entityType,id:l,title:d});if(!u)return{success:!1,error:`Entity type '${t.entityType}' does not support queued generation. Provide an exact source to system_create instead.`};let p;try{p=(await s.createEntity({entity:u,options:{deduplicateId:!0,...n?{eventContext:n}:{}}})).entityId}catch(g){return{success:!1,error:P(g,"Failed to persist generation stub")}}let m={entityId:p,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}},f=e.entityRegistry.getGenerationEnqueuer(t.entityType);try{let g=f?await f(m,o):await a.enqueue({type:`${t.entityType}:generation`,data:m,toolContext:o});return{success:!0,data:{entityId:p,status:"generating",jobId:g}}}catch(g){return await s.deleteEntity({entityType:t.entityType,id:p}).catch((h)=>{e.logger.warn("Failed to remove unqueued generation stub",{entityType:t.entityType,entityId:p,error:h})}),{success:!1,error:P(g,"Failed to queue generation job")}}}function pl(e,t,r){return e.title??t??r}async function Ag(e,t,r){let i=ar(t.title);if(t.kind==="prompt"||t.kind==="prompt-from-source"){if(e.entityRegistry.getEntityTypeConfig(t.entityType).binaryStorage)return T(`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.`,"unsupported-generation");let l=t.kind==="prompt-from-source"?await Pg(e,t.source.entityType,[t.source.entityId,...t.additionalSourceIds??[]],r):void 0;if(l?.kind==="error")return l;let d=t.kind==="prompt-from-source"&&l?{entityType:t.source.entityType,entries:l.value,usedUp:dl(e,t.entityType).includes(t.source.entityType)}:void 0,[u]=d?.entries??[];return{kind:"ok",value:{createInput:{entityType:t.entityType,...i?{title:i}:{},prompt:t.prompt??`Write a ${t.entityType} from ${d?Zi(d):""}.`,...d&&u&&{sourceEntityType:d.entityType,sourceEntityId:u.entityId,sourceEntityIds:d.entries.map(({entityId:p})=>p)}},sourceAttachment:void 0,writtenFrom:d}}}if(t.kind==="standalone-image")return{kind:"ok",value:{createInput:{entityType:"image",...i?{title:i}:{},prompt:t.prompt},sourceAttachment:void 0,writtenFrom:void 0}};if(t.kind==="cover-image"){let l=await ul(e,t.target,r,"target-not-found");if(l.kind==="error")return l;return{kind:"ok",value:{createInput:{entityType:"image",...i?{title:i}:{},prompt:t.prompt,targetEntityType:l.value.entityType,targetEntityId:l.value.entityId},sourceAttachment:void 0,writtenFrom:void 0}}}let n=await Tg(e,t.source,t.attachmentType,r);if(n.kind==="error")return n;let{sourceAttachment:o,metadata:s}=n.value,a=t.replace===!0;return{kind:"ok",value:{createInput:{entityType:s.outputEntityType,...i?{title:i}:{},from:{kind:"entity-attachment",...o},...a&&{replace:a},...s.targetField&&{targetEntityType:o.sourceEntityType,targetEntityId:o.sourceEntityId}},sourceAttachment:o,writtenFrom:void 0}}}async function kg(e,t,r){let i=t.operation,n=A(r.userPermissionLevel),o=Cg(e,i,r);if(o)return X(o);let s=await Ag(e,i,n);if(s.kind==="error")return s;let{createInput:a,sourceAttachment:l,writtenFrom:d}=s.value,p="prompt"in i&&i.prompt!==void 0&&!d?.usedUp?void 0:d?.entries[0]?.entityId,m=lr(e,a.entityType,r);if(m.kind==="error")return m;let{interceptor:f}=m.value;if(!a.prompt&&!a.from)return T("Provide a generation source.");if(a.from&&!f)return T(`Entity type '${a.entityType}' does not support attachment-based generation. Use operation.kind prompt-from-source for AI-generated content based on referenced source material, or choose an entity type with an attachment provider.`,"unsupported-generation");let g=i.kind==="prompt"||i.kind==="prompt-from-source",h=f&&!g?void 0:await cr(e,{entityType:a.entityType,candidateId:a.prompt?Hi(ee(pl(a,p,a.prompt)),100):a.title?ee(a.title):void 0,replace:a.replace===!0,copyHint:"generate a new copy intentionally"},r);if(h?.kind==="error")return h;return{kind:"ok",value:{createInput:a,operation:jg(i,a,l),interceptor:f,eventContext:Ue(r),...h?.value&&{replacesFailed:h.value},writtenFrom:d,sourceName:p}}}function jg(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},...(t.sourceEntityIds?.length??0)>1&&{additionalSourceIds:t.sourceEntityIds?.slice(1)},...e.prompt!==void 0&&{prompt:e.prompt}};return{kind:"prompt",entityType:t.entityType,...t.title&&{title:t.title},prompt:e.prompt}}function ml(e){let t=Y({label:"generate",requestNoun:"generation"});return W("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. Turning an uploaded file into a note is extraction too: system_create on the upload with transform extract-markdown, never generation, however little text it holds. 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.",zc,async(r,i)=>{let n=await kg(e,r,i);if(n.kind==="error")return n.result;let{createInput:o,operation:s,interceptor:a,eventContext:l,replacesFailed:d,writtenFrom:u,sourceName:p}=n.value;return dr({gate:t,input:r,replacesFailed:d,confirmation:()=>({toolName:"system_generate",...xg(o,u,"prompt"in s?s.prompt:void 0),args:{operation:s}}),run:()=>ot(e,i,{createInput:o,interceptor:a,replacesFailed:d,persist:async(m)=>{if(!m.prompt)return{success:!1,error:"Attachment generation is supported only for entity types that explicitly handle source-derived artifacts."};return Eg(e,m,m.prompt,p,l,i)}})})},{visibility:"trusted",sideEffects:"writes"})}function fl(e){let{entityService:t,entityRegistry:r,logger:i}=e,n=Y({label:"delete",requestNoun:"deletion"});return W("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.",Mc,async(o,s)=>{if((s.userPermissionLevel??"public")==="public")return{success:!1,error:"Changing content requires higher permission; current permission is Public."};let a=B(e,o.entityType,"delete",s);if(a)return a;let l=Le(e,o.entityType);if(l)return l;if(r.getAdapter(o.entityType).isSingleton===!0)return{success:!1,error:`${o.entityType} is a singleton entity and cannot be deleted through system tools. Update it instead.`};let d=A(s.userPermissionLevel),u=await _(t,{entityType:o.entityType,identifier:o.id},{visibilityScope:d,logger:i});if(!u.ok)return{success:!1,error:u.error};let{entity:p}=u;if(o.confirmed){let g=n.validateConfirmed(o.confirmationToken,o);if(g)return g;try{await t.deleteEntity({entityType:o.entityType,id:p.id})}catch(h){return{success:!1,error:P(h,"Failed to delete entity")}}return{success:!0,data:{deleted:p.id}}}let m=Be(p),f=n.buildArgs((g)=>({...o,id:p.id,confirmed:!0,confirmationToken:g}));return{needsConfirmation:!0,toolName:"system_delete",summary:`Delete "${m}"?`,preview:p.content.slice(0,200),args:f}},{visibility:"admin",sideEffects:"writes"})}function gl(e,t){let r=t.map(({oldText:o,newText:s},a)=>{let l=e.indexOf(o);if(!o||l<0)throw Error(`Edit ${a+1}: oldText was not found. Fetch the entity again and provide exact text.`);if(e.indexOf(o,l+1)!==-1)throw Error(`Edit ${a+1}: oldText is ambiguous. Include more surrounding text to match exactly once.`);return{start:l,end:l+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 an}from"util";class _e{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=(b)=>{if(b=this.postProcess(b,r),i){setTimeout(function(){i(b)},0);return}else return b},s=t.length,a=e.length,l=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}],f=this.extractCommon(m[0],t,e,0,r);if(m[0].oldPos+1>=a&&f+1>=s)return o(this.buildValues(m[0].lastComponent,t,e));let g=-1/0,h=1/0,S=()=>{for(let b=Math.max(g,-l);b<=Math.min(h,l);b+=2){let y,v=m[b-1],R=m[b+1];if(v)m[b-1]=void 0;let I=!1;if(R){let z=R.oldPos-b;I=R&&0<=z&&z<s}let E=v&&v.oldPos+1<a;if(!I&&!E){m[b]=void 0;continue}if(!E||I&&v.oldPos<R.oldPos)y=this.addToPath(R,!0,!1,0,r);else y=this.addToPath(v,!1,!0,1,r);if(f=this.extractCommon(y,t,e,b,r),y.oldPos+1>=a&&f+1>=s)return o(this.buildValues(y.lastComponent,t,e))||!0;else{if(m[b]=y,y.oldPos+1>=a)h=Math.min(h,b-1);if(f+1>=s)g=Math.max(g,b+1)}}l++};if(i)(function b(){setTimeout(function(){if(l>d||Date.now()>p)return i(void 0);if(!S())b()},0)})();else while(l<=d&&Date.now()<=p){let b=S();if(b)return b}}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,l=a-i,d=0;while(l+1<o&&a+1<s&&this.equals(r[a+1],t[l+1],n))if(l++,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,l}equals(e,t,r){if(r.comparator)return r.comparator(e,t);else return e===t||!!r.ignoreCase&&e.toLowerCase()===t.toLowerCase()}removeEmpty(e){let t=[];for(let r=0;r<e.length;r++)if(e[r])t.push(e[r]);return t}castInput(e,t){return e}tokenize(e,t){return Array.from(e)}join(e){return e.join("")}postProcess(e,t){return e}get useLongestToken(){return!1}buildValues(e,t,r){let i=[],n;while(e)i.push(e),n=e.previousComponent,delete e.previousComponent,e=n;i.reverse();let o=i.length,s=0,a=0,l=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 f=r[l+m];return f.length>p.length?f:p}),d.value=this.join(u)}else d.value=this.join(t.slice(a,a+d.count));if(a+=d.count,!d.added)l+=d.count}else d.value=this.join(r.slice(l,l+d.count)),l+=d.count}return i}}class hl extends _e{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}}var yl=new hl;function hr(e,t,r){return yl.diff(e,t,r)}class vl extends _e{constructor(){super(...arguments);this.tokenize=Og}equals(e,t,r){if(r.ignoreWhitespace){if(!r.newlineIsToken||!e.includes(`
84
84
  `))e=e.trim();if(!r.newlineIsToken||!t.includes(`
85
85
  `))t=t.trim()}else if(r.ignoreNewlineAtEof&&!r.newlineIsToken){if(e.endsWith(`
@@ -92,14 +92,14 @@ ${Gc(i)}`:a,args:t.buildArgs((d)=>({...l,confirmed:!0,confirmationToken:d}))}}as
92
92
  `}function Mg(e,t,r,i,n,o,s){if(typeof s==="function")s={callback:s};if(!(s===null||s===void 0?void 0:s.callback)){let a=Ji(e,t,r,i,n,o,s);if(!a)return;return yr(a,s===null||s===void 0?void 0:s.headerOptions)}else{let{callback:a}=s;Ji(e,t,r,i,n,o,Object.assign(Object.assign({},s),{callback:(l)=>{if(!l)a(void 0);else a(yr(l,s.headerOptions))}}))}}function Lg(e){let t=e.endsWith(`
93
93
  `),r=e.split(`
94
94
  `).map((i)=>i+`
95
- `);if(t)r.pop();else r.push(r.pop().slice(0,-1));return r}var Re=c.enum(["png","jpg","jpeg","webp","gif","svg"]),Sl=c.enum(["pending","draft","failed"]),Rl=c.enum(["fallback","generated","owner"]),wl=c.object({title:c.string().optional(),alt:c.string().optional(),altSource:Rl.optional().meta({studioWidget:"provenance"}),format:Re.optional().meta({studioWidget:"provenance"}),mediaType:c.string().optional().meta({studioWidget:"provenance"}),sizeBytes:c.number().int().nonnegative().optional().meta({studioWidget:"provenance"}),width:c.number().optional().meta({studioWidget:"provenance"}),height:c.number().optional().meta({studioWidget:"provenance"}),status:Sl.optional().meta({studioWidget:"provenance"}),processingJobId:c.string().optional().meta({studioWidget:"hidden"}),processingError:c.string().optional().meta({studioWidget:"provenance"}),sourceUrl:c.url().optional().meta({studioWidget:"provenance"}),sourceEntityType:c.string().optional().meta({studioWidget:"provenance"}),sourceEntityId:c.string().optional().meta({studioWidget:"provenance"}),sourceUploadId:c.string().optional().meta({studioWidget:"provenance"}),sourceFilename:c.string().optional().meta({studioWidget:"provenance"}),sourceMediaType:c.string().optional().meta({studioWidget:"provenance"}),attachmentType:c.string().optional().meta({studioWidget:"provenance"}),dedupKey:c.string().optional().meta({studioWidget:"hidden"})}).superRefine((e,t)=>{if(e.status==="pending"||e.status==="failed")return;for(let[r,i]of[["format",Re],["width",c.number()],["height",c.number()]]){let n=i.safeParse(e[r]);if(!n.success)for(let o of n.error.issues)t.addIssue({...o,path:[r,...o.path]})}}),Il=bl.extend({entityType:c.literal("image"),metadata:wl}),Ug=c.object({url:c.string(),alt:c.string(),title:c.string(),width:c.number(),height:c.number()});var Bg=c.object({alt:c.string().trim().min(1),altSource:c.enum(["generated","owner"])});function $g(e){let t=Bg.safeParse(e);return t.success?t.data.alt:void 0}function xl(e){return/^https?:\/\//i.test(e)}async function Pl(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 at(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 ct(e){let t=at(e);if(!t)throw Error("Invalid image data URL");return t}function vr(e){let t=e.toLowerCase(),r=t==="svg+xml"?"svg":t,i=Re.safeParse(r);return i.success?i.data:null}async function _g(e){return Pl(e,"image/")}function Cl(e){let t=(...i)=>i.every((n,o)=>e[o]===n),r=(i,n)=>Buffer.from(e.subarray(i,n)).toString("latin1");if(t(137,80,78,71))return"png";if(t(255,216,255))return"jpg";if(t(71,73,70,56))return"gif";if(r(0,4)==="RIFF"&&r(8,12)==="WEBP")return"webp";return null}function we(e){switch(e){case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";default:return`image/${e}`}}var Fg=64;async function Gi(e){let t=await e(0,Fg),r=Cl(t);if(!r)return;let i=r==="jpg"||r==="jpeg"?await Zg(e):Yi(t);return{format:r,mediaType:we(r),width:i?.width??0,height:i?.height??0}}function Qi(e){return async(t,r)=>e.subarray(t,r)}function Ki(e){let t=/\s/.test(e)?e.replace(/\s/g,""):e;return async(r,i)=>{let n=Math.floor(r/3);return Buffer.from(t.slice(n*4,Math.ceil(i/3)*4),"base64").subarray(r-n*3,i-n*3)}}function Ng(e){return(t,r)=>Bun.file(e).slice(t,r).bytes()}async function Zg(e){let t=st(2),r=async(i)=>i.done?i.value:r(t.next(await e(...i.value)));return r(t.next(new Uint8Array))}function*st(e){let t=Buffer.from(yield[e,e+4]);if(t.byteLength<2||t[0]!==255)return null;let r=t[1]??0;if(r===255)return yield*st(e+1);if(r===1||r>=208&&r<=215)return yield*st(e+2);if(r===218||r===217)return null;if(t.byteLength<4)return null;if(r>=192&&r<=207&&![196,200,204].includes(r)){let n=Buffer.from(yield[e+5,e+9]);if(n.byteLength<4)return null;return{height:n.readUInt16BE(0),width:n.readUInt16BE(2)}}let i=t.readUInt16BE(2);if(i<2)return null;return yield*st(e+2+i)}function Vi(e){return Yi(Buffer.from(e,"base64"))}function Yi(e){let t=Buffer.from(e.buffer,e.byteOffset,e.byteLength);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=st(2),i=(n)=>n.done?n.value:i(r.next(t.subarray(...n.value)));return i(r.next(new Uint8Array))}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 Wg(e){let t=vr(e);if(!t)throw Error(`Unsupported image format: ${e}`);return t}function Tl(e){return{title:e.title,alt:e.alt??e.title,...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 qg(e){if(e===""||lt.safeParse(e).success)return{};let{format:t,base64:r}=ct(e),i=Vi(r);return{format:Wg(t),width:i?.width??0,height:i?.height??0}}function Xi(e){let{title:t,alt:r,...i}=Tl(e);return{entityType:"image",content:e.asset.ref,metadata:{title:t,alt:r,...e.description,sizeBytes:e.asset.sizeBytes,...i}}}function Jg(e){return{entityType:"image",content:"",metadata:Tl(e)}}function YT(e){return Al(e,{skipInvalid:!0,noRefs:!0,sortKeys:!0})}function kl(e){return El(e)}async function Dl(e,t){let r=lt.safeParse(t.content);if(!r.success){let i=at(t.content);if(!i)return;let n=vr(i.format);return{bytes:Buffer.from(i.base64,"base64"),mediaType:n?we(n):`image/${i.format}`}}return{bytes:await jl(e,r.data),mediaType:Gg(t)}}async function Ol(e,t){if(!lt.safeParse(t.content).success)return at(t.content)?t.content:void 0;let r=await Dl(e,t);return r&&`data:${r.mediaType};base64,${r.bytes.toString("base64")}`}function Gg(e){let t=e.metadata.mediaType;if(typeof t==="string")return t;let r=Re.safeParse(e.metadata.format);return r.success?we(r.data):"image/png"}var Qg=c.record(c.string(),c.unknown());function zl(e,t){let r=Ie.exec(e.content);if(!r?.[1])return;try{let i=Qg.safeParse(kl(r[1]));if(i.success){let n=i.data[t];return typeof n==="string"?n:void 0}}catch{return}return}function Kg(e){return zl(e,"coverImageId")}function Vg(e){return zl(e,"ogImageId")}function en(e,t){return{...e,content:Fe(e.content,"coverImageId",t)}}function tn(e,t){return{...e,content:Fe(e.content,"ogImageId",t)}}var rn=Ml();function Yg(e,t){let r=rn.parse(e),i=new Map;br(r,"definition",(o)=>{if(!i.has(o.identifier))i.set(o.identifier,o)});let n=new Set;return br(r,(o,s,a)=>{if(o.type!=="image"&&o.type!=="imageReference")return;let l=o.type==="image"?o:i.get(o.identifier);if(!l)return;let d=t(l.url);if(d===l.url)return;if(n.add(l.url),o.type==="image")o.url=d;else if(a&&s!==void 0)a.children[s]={type:"image",url:d,alt:o.alt,title:l.title}}),n.size>0?rn.stringify(r):e}function Xg(e){let t=[],r=rn.parse(e);return br(r,"image",(i)=>{t.push({url:i.url,alt:i.alt??"",title:i.title??void 0})}),t}var on=26214400,eh=["png","jpg","gif","webp"].map(we);async function th(e,t,r){let{read:i,bytes:n}=rh(t),o=await Gi(i);if(!o)throw Error("Unsupported image format: not a PNG, JPEG, GIF or WebP");let s=await e.stageAsset(n,{maxBytes:on});return{stagedAsset:s,entity:Xi({...r,asset:s,description:o})}}function rh(e){if("bytes"in e)return{read:Qi(e.bytes),bytes:e.bytes};let{base64:t}=ct(e.dataUrl);return{read:Ki(t),bytes:nn(t)}}var nh="6b7fa434f92a8b80aab02d9bf1a12e49ffcae424e4013a1c4f68b67e3d2bbcd0";function oh(e,t){return(t==="pending"||t==="failed")&&e===nh}var Ll=400;function Sr(e,t,r){if(r===null)return!Object.hasOwn(e,t);return Object.hasOwn(e,t)&&an(e[t],r)}function dt(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 sh(e,t,r){if(r.has(t))return Se(e.content).frontmatter[t];return t==="visibility"?e.visibility:e.metadata[t]}function Nl(e,t){let r=Object.fromEntries(Object.entries(Se(t).frontmatter).filter(([i])=>i!=="visibility"));return Object.keys(r).length>0?{...e,content:mr(r,e.content)}:e}function Zl(e,t,r){let{visibility:i,coverImageId:n,ogImageId:o,...s}=t,a=i===void 0?e.visibility:_l.parse(i),l=!(r.getAdapter(e.entityType).metadataFromFrontmatter===!0&&!Ie.test(e.content)),d=l&&Object.hasOwn(t,"coverImageId")?en(e,typeof n==="string"?n:null):e,u=l&&Object.hasOwn(t,"ogImageId")?tn(d,typeof o==="string"?o:null):d,p={...e.metadata};for(let[y,v]of Object.entries(s))if(v===null)delete p[y];else p[y]=v;let m={...u,visibility:a,metadata:p};for(let[y,v]of Object.entries(s))if(v===null)delete m[y];else m[y]=v;let f=dt(e.entityType,r),g=r.getAdapter(e.entityType),h=new Set(Object.keys((g.writtenFrontmatterSchema??g.frontmatterSchema)?.shape??{})),S=g.metadataFromFrontmatter===!0?Se(m.content).frontmatter:{},b=!1;for(let[y,v]of Object.entries(t))if(f.has(y))m.content=Fe(m.content,y,v),b=!0;else if(Object.hasOwn(S,y)&&h.has(y))m.content=Fe(m.content,y,v);if(b)m.metadata=r.projectMetadata(e.entityType,m.content,p);if(r.getAdapter(e.entityType).metadataFromFrontmatter===!0){let y={...m.metadata};for(let v of["coverImageId","ogImageId"]){if(!Object.hasOwn(t,v))continue;let R=t[v];if(typeof R==="string")y[v]=R;else delete y[v]}m.metadata=y}return m}function ah(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 l=o.metadata?.[a];if(an(n.metadata?.[a],l))continue;if(l===void 0)delete s[a];else s[a]=l}return{...e,...o,id:e.id,entityType:e.entityType,created:e.created,updated:e.updated,contentHash:e.contentHash,content:t,metadata:s,visibility:gr(t)??e.visibility}}var ch=new Set(["visibility","coverImageId","ogImageId"]),lh=c.record(c.string(),c.unknown());function dh(e,t,r,i){if(t.kind!=="fields")return;let n=t.fields,o=r.getEffectiveFrontmatterSchema(e.entityType);if(!o)return;let s=dt(e.entityType,r),a=Object.keys(n).filter((h)=>s.has(h)),l;try{if(l=Zl(e,n,r),a.length>0){let h=r.validateEntity(e.entityType,l),S=i.serializeEntity(h),b=Se(S).frontmatter,y=i.deserializeEntity(S,e.entityType).metadata??{};for(let v of a){let R=n[v];if(!Sr(b,v,R)||!Sr(y,v,R))return{success:!1,error:`The requested ${v} value would not survive frontmatter persistence.`}}}}catch(h){return{success:!1,error:P(h,"Invalid field update")}}let d=r.getAdapter(e.entityType).metadataFromFrontmatter===!0,u=Object.keys(n).filter((h)=>!s.has(h)&&(!ch.has(h)||d&&h!=="visibility")&&(h in o.shape));if(u.length===0)return;let p=r.getAdapter(e.entityType),m;try{l=r.validateEntity(e.entityType,l),m=p.extractMetadata(l)}catch{return}let f=[],g=[];for(let h of u){let S=n[h];if(Object.hasOwn(m,h)){if(!Sr(m,h,S))f.push(h)}else if(S!==null||!Object.hasOwn(e.metadata,h))g.push(h)}if(g.length>0){let h;try{h=p.parseFrontMatter(p.toMarkdown(l),lh)}catch{if(f.length===0)return}if(h){for(let S of g)if(!Sr(h,S,n[S]))f.push(S)}}if(f.length===0)return;return{success:!1,error:`${e.entityType} does not persist ${f.join(", ")} through 'fields'. The update would report success without changing anything. Provide full markdown with frontmatter via 'content' instead.`}}function Hl(e,t,r){let i=Ie.exec(e.content)?.[0];if(i===void 0||!t.trim()||Ie.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 uh(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&&!Ie.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 ph(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 mh(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 Wl(e,t,r){let i=dt(e.entityType,r);if(t.kind==="fields")return Object.entries(t.fields).map(([a,l])=>{let d=sh(e,a,i);if(!i.has(a))return`${a}: ${String(d??"(empty)")} \u2192 ${String(l)}`;let u=r.getEffectiveFrontmatterSchema(e.entityType)?.shape[a],p=u!==void 0&&c.safeParse(u,d).success,m=d===void 0?"(absent)":`${JSON.stringify(d)}${p?"":" (invalid existing value)"}`,f=l===null?"(removed)":JSON.stringify(l);return`${a}: ${m} \u2192 ${f}`}).join(`
95
+ `);if(t)r.pop();else r.push(r.pop().slice(0,-1));return r}var we=c.enum(["png","jpg","jpeg","webp","gif","svg"]),Sl=c.enum(["pending","draft","failed"]),Rl=c.enum(["fallback","generated","owner"]),wl=c.object({title:c.string().optional(),alt:c.string().optional(),altSource:Rl.optional().meta({studioWidget:"provenance"}),format:we.optional().meta({studioWidget:"provenance"}),mediaType:c.string().optional().meta({studioWidget:"provenance"}),sizeBytes:c.number().int().nonnegative().optional().meta({studioWidget:"provenance"}),width:c.number().optional().meta({studioWidget:"provenance"}),height:c.number().optional().meta({studioWidget:"provenance"}),status:Sl.optional().meta({studioWidget:"provenance"}),processingJobId:c.string().optional().meta({studioWidget:"hidden"}),processingError:c.string().optional().meta({studioWidget:"provenance"}),sourceUrl:c.url().optional().meta({studioWidget:"provenance"}),sourceEntityType:c.string().optional().meta({studioWidget:"provenance"}),sourceEntityId:c.string().optional().meta({studioWidget:"provenance"}),sourceUploadId:c.string().optional().meta({studioWidget:"provenance"}),sourceFilename:c.string().optional().meta({studioWidget:"provenance"}),sourceMediaType:c.string().optional().meta({studioWidget:"provenance"}),attachmentType:c.string().optional().meta({studioWidget:"provenance"}),dedupKey:c.string().optional().meta({studioWidget:"hidden"})}).superRefine((e,t)=>{if(e.status==="pending"||e.status==="failed")return;for(let[r,i]of[["format",we],["width",c.number()],["height",c.number()]]){let n=i.safeParse(e[r]);if(!n.success)for(let o of n.error.issues)t.addIssue({...o,path:[r,...o.path]})}}),Il=bl.extend({entityType:c.literal("image"),metadata:wl}),Ug=c.object({url:c.string(),alt:c.string(),title:c.string(),width:c.number(),height:c.number()});var Bg=c.object({alt:c.string().trim().min(1),altSource:c.enum(["generated","owner"])});function $g(e){let t=Bg.safeParse(e);return t.success?t.data.alt:void 0}function xl(e){return/^https?:\/\//i.test(e)}async function Pl(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 at(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 ct(e){let t=at(e);if(!t)throw Error("Invalid image data URL");return t}function vr(e){let t=e.toLowerCase(),r=t==="svg+xml"?"svg":t,i=we.safeParse(r);return i.success?i.data:null}async function _g(e){return Pl(e,"image/")}function Cl(e){let t=(...i)=>i.every((n,o)=>e[o]===n),r=(i,n)=>Buffer.from(e.subarray(i,n)).toString("latin1");if(t(137,80,78,71))return"png";if(t(255,216,255))return"jpg";if(t(71,73,70,56))return"gif";if(r(0,4)==="RIFF"&&r(8,12)==="WEBP")return"webp";return null}function Ie(e){switch(e){case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";default:return`image/${e}`}}var Fg=64;async function Gi(e){let t=await e(0,Fg),r=Cl(t);if(!r)return;let i=r==="jpg"||r==="jpeg"?await Zg(e):Yi(t);return{format:r,mediaType:Ie(r),width:i?.width??0,height:i?.height??0}}function Qi(e){return async(t,r)=>e.subarray(t,r)}function Ki(e){let t=/\s/.test(e)?e.replace(/\s/g,""):e;return async(r,i)=>{let n=Math.floor(r/3);return Buffer.from(t.slice(n*4,Math.ceil(i/3)*4),"base64").subarray(r-n*3,i-n*3)}}function Ng(e){return(t,r)=>Bun.file(e).slice(t,r).bytes()}async function Zg(e){let t=st(2),r=async(i)=>i.done?i.value:r(t.next(await e(...i.value)));return r(t.next(new Uint8Array))}function*st(e){let t=Buffer.from(yield[e,e+4]);if(t.byteLength<2||t[0]!==255)return null;let r=t[1]??0;if(r===255)return yield*st(e+1);if(r===1||r>=208&&r<=215)return yield*st(e+2);if(r===218||r===217)return null;if(t.byteLength<4)return null;if(r>=192&&r<=207&&![196,200,204].includes(r)){let n=Buffer.from(yield[e+5,e+9]);if(n.byteLength<4)return null;return{height:n.readUInt16BE(0),width:n.readUInt16BE(2)}}let i=t.readUInt16BE(2);if(i<2)return null;return yield*st(e+2+i)}function Vi(e){return Yi(Buffer.from(e,"base64"))}function Yi(e){let t=Buffer.from(e.buffer,e.byteOffset,e.byteLength);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=st(2),i=(n)=>n.done?n.value:i(r.next(t.subarray(...n.value)));return i(r.next(new Uint8Array))}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 Wg(e){let t=vr(e);if(!t)throw Error(`Unsupported image format: ${e}`);return t}function Tl(e){return{title:e.title,alt:e.alt??e.title,...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 qg(e){if(e===""||lt.safeParse(e).success)return{};let{format:t,base64:r}=ct(e),i=Vi(r);return{format:Wg(t),width:i?.width??0,height:i?.height??0}}function Xi(e){let{title:t,alt:r,...i}=Tl(e);return{entityType:"image",content:e.asset.ref,metadata:{title:t,alt:r,...e.description,sizeBytes:e.asset.sizeBytes,...i}}}function Jg(e){return{entityType:"image",content:"",metadata:Tl(e)}}function YT(e){return Al(e,{skipInvalid:!0,noRefs:!0,sortKeys:!0})}function kl(e){return El(e)}async function Dl(e,t){let r=lt.safeParse(t.content);if(!r.success){let i=at(t.content);if(!i)return;let n=vr(i.format);return{bytes:Buffer.from(i.base64,"base64"),mediaType:n?Ie(n):`image/${i.format}`}}return{bytes:await jl(e,r.data),mediaType:Gg(t)}}async function Ol(e,t){if(!lt.safeParse(t.content).success)return at(t.content)?t.content:void 0;let r=await Dl(e,t);return r&&`data:${r.mediaType};base64,${r.bytes.toString("base64")}`}function Gg(e){let t=e.metadata.mediaType;if(typeof t==="string")return t;let r=we.safeParse(e.metadata.format);return r.success?Ie(r.data):"image/png"}var Qg=c.record(c.string(),c.unknown());function zl(e,t){let r=de.exec(e.content);if(!r?.[1])return;try{let i=Qg.safeParse(kl(r[1]));if(i.success){let n=i.data[t];return typeof n==="string"?n:void 0}}catch{return}return}function Kg(e){return zl(e,"coverImageId")}function Vg(e){return zl(e,"ogImageId")}function en(e,t){return{...e,content:Fe(e.content,"coverImageId",t)}}function tn(e,t){return{...e,content:Fe(e.content,"ogImageId",t)}}var rn=Ml();function Yg(e,t){let r=rn.parse(e),i=new Map;br(r,"definition",(o)=>{if(!i.has(o.identifier))i.set(o.identifier,o)});let n=new Set;return br(r,(o,s,a)=>{if(o.type!=="image"&&o.type!=="imageReference")return;let l=o.type==="image"?o:i.get(o.identifier);if(!l)return;let d=t(l.url);if(d===l.url)return;if(n.add(l.url),o.type==="image")o.url=d;else if(a&&s!==void 0)a.children[s]={type:"image",url:d,alt:o.alt,title:l.title}}),n.size>0?rn.stringify(r):e}function Xg(e){let t=[],r=rn.parse(e);return br(r,"image",(i)=>{t.push({url:i.url,alt:i.alt??"",title:i.title??void 0})}),t}var on=26214400,eh=["png","jpg","gif","webp"].map(Ie);async function th(e,t,r){let{read:i,bytes:n}=rh(t),o=await Gi(i);if(!o)throw Error("Unsupported image format: not a PNG, JPEG, GIF or WebP");let s=await e.stageAsset(n,{maxBytes:on});return{stagedAsset:s,entity:Xi({...r,asset:s,description:o})}}function rh(e){if("bytes"in e)return{read:Qi(e.bytes),bytes:e.bytes};let{base64:t}=ct(e.dataUrl);return{read:Ki(t),bytes:nn(t)}}var nh="6b7fa434f92a8b80aab02d9bf1a12e49ffcae424e4013a1c4f68b67e3d2bbcd0";function oh(e,t){return(t==="pending"||t==="failed")&&e===nh}var Ll=400;function Sr(e,t,r){if(r===null)return!Object.hasOwn(e,t);return Object.hasOwn(e,t)&&an(e[t],r)}function dt(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 sh(e,t,r){if(r.has(t))return Re(e.content).frontmatter[t];return t==="visibility"?e.visibility:e.metadata[t]}function Nl(e,t){let r=Object.fromEntries(Object.entries(Re(t).frontmatter).filter(([i])=>i!=="visibility"));return Object.keys(r).length>0?{...e,content:mr(r,e.content)}:e}function Zl(e,t,r){let{visibility:i,coverImageId:n,ogImageId:o,...s}=t,a=i===void 0?e.visibility:_l.parse(i),l=!(r.getAdapter(e.entityType).metadataFromFrontmatter===!0&&!de.test(e.content)),d=l&&Object.hasOwn(t,"coverImageId")?en(e,typeof n==="string"?n:null):e,u=l&&Object.hasOwn(t,"ogImageId")?tn(d,typeof o==="string"?o:null):d,p={...e.metadata};for(let[y,v]of Object.entries(s))if(v===null)delete p[y];else p[y]=v;let m={...u,visibility:a,metadata:p};for(let[y,v]of Object.entries(s))if(v===null)delete m[y];else m[y]=v;let f=dt(e.entityType,r),g=r.getAdapter(e.entityType),h=new Set(Object.keys((g.writtenFrontmatterSchema??g.frontmatterSchema)?.shape??{})),S=g.metadataFromFrontmatter===!0?Re(m.content).frontmatter:{},b=!1;for(let[y,v]of Object.entries(t))if(f.has(y))m.content=Fe(m.content,y,v),b=!0;else if(Object.hasOwn(S,y)&&h.has(y))m.content=Fe(m.content,y,v);if(b)m.metadata=r.projectMetadata(e.entityType,m.content,p);if(r.getAdapter(e.entityType).metadataFromFrontmatter===!0){let y={...m.metadata};for(let v of["coverImageId","ogImageId"]){if(!Object.hasOwn(t,v))continue;let R=t[v];if(typeof R==="string")y[v]=R;else delete y[v]}m.metadata=y}return m}function ah(e,t,r){let i=r.getAdapter(e.entityType),n=(l)=>i.metadataFromFrontmatter===!0&&!de.test(l)?i.toMarkdown({...e,content:l}):l,o=i.fromMarkdown(n(e.content)),s=i.fromMarkdown(n(t)),a={...e.metadata};for(let l of new Set([...Object.keys(o.metadata??{}),...Object.keys(s.metadata??{})])){let d=s.metadata?.[l];if(an(o.metadata?.[l],d))continue;if(d===void 0)delete a[l];else a[l]=d}return{...e,...s,id:e.id,entityType:e.entityType,created:e.created,updated:e.updated,contentHash:e.contentHash,content:t,metadata:a,visibility:gr(t)??e.visibility}}var ch=new Set(["visibility","coverImageId","ogImageId"]),lh=c.record(c.string(),c.unknown());function dh(e,t,r,i){if(t.kind!=="fields")return;let n=t.fields,o=r.getEffectiveFrontmatterSchema(e.entityType);if(!o)return;let s=dt(e.entityType,r),a=Object.keys(n).filter((h)=>s.has(h)),l;try{if(l=Zl(e,n,r),a.length>0){let h=r.validateEntity(e.entityType,l),S=i.serializeEntity(h),b=Re(S).frontmatter,y=i.deserializeEntity(S,e.entityType).metadata??{};for(let v of a){let R=n[v];if(!Sr(b,v,R)||!Sr(y,v,R))return{success:!1,error:`The requested ${v} value would not survive frontmatter persistence.`}}}}catch(h){return{success:!1,error:P(h,"Invalid field update")}}let d=r.getAdapter(e.entityType).metadataFromFrontmatter===!0,u=Object.keys(n).filter((h)=>!s.has(h)&&(!ch.has(h)||d&&h!=="visibility")&&(h in o.shape));if(u.length===0)return;let p=r.getAdapter(e.entityType),m;try{l=r.validateEntity(e.entityType,l),m=p.extractMetadata(l)}catch{return}let f=[],g=[];for(let h of u){let S=n[h];if(Object.hasOwn(m,h)){if(!Sr(m,h,S))f.push(h)}else if(S!==null||!Object.hasOwn(e.metadata,h))g.push(h)}if(g.length>0){let h;try{h=p.parseFrontMatter(p.toMarkdown(l),lh)}catch{if(f.length===0)return}if(h){for(let S of g)if(!Sr(h,S,n[S]))f.push(S)}}if(f.length===0)return;return{success:!1,error:`${e.entityType} does not persist ${f.join(", ")} through 'fields'. The update would report success without changing anything. Provide full markdown with frontmatter via 'content' instead.`}}function Hl(e,t,r){let i=de.exec(e.content)?.[0];if(i===void 0||!t.trim()||de.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 uh(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&&!de.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 ph(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 mh(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 Wl(e,t,r){let i=dt(e.entityType,r);if(t.kind==="fields")return Object.entries(t.fields).map(([a,l])=>{let d=sh(e,a,i);if(!i.has(a))return`${a}: ${String(d??"(empty)")} \u2192 ${String(l)}`;let u=r.getEffectiveFrontmatterSchema(e.entityType)?.shape[a],p=u!==void 0&&c.safeParse(u,d).success,m=d===void 0?"(absent)":`${JSON.stringify(d)}${p?"":" (invalid existing value)"}`,f=l===null?"(removed)":JSON.stringify(l);return`${a}: ${m} \u2192 ${f}`}).join(`
96
96
  `);let n=e.content.split(`
97
97
  `),o=t.content.split(`
98
98
  `),s=hr(n,o,{maxEditLength:Ll});if(!s)return`Full content replacement (line diff omitted: more than ${Ll} changed lines).`;return s.filter((a)=>a.added||a.removed).flatMap((a)=>a.value.map((l)=>`${a.added?"+":"-"} ${l}`)).join(`
99
99
  `)}function ql(e,t,r,i){return dh(e,t,r,i)??uh(e.entityType,t,r)??ph(e.entityType,t,r)}function Jl(e,t,r){return Fl(e.entityType,e.metadata.status,mh(e,t,r),r)==="non-publish"?"update":"publish"}function Gl(e,t,r){return t.kind==="content"?ah(e,t.content,r):Zl(e,t.fields,r)}var Ul=5,Bl=160;function fh(e){return e.length>Bl?`${e.slice(0,Bl)}\u2026`:e}function gh(e){if(e===void 0)return"(removed)";return typeof e==="string"?e:JSON.stringify(e)}function $l(e){return e.trim().length>0}function sn(e,t){if(t.length===0)return;let r=t.length-Ul;return[e,...t.slice(0,Ul).map((i)=>`> ${fh(i)}`),...r>0?[`\u2026 and ${r} more changed lines`]:[]].join(`
100
100
  `)}function hh(e,t){return[...new Set([...Object.keys(e.metadata),...Object.keys(t.metadata)])].filter((r)=>!an(e.metadata[r],t.metadata[r])).map((r)=>`${r}: ${gh(t.metadata[r])}`)}function Ql(e,t){if(t.content===e.content)return sn("Stored now:",hh(e,t));let r=hr(e.content.split(`
101
101
  `),t.content.split(`
102
- `)),i=r.filter((n)=>n.added).flatMap((n)=>n.value).filter($l);if(i.length>0)return sn("Stored now:",i);return sn("No longer stored:",r.filter((n)=>n.removed).flatMap((n)=>n.value).filter($l))}function xe(e){return{success:!1,error:e}}async function yh(e,t,r,i){if(t.confirmed&&t.contentHash&&r.contentHash!==t.contentHash)return xe("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:gl(r.content,n.edits)}};if(n.content!==void 0)return Kl(e,r,n.content);if(n.source===void 0)return xe(it);let o=await ur(e,n.source,i,{confirmed:t.confirmed===!0});if(!o.success)return o;return Kl(e,r,o.content,pr(n.source,o))}function Kl(e,t,r,i){let n=Hl(t,r,e.entityRegistry);if(typeof n!=="string")return n;return{operation:{kind:"content",content:n},...i?{source:i}:{}}}function Vl(e){let{entityService:t,logger:r,entityRegistry:i}=e,n=Y({label:"update",requestNoun:"the update"}),o=async(d,u,p,m)=>{let f=n.validateConfirmed(d.confirmationToken,d);if(f)return f;let g=Gl(u,p,i);if(g.visibility!==u.visibility&&!fr(m.userPermissionLevel,g.visibility))return xe(`Cannot set entity visibility to "${g.visibility}" \u2014 caller permission "${m.userPermissionLevel??"public"}" is not allowed to write at that level.`);try{let b=Ue(m);if((await t.updateEntity({entity:g,options:{expectedContentHash:u.contentHash,...b?{eventContext:b}:{}}})).skipReason==="content-conflict")return xe("Entity was modified before the update could be saved. Please request and confirm the update again.")}catch(b){return xe(P(b,"Failed to update entity"))}let h=await t.getEntity({entityType:u.entityType,id:u.id,visibilityScope:A(m.userPermissionLevel)}),S=h?Ql(u,h):void 0;return{success:!0,data:{updated:u.id},...S!==void 0&&{completionDetail:S}}},s=async(d,u,p)=>{if(u.kind!=="fields")return d;if(i.getAdapter(d.entityType).metadataFromFrontmatter!==!0)return d;let m=dt(d.entityType,i);if(!Object.keys(u.fields).some((g)=>m.has(g)))return d;let f=await t.getEntity({entityType:d.entityType,id:d.id,visibilityScope:p,source:!0});return f?Nl(d,f.content):d},a=(d,u,{operation:p,source:m})=>({needsConfirmation:!0,toolName:"system_update",summary:`Update "${Be(u)}"?`,completionSummary:`Updated ${Wc(u.entityType)}.`,preview:Wl(u,p,i),args:n.buildArgs((f)=>({...d,...m?{operation:{source:m}}:{},id:u.id,confirmed:!0,confirmationToken:f,contentHash:u.contentHash}))});return{...W("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.",ir,async(d,u)=>{await i.ensureGroupingsCurrent(d.entityType);let p=nr(i,d.entityType,d.operation.fields,{on:"update",allow:["visibility","coverImageId","ogImageId"]});if(p)return xe(p);let m=await _(t,{entityType:d.entityType,identifier:d.id},{visibilityScope:A(u.userPermissionLevel),logger:r});if(!m.ok)return xe(m.error);let f=await yh(e,d,m.entity,u);if("success"in f)return f;let{operation:g}=f,h=await s(m.entity,g,A(u.userPermissionLevel)),S=ql(h,g,i,t);if(S)return S;let b=B(e,d.entityType,Jl(h,g,i),u);if(b)return b;return d.confirmed?o(d,h,g,u):a(d,h,f)},{visibility:"trusted",sideEffects:"writes"}),modelInput:Zc(e.entityRegistry,Me(e.permissionService))}}function Yl(e){return[cl(e),ml(e),fl(e),Vl(e)]}function Rr(e){if(e.interfaceType!==Xl)return;if(e.userPermissionLevel!=="public"||e.isAnchor)throw Error("Guest execution denied")}var id=3000,vh={limit:10,excerptChars:id},bh={limit:5,maxLimit:5,excerptChars:800};function nd(e){return e!==void 0&&ge(e)==="local"?bh:vh}var ed=`
102
+ `)),i=r.filter((n)=>n.added).flatMap((n)=>n.value).filter($l);if(i.length>0)return sn("Stored now:",i);return sn("No longer stored:",r.filter((n)=>n.removed).flatMap((n)=>n.value).filter($l))}function xe(e){return{success:!1,error:e}}async function yh(e,t,r,i){if(t.confirmed&&t.contentHash&&r.contentHash!==t.contentHash)return xe("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:gl(r.content,n.edits)}};if(n.content!==void 0)return Kl(e,r,n.content);if(n.source===void 0)return xe(it);let o=await ur(e,n.source,i,{confirmed:t.confirmed===!0});if(!o.success)return o;return Kl(e,r,o.content,pr(n.source,o))}function Kl(e,t,r,i){let n=Hl(t,r,e.entityRegistry);if(typeof n!=="string")return n;return{operation:{kind:"content",content:n},...i?{source:i}:{}}}function Vl(e){let{entityService:t,logger:r,entityRegistry:i}=e,n=Y({label:"update",requestNoun:"the update"}),o=async(d,u,p,m)=>{let f=n.validateConfirmed(d.confirmationToken,d);if(f)return f;let g=Gl(u,p,i);if(g.visibility!==u.visibility&&!fr(m.userPermissionLevel,g.visibility))return xe(`Cannot set entity visibility to "${g.visibility}" \u2014 caller permission "${m.userPermissionLevel??"public"}" is not allowed to write at that level.`);try{let b=Ue(m);if((await t.updateEntity({entity:g,options:{expectedContentHash:u.contentHash,...b?{eventContext:b}:{}}})).skipReason==="content-conflict")return xe("Entity was modified before the update could be saved. Please request and confirm the update again.")}catch(b){return xe(P(b,"Failed to update entity"))}let h=await t.getEntity({entityType:u.entityType,id:u.id,visibilityScope:A(m.userPermissionLevel)}),S=h?Ql(u,h):void 0;return{success:!0,data:{updated:u.id},...S!==void 0&&{completionDetail:S}}},s=async(d,u,p)=>{if(u.kind!=="fields")return d;if(i.getAdapter(d.entityType).metadataFromFrontmatter!==!0)return d;let m=dt(d.entityType,i);if(!Object.keys(u.fields).some((g)=>m.has(g)))return d;let f=await t.getEntity({entityType:d.entityType,id:d.id,visibilityScope:p,source:!0});return f?Nl(d,f.content):d},a=(d,u,{operation:p,source:m})=>({needsConfirmation:!0,toolName:"system_update",summary:`Update "${Be(u)}"?`,completionSummary:`Updated ${Wc(u.entityType)}.`,preview:Wl(u,p,i),args:n.buildArgs((f)=>({...d,...m?{operation:{source:m}}:{},id:u.id,confirmed:!0,confirmationToken:f,contentHash:u.contentHash}))});return{...W("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.",ir,async(d,u)=>{await i.ensureGroupingsCurrent(d.entityType);let p=nr(i,d.entityType,d.operation.fields,{on:"update",allow:["visibility","coverImageId","ogImageId"]});if(p)return xe(p);let m=await _(t,{entityType:d.entityType,identifier:d.id},{visibilityScope:A(u.userPermissionLevel),logger:r});if(!m.ok)return xe(m.error);let f=await yh(e,d,m.entity,u);if("success"in f)return f;let{operation:g}=f,h=await s(m.entity,g,A(u.userPermissionLevel)),S=ql(h,g,i,t);if(S)return S;let b=B(e,d.entityType,Jl(h,g,i),u);if(b)return b;return d.confirmed?o(d,h,g,u):a(d,h,f)},{visibility:"trusted",sideEffects:"writes"}),modelInput:Zc(e.entityRegistry,Me(e.permissionService))}}function Yl(e){return[cl(e),ml(e),fl(e),Vl(e)]}function Rr(e){if(e.interfaceType!==Xl)return;if(e.userPermissionLevel!=="public"||e.isAnchor)throw Error("Guest execution denied")}var id=3000,vh={limit:10,excerptChars:id},bh={limit:5,maxLimit:5,excerptChars:800};function nd(e){return e!==void 0&&he(e)==="local"?bh:vh}var ed=`
103
103
 
104
104
  \u2026
105
105
 
@@ -108,10 +108,10 @@ ${Gc(i)}`:a,args:t.buildArgs((d)=>({...l,confirmed:!0,confirmationToken:d}))}}as
108
108
  `).trim()).filter((n)=>n.length>0).map((n,o)=>({index:o,heading:td.test(n)?n.split(`
109
109
  `)[0]??"":"",text:n}))}function Ih(e,t){let r=cn(t.heading),i=cn(t.text);return Array.from(e).reduce((n,o)=>n+(i.has(o)?1:0)+(r.has(o)?1:0),0)}function rd(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 od(e,t,r=id){if(e.length<=r)return e;let i=cn(t),n=wh(e).map((a)=>({section:a,score:Ih(i,a)})).filter(({score:a})=>a>0).sort((a,l)=>l.score-a.score||a.section.index-l.section.index).map(({section:a})=>a),[o]=n;if(!o)return rd(e.trim(),r);if(o.text.length>r)return rd(o.text,r);let{kept:s}=n.reduce((a,l)=>{let d=l.text.length+(a.kept.length>0?ed.length:0);return a.used+d<=r?{used:a.used+d,kept:[...a.kept,l]}:a},{used:0,kept:[]});return s.sort((a,l)=>a.index-l.index).map((a,l,d)=>{let u=d[l-1];if(!u)return a.text;return`${a.index===u.index+1?`
110
110
 
111
- `:ed}${a.text}`}).join("")}var xh=0.5;function sd(e,t){let r=e??t.limit;return t.maxLimit===void 0?r:Math.min(r,t.maxLimit)}function ad(e,t,r,i){let n=Li(e.entity,r);if(n!==e.entity)return{...e,entity:n,excerpt:n.content};let o=$e(n.content);if(o.length<=i)return{...e,entity:n};let{content:s,...a}=n;return{...e,entity:a,excerpt:od(o,t,i),excerpted:!0}}var wr=(e)=>e==="public"?{publishedOnly:!0}:{};function Ph(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 cd(e){let{entityService:t,logger:r}=e;return[de("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. When a typed search's results hold that type's entities but not a detail the user asked about, the detail is not saved there: answer from what the results say and name what is missing, rather than searching the same type again with added words or a lower minScore. 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?'.",Ec,async(i,n)=>{Rr(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:sd(i.limit,e.searchBudget),filter:{visibilityScope:o},...wr(o)}})).map((m)=>ad({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??xh,a=await t.search({query:i.query,options:{limit:sd(i.limit,e.searchBudget),...i.scope.kind==="type"&&{types:[i.scope.entityType]},...i.includeUngenerated!==void 0&&{includeUngenerated:i.includeUngenerated},visibilityScope:o,...wr(o)}}),l=a.filter((u)=>u.score>=s),d=l.length===0?Ph(a,s):void 0;return{success:!0,data:{results:l.map((u)=>ad(u,i.query,e.entityRegistry,e.searchBudget.excerptChars)),...d&&{belowThreshold:d}}}},{visibility:"public",sideEffects:"none",cli:{name:"search"}}),de("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.",Ac,async(i,n)=>{if(Rr(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 _(t,{entityType:i.entityType,identifier:i.id},{visibilityScope:o,logger:r,read:{...wr(o),source:!0}});if(!s.ok)return{success:!1,error:s.error};let a=Li(s.entity,e.entityRegistry);return{success:!0,data:{entity:i.part==="body"?{...a,content:$e(a.content)}:a}}},{visibility:"public",sideEffects:"none",cli:{name:"get"}}),de("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.",kc,async(i,n)=>{if(Rr(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,...wr(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 Ch(e){let t=Object.fromEntries(Object.entries(e.params.shape).map(([r,i])=>{let n=i instanceof c.ZodDefault?i.unwrap():i,o=i.description?n.describe(i.description):n;return[r,o.optional()]}));return c.looseObject(t).describe(`Params for ${e.type}`)}function Th(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(Ch),n=c.union([...i,c.looseObject({})]);return c.object({type:c.enum([t,...r]).describe("The report to run"),params:n.optional().describe("The report's params; each report lists its own")})}function ld(e){let{entityService:t,analytics:r}=e,i=r.getDefinitions(),n=i.map((o)=>`${o.type} (${o.description})`).join("; ");return[de("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}.`,Th(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 dd(e){let{jobs:t}=e;return[W("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.",Lc,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 l=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:l},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 Eh(e,t){let{entityCounts:r,daemons:i,endpoints:n,interactions:o,...s}=e,a=n.filter((l)=>t(l.visibility)).sort((l,d)=>l.priority-d.priority).map(({label:l,url:d})=>({label:l,url:d}));if(!t("trusted"))return{...{version:e.version,uptime:e.uptime,backgroundWork:e.backgroundWork},endpoints:a};return{...s,endpoints:a}}function ud(e){return[de("system","status","Get system status including version, background work, and the web surfaces the caller can open, with their paths; trusted callers also get the model and entity totals. Report only the paths it lists; when a surface the user asks about is not listed, say its path was not reported.",c.object({}),async(t,r)=>({success:!0,data:Eh(await e.getAppInfo(),(i)=>e.permissionService.hasPermission(r.userPermissionLevel??"public",i))}),{visibility:"public",sideEffects:"none",cli:{name:"status"}})]}function pd(e){return[...cd(e),...dd(e),...ud(e),...Yl(e),...ld(e)]}function md(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(`
111
+ `:ed}${a.text}`}).join("")}var xh=0.5;function sd(e,t){let r=e??t.limit;return t.maxLimit===void 0?r:Math.min(r,t.maxLimit)}function ad(e,t,r,i){let n=Li(e.entity,r);if(n!==e.entity)return{...e,entity:n,excerpt:n.content};let o=$e(n.content);if(o.length<=i)return{...e,entity:n};let{content:s,...a}=n;return{...e,entity:a,excerpt:od(o,t,i),excerpted:!0}}var wr=(e)=>e==="public"?{publishedOnly:!0}:{};function Ph(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 cd(e){let{entityService:t,logger:r}=e;return[ue("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. When a typed search's results hold that type's entities but not a detail the user asked about, the detail is not saved there: answer from what the results say and name what is missing, rather than searching the same type again with added words or a lower minScore. 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?'.",Ec,async(i,n)=>{Rr(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:sd(i.limit,e.searchBudget),filter:{visibilityScope:o},...wr(o)}})).map((m)=>ad({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??xh,a=await t.search({query:i.query,options:{limit:sd(i.limit,e.searchBudget),...i.scope.kind==="type"&&{types:[i.scope.entityType]},...i.includeUngenerated!==void 0&&{includeUngenerated:i.includeUngenerated},visibilityScope:o,...wr(o)}}),l=a.filter((u)=>u.score>=s),d=l.length===0?Ph(a,s):void 0;return{success:!0,data:{results:l.map((u)=>ad(u,i.query,e.entityRegistry,e.searchBudget.excerptChars)),...d&&{belowThreshold:d}}}},{visibility:"public",sideEffects:"none",cli:{name:"search"}}),ue("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.",Ac,async(i,n)=>{if(Rr(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 _(t,{entityType:i.entityType,identifier:i.id},{visibilityScope:o,logger:r,read:{...wr(o),source:!0}});if(!s.ok)return{success:!1,error:s.error};let a=Li(s.entity,e.entityRegistry);return{success:!0,data:{entity:i.part==="body"?{...a,content:$e(a.content)}:a}}},{visibility:"public",sideEffects:"none",cli:{name:"get"}}),ue("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.",kc,async(i,n)=>{if(Rr(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,...wr(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 Ch(e){let t=Object.fromEntries(Object.entries(e.params.shape).map(([r,i])=>{let n=i instanceof c.ZodDefault?i.unwrap():i,o=i.description?n.describe(i.description):n;return[r,o.optional()]}));return c.looseObject(t).describe(`Params for ${e.type}`)}function Th(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(Ch),n=c.union([...i,c.looseObject({})]);return c.object({type:c.enum([t,...r]).describe("The report to run"),params:n.optional().describe("The report's params; each report lists its own")})}function ld(e){let{entityService:t,analytics:r}=e,i=r.getDefinitions(),n=i.map((o)=>`${o.type} (${o.description})`).join("; ");return[ue("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}.`,Th(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 dd(e){let{jobs:t}=e;return[W("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.",Lc,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 l=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:l},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 Eh(e,t){let{entityCounts:r,daemons:i,endpoints:n,interactions:o,...s}=e,a=n.filter((l)=>t(l.visibility)).sort((l,d)=>l.priority-d.priority).map(({label:l,url:d})=>({label:l,url:d}));if(!t("trusted"))return{...{version:e.version,uptime:e.uptime,backgroundWork:e.backgroundWork},endpoints:a};return{...s,endpoints:a}}function ud(e){return[ue("system","status","Get system status including version, background work, and the web surfaces the caller can open, with their paths; trusted callers also get the model and entity totals. Report only the paths it lists; when a surface the user asks about is not listed, say its path was not reported.",c.object({}),async(t,r)=>({success:!0,data:Eh(await e.getAppInfo(),(i)=>e.permissionService.hasPermission(r.userPermissionLevel??"public",i))}),{visibility:"public",sideEffects:"none",cli:{name:"status"}})]}function pd(e){return[...cd(e),...dd(e),...ud(e),...Yl(e),...ld(e)]}function md(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(`
112
112
  `)}]})},{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 gd(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}`);let o=e.entityRegistry.getEntityTypeConfig(r).binaryStorage==="asset"?await fd(t,n.content,n.metadata):n.content;return{contents:[{uri:`entity://${r}/${i}`,mimeType:"text/markdown",text:o}]}}}]}function hd(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 Ah(e,t){let r=Me(e.permissionService),i=e.entityRegistry.getEntityTypeConfig(t);return["create","update","delete"].every((n)=>r(t,n))&&i.embeddable===!1&&i.fullTextSearchable===!1}function yd(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 without calling any tool to find or read the target; 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().filter((i)=>!Ah(e,i)).map((i)=>`- ${i}: ${e.entityRegistry.getAdapter(i).purpose}`)].join(`
113
- `)}var kh=c.union([c.object({needsConfirmation:c.literal(!0),summary:c.string(),completionSummary:c.string().optional(),preview:c.string(),args:c.record(c.string(),c.unknown())}),c.object({success:c.literal(!0),data:c.object({entityId:c.string(),jobId:c.string().optional()})}),c.object({success:c.literal(!1),error:c.string(),code:c.string().optional()})]);function Sd(e){let[t="",...r]=e.source.entityIds;return{kind:"prompt-from-source",entityType:e.entityType,source:{entityType:e.source.entityType,entityId:t},...r.length>0&&{additionalSourceIds:r},...e.prompt!==void 0&&{prompt:e.prompt}}}var jh=c.object({operation:c.looseObject({kind:c.literal("prompt-from-source"),entityType:c.string(),source:c.looseObject({entityType:c.string(),entityId:c.string()}),additionalSourceIds:c.array(c.string()).optional(),prompt:c.string().optional()})});function Dh(e,t){let r=jh.safeParse(e);if(!r.success)return!1;let{operation:i}=r.data,n=Sd(t),o=[n.source.entityId,...n.additionalSourceIds??[]],s=[i.source.entityId,...i.additionalSourceIds??[]];return i.entityType===n.entityType&&i.source.entityType===n.source.entityType&&i.prompt===n.prompt&&s.length===o.length&&s.every((a,l)=>a===o[l])}function Rd(e,t,r){return bd(t,vd,async(i)=>{let n=e.find(({name:a})=>a==="system_generate");if(!n)return{status:"refused",error:"Generation is unavailable."};if(i.approval&&!Dh(i.approval,i))return{status:"refused",error:"The approval is not for this generation."};let o={interfaceType:i.interfaceType,actor:i.actor,userPermissionLevel:i.userPermissionLevel},s=kh.parse(await n.handler(i.approval??{operation:Sd(i)},o));if("needsConfirmation"in s)return{status:"confirm",summary:s.summary,...s.completionSummary!==void 0&&{completionSummary:s.completionSummary},preview:s.preview,approval:s.args};if(s.success)return{status:"queued",entityId:s.data.entityId,...s.data.jobId!==void 0&&{jobId:s.data.jobId}};return{status:"refused",error:s.error,...s.code!==void 0&&{code:s.code}}},{owner:"system",logger:r})}var Ne="system",Oh=c.object({toolName:c.string(),args:c.unknown(),...wd.partial().shape});function Ir(e,t,r,i,n){for(let o of e)try{t(o)}catch{n.debug(`System ${i} ${r(o)} already registered, skipping`)}}function Id(e,t,r,i){let n=pd(e);Ir(n,(p)=>t.registerTool(Ne,p),(p)=>p.name,"tool",i);let o=r.subscribe(Yt.toolExecute(Ne),async(p)=>{let m=Oh.safeParse(p.payload);if(!m.success)return{success:!1,error:"Invalid system tool execute payload"};let{toolName:f,args:g,interfaceType:h,actor:S,conversationId:b,channelId:y,userPermissionLevel:v}=m.data,R=n.find((z)=>z.name===f);if(!R)return{success:!1,error:`System tool not found: ${f}`};let I={interfaceType:h??"system",actor:S??{kind:"service",serviceId:"system"}};if(b)I.conversationId=b;if(y)I.channelId=y;if(v)I.userPermissionLevel=v;return{success:!0,data:await R.handler(g,I)}});i.debug(`Registered ${n.length} system tools`);let s=md(e);Ir(s,(p)=>t.registerResource(Ne,p),(p)=>p.uri,"resource",i),i.debug(`Registered ${s.length} system resources`);let a=gd(e);Ir(a,(p)=>t.registerResourceTemplate(Ne,p),(p)=>p.uriTemplate,"resource template",i),i.debug(`Registered ${a.length} system resource templates`);let l=hd(e);Ir(l,(p)=>t.registerPrompt(Ne,p),(p)=>p.name,"prompt",i),i.debug(`Registered ${l.length} system prompts`);let d=yd(e);try{t.registerInstructions(Ne,d)}catch{i.debug("System instructions already registered, skipping")}i.debug("Registered system instructions");let u=Rd(n,r,i);return()=>{o(),u()}}function Ed(e){let{services:t,jobs:r,analytics:i,query:n,getAppInfo:o}=e,s=t.jobQueueService,a=t.logger.child("system"),l=Id({entityService:t.entityService,entityRegistry:t.entityRegistry,jobs:{...r,enqueue:xd(s,"system",!1),enqueueBatch:Cd(r,"system"),registerHandler:Td(s,"system"),has:Pd(s)},conversationService:t.conversationService,runtimeUploads:t.runtimeUploadRegistry,attachments:xr(t.attachmentRegistry),logger:a,query:n,getIdentity:()=>t.identityService.getCharacter(),getProfile:()=>t.profileService.getProfile(),getAppInfo:o,searchBudget:nd(t.aiService.getConfig().model),analytics:i,permissionService:t.permissionService},t.mcpService,t.messageBus,a);t.disposables.push(l)}class ln{scope;closePromise=null;closed=!1;constructor(){this.scope=w.runSync(D.make())}buildLayer(e){this.assertOpen();let t=w.runSyncExit(Q.buildWithScope(e,this.scope));if(j.isFailure(t))throw oe.squash(t.cause);return t.value}addFinalizer(e){this.assertOpen(),w.runSync(D.addFinalizer(this.scope,w.promise(async()=>{await e()})))}addSyncFinalizer(e){this.assertOpen(),w.runSync(D.addFinalizer(this.scope,w.sync(()=>{e()})))}async fork(e){if(this.closed)throw Error("Cannot start background work after shell shutdown");await w.runPromise(w.forkIn(e,this.scope))}close(e=j.void){if(this.closePromise)return this.closePromise;if(this.closed)return Promise.resolve();return this.closed=!0,this.closePromise=w.runPromise(D.close(this.scope,e)),this.closePromise}closeSync(e){if(this.closed)return;this.closed=!0,w.runSync(D.close(this.scope,e))}assertOpen(){if(this.closed)throw Error("Cannot register cleanup after shell shutdown")}}class dn{config;services;lifecycle;bootloader;initialized=!1;lifecycleState="constructed";bootMode;bootPromise=null;shutdownPromise=null;analyticsRegistry;bootTime=Date.now();endpointRegistry=new Ai;interactionRegistry=new ki;httpRouteRegistry=tr.createFresh();httpServed;jobs;static createFresh(e,t,r){return new dn(gt(e),t,r)}constructor(e,t,r){this.config=e,this.httpServed=e.http.enabled&&Ae(r?.processRole).serves,this.lifecycle=new ln,Ld(this,()=>this.httpRouteRegistry.getSnapshot());let i=t?.logger??Ee.getInstance(),n=Ut.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=gc(this.services.entityRegistry),this.bootloader=new Ti(this.config,this.services,this.lifecycle,n,r?.processRole,{registerCoreDataSources:()=>Dn(this.services,this.config),finalizeHttpRoutes:()=>{this.httpRouteRegistry.finalize(wc(this.services.pluginManager))},registerSystemCapabilities:()=>Ed({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(j.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 kd.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:Dd(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 be(this.services.messageBus,Od,{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(j.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"),On(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 Ad.parse(await this.generateContent({prompt:e,templateName:Je.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()}canDescribeImages(){return this.services.aiService.canDescribeImages?.()??!1}async describeImage(e,t){return this.services.aiService.describeImage?.(e,t)}getPluginManager(){return this.services.pluginManager}getContentService(){return this.services.contentService}getCallerAuthorizer(){return this.services.callerAuthorizer}getRenderService(){return this.services.renderService}getAttachmentRegistry(){return xr(this.services.attachmentRegistry)}getRuntimeUploadRegistry(){return zd(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(K,ec({config:this.config.http,domain:this.config.siteBaseUrl,logger:t.child(H),messageBus:r,getRoutes:()=>this.httpRouteRegistry.getSnapshot(),getPlugins:()=>[...i.getAllPlugins().values()].map(({plugin:s})=>s),getOperationalInfo:async()=>Md(jd(await this.getAppInfo())),getReadinessData:()=>this.getRuntimeReadiness()}),H),this.lifecycle.addSyncFinalizer(()=>e.abandon(K));let{endpoints:n,interactions:o}=tc(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 Rn({config:this.config,services:this.services,bootTime:this.bootTime,endpoints:()=>this.listEndpoints(),interactions:()=>this.listInteractions()})}getRuntimeReadiness(){return xn(this.services)}}async function Jd(e,t){await ue({label:"entity",config:e,schema:{assets:Bd,entities:Ud,entityMutationReceipts:$d,projectionDirtyInputs:_d,projectionWaves:Fd,projectionIncidents:Nd,projectionWaveInputs:Zd,projectionWaveRules:Hd,projectionRuleMemos:Wd},migrationsFolder:pe(import.meta.url,"entity-service"),authTokenEnv:"DATABASE_AUTH_TOKEN",logger:t,afterMigrate:qd})}async function Kd(e,t){await ue({label:"job-queue",config:e,schema:{jobQueue:Gd,jobWorkerSessions:Qd},migrationsFolder:pe(import.meta.url,"job-queue"),authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",logger:t})}async function eu(e,t){await ue({label:"conversation",config:e,schema:{conversations:Vd,messages:Yd,summaryTracking:Xd},migrationsFolder:pe(import.meta.url,"conversation-service"),authTokenEnv:"CONVERSATION_DATABASE_AUTH_TOKEN",logger:t})}async function tu(e,t){await ue({label:"runtime-state",config:e,schema:{runtimeStateRecords:x},migrationsFolder:pe(import.meta.url,"runtime-state"),authTokenEnv:"RUNTIME_STATE_DATABASE_AUTH_TOKEN",logger:t})}import{mkdir as pn}from"fs/promises";import{isAbsolute as zh}from"path";function ru(e=process.env){return{dataDir:e.XDG_DATA_HOME??"./data",cacheDir:e.XDG_CACHE_HOME??"./cache",distDir:"./dist"}}function iu(e=process.env){let t=e.BRAIN_GIT_BROKER_CHECKOUT;if(!t)return;if(!zh(t))throw Error(`Git broker checkout path must be absolute: ${t}`);return t}function nu(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 ou(e=process.env){return fe(ru(e))}async function su(e=process.env){let t=ru(e);try{await pn(t.dataDir,{recursive:!0}),await pn(t.cacheDir,{recursive:!0}),await pn(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: ${P(r)}`;throw Error(i,{cause:r})}return fe(t)}class Mh{logger;migrations;constructor(e,t){this.logger=e,this.migrations=t??{getStandardConfigWithDirectories:()=>su(),migrateEntities:Jd,migrateJobQueue:Kd,migrateConversations:eu,migrateRuntimeState:tu}}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 mn={kind:"service",serviceId:"brain-cli"},fn=`${mn.kind}:${mn.serviceId}`;function Tj(e="admin"){return{interfaceType:"cli",actor:mn,userPermissionLevel:e}}var kj=c.enum(["eval"]),jj=c.enum(["person","team","organization"]),gn=c.object({provider:c.enum(["hetzner","docker"]).default("hetzner"),serverSize:c.string().default("cx33"),location:c.string().default("fsn1"),domain:c.string().optional(),docker:c.object({enabled:c.boolean().default(!0),image:c.string().optional()}).prefault({}),ports:c.object({default:c.number().default(3333),preview:c.number().default(4321),production:c.number().default(8080)}).prefault({}),cdn:c.object({enabled:c.boolean().default(!1),provider:c.enum(["bunny","none"]).default("none")}).prefault({}),dns:c.object({enabled:c.boolean().default(!1),provider:c.enum(["bunny","none"]).default("none")}).prefault({}),paths:c.object({install:c.string().optional(),data:c.string().optional()}).prefault({})});var Lh=c.object({providerKeys:qe.optional(),model:c.string().optional(),embeddingModel:c.string().optional(),modelRuntimeUrl:c.string().optional(),answerModel:c.string().optional(),visionModel:c.string().optional(),imageModel:c.string().optional(),reasoningEffort:re.optional()}),cu=c.object({name:c.string().default("brain-app"),version:c.string().default("1.0.0"),database:c.string().optional(),ai:Lh.optional(),logLevel:Te.optional(),logFile:c.string().optional(),profileKind:c.string().trim().min(1).optional(),plugins:c.array(ft).default([]),spaces:c.array(c.string()).default([]),identity:au.optional(),agentInstructions:c.array(c.string()).optional(),deployment:gn.prefault({}),http:We.prefault({})});var Uh="NODE_ENV";function Bh(){return process.env[Uh]}function hn(){return Bh()==="production"}function lu(){return!hn()}var $h="startup-check";function _h(){return Object.fromEntries(un.map((e)=>[e,$h]))}function Gj(e){let r={...cu.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 Qj(e,t){let r={plugins:e.plugins??[],...e.shellConfig};return Fh(r),Nh(e,r),Zh(e,r,t),Hh(e,r),Wh(e,r),qh(e,r),Jh(e,r),Gh(e,r),Kh(e,r),Qh(e,r),r}function Fh(e){let t=ou();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??=nu(),e.gitBrokerCheckout??=iu()}function Nh(e,t){if(e.database)t.database={url:e.database};if(e.profileKind)t.profileKind=e.profileKind;t.features={}}function Zh(e,t,r){let i=r?.mode==="startup-check",{providerKeys:n,...o}=F(e.ai??{});if(!n&&Object.keys(o).length===0&&!i)return;t.ai={...t.ai,providerKeys:{...i&&_h(),...t.ai?.providerKeys,...n},...o}}function Hh(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 Wh(e,t){let r=e.permissions?.rules??[];t.permissions={...e.permissions,rules:r.some((i)=>i.pattern===fn)?r:[{pattern:fn,level:"admin"},...r]}}function qh(e,t){if(e.spaces)t.spaces=e.spaces}function Jh(e,t){if(e.identity)t.identity=e.identity}function Gh(e,t){if(e.agentInstructions)t.agentInstructions=e.agentInstructions}function Qh(e,t){t.http??={...F(e.http),port:e.deployment.ports.production}}function Kh(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=lu(),t.production=hn()}
114
- export{fe as P,We as Q,Te as R,gt as S,O as T,np as U,op as V,sp as W,pp as X,eo as Y,fp as Z,gp as _,hp as $,yp as aa,vp as ba,bp as ca,Sp as da,Yr as ea,oa as fa,Si as ga,Cc as ha,Mg as ia,wl as ja,$g as ka,xl as la,at as ma,_g as na,we as oa,Gi as pa,Qi as qa,Ki as ra,Ng as sa,qg as ta,Jg as ua,YT as va,Dl as wa,Ol as xa,Kg as ya,Vg as za,Yg as Aa,Xg as Ba,on as Ca,eh as Da,th as Ea,oh as Fa,dn as Ga,Jd as Ha,Kd as Ia,eu as Ja,tu as Ka,Mh as La,Tj as Ma,jj as Na,Gj as Oa,Qj as Pa};
113
+ `)}var kh=c.union([c.object({needsConfirmation:c.literal(!0),summary:c.string(),completionSummary:c.string().optional(),preview:c.string(),args:c.record(c.string(),c.unknown())}),c.object({success:c.literal(!0),data:c.object({entityId:c.string(),jobId:c.string().optional()})}),c.object({success:c.literal(!1),error:c.string(),code:c.string().optional()})]);function Sd(e){let[t="",...r]=e.source.entityIds;return{kind:"prompt-from-source",entityType:e.entityType,source:{entityType:e.source.entityType,entityId:t},...r.length>0&&{additionalSourceIds:r},...e.prompt!==void 0&&{prompt:e.prompt}}}var jh=c.object({operation:c.looseObject({kind:c.literal("prompt-from-source"),entityType:c.string(),source:c.looseObject({entityType:c.string(),entityId:c.string()}),additionalSourceIds:c.array(c.string()).optional(),prompt:c.string().optional()})});function Dh(e,t){let r=jh.safeParse(e);if(!r.success)return!1;let{operation:i}=r.data,n=Sd(t),o=[n.source.entityId,...n.additionalSourceIds??[]],s=[i.source.entityId,...i.additionalSourceIds??[]];return i.entityType===n.entityType&&i.source.entityType===n.source.entityType&&i.prompt===n.prompt&&s.length===o.length&&s.every((a,l)=>a===o[l])}function Rd(e,t,r){return bd(t,vd,async(i)=>{let n=e.find(({name:a})=>a==="system_generate");if(!n)return{status:"refused",error:"Generation is unavailable."};if(i.approval&&!Dh(i.approval,i))return{status:"refused",error:"The approval is not for this generation."};let o={interfaceType:i.interfaceType,actor:i.actor,userPermissionLevel:i.userPermissionLevel},s=kh.parse(await n.handler(i.approval??{operation:Sd(i)},o));if("needsConfirmation"in s)return{status:"confirm",summary:s.summary,...s.completionSummary!==void 0&&{completionSummary:s.completionSummary},preview:s.preview,approval:s.args};if(s.success)return{status:"queued",entityId:s.data.entityId,...s.data.jobId!==void 0&&{jobId:s.data.jobId}};return{status:"refused",error:s.error,...s.code!==void 0&&{code:s.code}}},{owner:"system",logger:r})}var Ne="system",Oh=c.object({toolName:c.string(),args:c.unknown(),...wd.partial().shape});function Ir(e,t,r,i,n){for(let o of e)try{t(o)}catch{n.debug(`System ${i} ${r(o)} already registered, skipping`)}}function Id(e,t,r,i){let n=pd(e);Ir(n,(p)=>t.registerTool(Ne,p),(p)=>p.name,"tool",i);let o=r.subscribe(Yt.toolExecute(Ne),async(p)=>{let m=Oh.safeParse(p.payload);if(!m.success)return{success:!1,error:"Invalid system tool execute payload"};let{toolName:f,args:g,interfaceType:h,actor:S,conversationId:b,channelId:y,userPermissionLevel:v}=m.data,R=n.find((z)=>z.name===f);if(!R)return{success:!1,error:`System tool not found: ${f}`};let I={interfaceType:h??"system",actor:S??{kind:"service",serviceId:"system"}};if(b)I.conversationId=b;if(y)I.channelId=y;if(v)I.userPermissionLevel=v;return{success:!0,data:await R.handler(g,I)}});i.debug(`Registered ${n.length} system tools`);let s=md(e);Ir(s,(p)=>t.registerResource(Ne,p),(p)=>p.uri,"resource",i),i.debug(`Registered ${s.length} system resources`);let a=gd(e);Ir(a,(p)=>t.registerResourceTemplate(Ne,p),(p)=>p.uriTemplate,"resource template",i),i.debug(`Registered ${a.length} system resource templates`);let l=hd(e);Ir(l,(p)=>t.registerPrompt(Ne,p),(p)=>p.name,"prompt",i),i.debug(`Registered ${l.length} system prompts`);let d=yd(e);try{t.registerInstructions(Ne,d)}catch{i.debug("System instructions already registered, skipping")}i.debug("Registered system instructions");let u=Rd(n,r,i);return()=>{o(),u()}}function Ed(e){let{services:t,jobs:r,analytics:i,query:n,getAppInfo:o}=e,s=t.jobQueueService,a=t.logger.child("system"),l=Id({entityService:t.entityService,entityRegistry:t.entityRegistry,jobs:{...r,enqueue:xd(s,"system",!1),enqueueBatch:Cd(r,"system"),registerHandler:Td(s,"system"),has:Pd(s)},conversationService:t.conversationService,runtimeUploads:t.runtimeUploadRegistry,attachments:xr(t.attachmentRegistry),logger:a,query:n,getIdentity:()=>t.identityService.getCharacter(),getProfile:()=>t.profileService.getProfile(),getAppInfo:o,searchBudget:nd(t.aiService.getConfig().model),analytics:i,permissionService:t.permissionService},t.mcpService,t.messageBus,a);t.disposables.push(l)}class ln{scope;closePromise=null;closed=!1;constructor(){this.scope=w.runSync(D.make())}buildLayer(e){this.assertOpen();let t=w.runSyncExit(Q.buildWithScope(e,this.scope));if(j.isFailure(t))throw oe.squash(t.cause);return t.value}addFinalizer(e){this.assertOpen(),w.runSync(D.addFinalizer(this.scope,w.promise(async()=>{await e()})))}addSyncFinalizer(e){this.assertOpen(),w.runSync(D.addFinalizer(this.scope,w.sync(()=>{e()})))}async fork(e){if(this.closed)throw Error("Cannot start background work after shell shutdown");await w.runPromise(w.forkIn(e,this.scope))}close(e=j.void){if(this.closePromise)return this.closePromise;if(this.closed)return Promise.resolve();return this.closed=!0,this.closePromise=w.runPromise(D.close(this.scope,e)),this.closePromise}closeSync(e){if(this.closed)return;this.closed=!0,w.runSync(D.close(this.scope,e))}assertOpen(){if(this.closed)throw Error("Cannot register cleanup after shell shutdown")}}class dn{config;services;lifecycle;bootloader;initialized=!1;lifecycleState="constructed";bootMode;bootPromise=null;shutdownPromise=null;analyticsRegistry;bootTime=Date.now();endpointRegistry=new Ai;interactionRegistry=new ki;httpRouteRegistry=tr.createFresh();httpServed;jobs;static createFresh(e,t,r){return new dn(gt(e),t,r)}constructor(e,t,r){this.config=e,this.httpServed=e.http.enabled&&Ae(r?.processRole).serves,this.lifecycle=new ln,Ld(this,()=>this.httpRouteRegistry.getSnapshot());let i=t?.logger??Ee.getInstance(),n=Ut.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=gc(this.services.entityRegistry),this.bootloader=new Ti(this.config,this.services,this.lifecycle,n,r?.processRole,{registerCoreDataSources:()=>Dn(this.services,this.config),finalizeHttpRoutes:()=>{this.httpRouteRegistry.finalize(wc(this.services.pluginManager))},registerSystemCapabilities:()=>Ed({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(j.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 kd.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:Dd(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 Se(this.services.messageBus,Od,{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(j.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"),On(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 Ad.parse(await this.generateContent({prompt:e,templateName:Je.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()}canDescribeImages(){return this.services.aiService.canDescribeImages?.()??!1}async describeImage(e,t){return this.services.aiService.describeImage?.(e,t)}getPluginManager(){return this.services.pluginManager}getContentService(){return this.services.contentService}getCallerAuthorizer(){return this.services.callerAuthorizer}getRenderService(){return this.services.renderService}getAttachmentRegistry(){return xr(this.services.attachmentRegistry)}getRuntimeUploadRegistry(){return zd(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(K,ec({config:this.config.http,domain:this.config.siteBaseUrl,logger:t.child(H),messageBus:r,getRoutes:()=>this.httpRouteRegistry.getSnapshot(),getPlugins:()=>[...i.getAllPlugins().values()].map(({plugin:s})=>s),getOperationalInfo:async()=>Md(jd(await this.getAppInfo())),getReadinessData:()=>this.getRuntimeReadiness()}),H),this.lifecycle.addSyncFinalizer(()=>e.abandon(K));let{endpoints:n,interactions:o}=tc(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 Rn({config:this.config,services:this.services,bootTime:this.bootTime,endpoints:()=>this.listEndpoints(),interactions:()=>this.listInteractions()})}getRuntimeReadiness(){return xn(this.services)}}async function Jd(e,t){await pe({label:"entity",config:e,schema:{assets:Bd,entities:Ud,entityMutationReceipts:$d,projectionDirtyInputs:_d,projectionWaves:Fd,projectionIncidents:Nd,projectionWaveInputs:Zd,projectionWaveRules:Hd,projectionRuleMemos:Wd},migrationsFolder:me(import.meta.url,"entity-service"),authTokenEnv:"DATABASE_AUTH_TOKEN",logger:t,afterMigrate:qd})}async function Kd(e,t){await pe({label:"job-queue",config:e,schema:{jobQueue:Gd,jobWorkerSessions:Qd},migrationsFolder:me(import.meta.url,"job-queue"),authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",logger:t})}async function eu(e,t){await pe({label:"conversation",config:e,schema:{conversations:Vd,messages:Yd,summaryTracking:Xd},migrationsFolder:me(import.meta.url,"conversation-service"),authTokenEnv:"CONVERSATION_DATABASE_AUTH_TOKEN",logger:t})}async function tu(e,t){await pe({label:"runtime-state",config:e,schema:{runtimeStateRecords:x},migrationsFolder:me(import.meta.url,"runtime-state"),authTokenEnv:"RUNTIME_STATE_DATABASE_AUTH_TOKEN",logger:t})}import{mkdir as pn}from"fs/promises";import{isAbsolute as zh}from"path";function ru(e=process.env){return{dataDir:e.XDG_DATA_HOME??"./data",cacheDir:e.XDG_CACHE_HOME??"./cache",distDir:"./dist"}}function iu(e=process.env){let t=e.BRAIN_GIT_BROKER_CHECKOUT;if(!t)return;if(!zh(t))throw Error(`Git broker checkout path must be absolute: ${t}`);return t}function nu(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 ou(e=process.env){return ge(ru(e))}async function su(e=process.env){let t=ru(e);try{await pn(t.dataDir,{recursive:!0}),await pn(t.cacheDir,{recursive:!0}),await pn(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: ${P(r)}`;throw Error(i,{cause:r})}return ge(t)}class Mh{logger;migrations;constructor(e,t){this.logger=e,this.migrations=t??{getStandardConfigWithDirectories:()=>su(),migrateEntities:Jd,migrateJobQueue:Kd,migrateConversations:eu,migrateRuntimeState:tu}}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 mn={kind:"service",serviceId:"brain-cli"},fn=`${mn.kind}:${mn.serviceId}`;function Tj(e="admin"){return{interfaceType:"cli",actor:mn,userPermissionLevel:e}}var kj=c.enum(["eval"]),jj=c.enum(["person","team","organization"]),gn=c.object({provider:c.enum(["hetzner","docker"]).default("hetzner"),serverSize:c.string().default("cx33"),location:c.string().default("fsn1"),domain:c.string().optional(),docker:c.object({enabled:c.boolean().default(!0),image:c.string().optional()}).prefault({}),ports:c.object({default:c.number().default(3333),preview:c.number().default(4321),production:c.number().default(8080)}).prefault({}),cdn:c.object({enabled:c.boolean().default(!1),provider:c.enum(["bunny","none"]).default("none")}).prefault({}),dns:c.object({enabled:c.boolean().default(!1),provider:c.enum(["bunny","none"]).default("none")}).prefault({}),paths:c.object({install:c.string().optional(),data:c.string().optional()}).prefault({})});var Lh=c.object({providerKeys:qe.optional(),model:c.string().optional(),embeddingModel:c.string().optional(),modelRuntimeUrl:c.string().optional(),answerModel:c.string().optional(),visionModel:c.string().optional(),imageModel:c.string().optional(),reasoningEffort:re.optional()}),cu=c.object({name:c.string().default("brain-app"),version:c.string().default("1.0.0"),database:c.string().optional(),ai:Lh.optional(),logLevel:Te.optional(),logFile:c.string().optional(),profileKind:c.string().trim().min(1).optional(),plugins:c.array(ft).default([]),spaces:c.array(c.string()).default([]),identity:au.optional(),agentInstructions:c.array(c.string()).optional(),deployment:gn.prefault({}),http:We.prefault({})});var Uh="NODE_ENV";function Bh(){return process.env[Uh]}function hn(){return Bh()==="production"}function lu(){return!hn()}var $h="startup-check";function _h(){return Object.fromEntries(un.map((e)=>[e,$h]))}function Gj(e){let r={...cu.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 Qj(e,t){let r={plugins:e.plugins??[],...e.shellConfig};return Fh(r),Nh(e,r),Zh(e,r,t),Hh(e,r),Wh(e,r),qh(e,r),Jh(e,r),Gh(e,r),Kh(e,r),Qh(e,r),r}function Fh(e){let t=ou();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??=nu(),e.gitBrokerCheckout??=iu()}function Nh(e,t){if(e.database)t.database={url:e.database};if(e.profileKind)t.profileKind=e.profileKind;t.features={}}function Zh(e,t,r){let i=r?.mode==="startup-check",{providerKeys:n,...o}=F(e.ai??{});if(!n&&Object.keys(o).length===0&&!i)return;t.ai={...t.ai,providerKeys:{...i&&_h(),...t.ai?.providerKeys,...n},...o}}function Hh(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 Wh(e,t){let r=e.permissions?.rules??[];t.permissions={...e.permissions,rules:r.some((i)=>i.pattern===fn)?r:[{pattern:fn,level:"admin"},...r]}}function qh(e,t){if(e.spaces)t.spaces=e.spaces}function Jh(e,t){if(e.identity)t.identity=e.identity}function Gh(e,t){if(e.agentInstructions)t.agentInstructions=e.agentInstructions}function Qh(e,t){t.http??={...F(e.http),port:e.deployment.ports.production}}function Kh(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=lu(),t.production=hn()}
114
+ export{ge as P,We as Q,Te as R,gt as S,O as T,np as U,op as V,sp as W,pp as X,eo as Y,fp as Z,gp as _,hp as $,yp as aa,vp as ba,bp as ca,Sp as da,Yr as ea,oa as fa,Si as ga,Cc as ha,Mg as ia,wl as ja,$g as ka,xl as la,at as ma,_g as na,Ie as oa,Gi as pa,Qi as qa,Ki as ra,Ng as sa,qg as ta,Jg as ua,YT as va,Dl as wa,Ol as xa,Kg as ya,Vg as za,Yg as Aa,Xg as Ba,on as Ca,eh as Da,th as Ea,oh as Fa,dn as Ga,Jd as Ha,Kd as Ia,eu as Ja,tu as Ka,Mh as La,Tj as Ma,jj as Na,Gj as Oa,Qj as Pa};
115
115
 
116
- //# debugId=392537931F4AD3B764756E2164756E21
117
- //# sourceMappingURL=index-hms2d331.js.map
116
+ //# debugId=F02EBEFB9A3832FF64756E2164756E21
117
+ //# sourceMappingURL=index-7cfgdh89.js.map