@rizom/brain 0.2.0-alpha.718 → 0.2.0-alpha.719

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 Ms,Ra as Ls}from"./index-6hdrx8va.js";import{$a as ct,$f as Yc,$h as kr,Ad as nl,Af as Bd,Be as io,Cb as vo,Cd as Dl,Ce as ys,Cg as wr,Db as Co,Dd as ms,De as Tn,Dg as Ps,Ee as vs,Eg as xe,Fb as le,Fd as Y,Ff as tr,Gb as de,Gc as fd,Gd as Ni,Ge as Ks,Gf as Wc,Gg as bd,Gj as _s,Hb as Id,Hc as Vs,He as Vr,Hf as oo,Hg as Cs,Hj as Wo,Ib as Pd,Ic as mo,If as qd,Ig as yc,Ii as gc,Jb as Cd,Jg as Ja,Ji as fc,Kb as xd,Ke as zd,Kg as wi,Ki as is,Kj as Zs,Lb as Td,Lc as ao,Le as Od,Li as dt,Lj as qo,Mb as Ed,Me as Qo,Mj as zs,Nb as Ad,Ne as Ko,Ni as Sd,Nj as Jo,Ob as kd,Oe as Vo,Oi as js,Pb as Dd,Qb as lo,Qe as Yo,Rb as uo,Re as ld,Sb as po,Se as dd,Te as ud,Ub as jt,Uc as ps,Ue as pd,Uh as Be,Uj as Fs,Vb as us,Ve as hd,Vf as En,Vh as cn,Vj as Rd,Wa as Rl,Wb as yt,We as Nl,Wf as pt,Xa as rt,Xb as Fe,Xf as ic,Xh as In,Xj as Os,Yb as Te,Yf as yd,Yh as me,Yj as lc,Zb as wc,Zd as H,Zh as Pn,Zj as Kt,_a as Xi,_b as kl,_d as Ys,_f as Zi,_h as Cn,ab as he,ac as A,ag as Xc,ai as Ts,bb as Ro,bc as ur,bg as bs,bi as xn,cb as O,cc as Yr,cg as Ss,dc as dl,dg as Rs,eb as oe,ec as Lo,fc as Uo,gb as wo,gc as Bo,ic as Mr,ii as Es,jc as Lr,ji as As,ki as zc,li as ks,mi as _o,ni as Ds,ob as Io,pc as pr,pi as Do,qc as Vc,qg as ws,qi as Zo,rd as hr,ri as Fo,sg as Is,si as No,tb as Hr,tg as Ne,ti as Ho,ub as wt,ug as nc,vb as fo,vd as Cl,vg as oc,wb as ho,we as Va,xd as Bs,xe as ft,xg as sc,yb as yo,yf as Ld,yg as vd,zb as wd,zd as $s,zf as Ud,zg as $o}from"./index-4am2hnt4.js";import{Al as Mo,An as ee,Bn as Q,Dl as to,Em as tc,Hm as qt,In as gs,On as fs,Pn as hs,Ql as ie,Rn as ad,Tl as we,Vl as P,Wl as Ze,Wn as xs,Xn as Na,Ym as gd,_n as ce,al as Ga,an as os,bl as W,bm as ro,co as V,fk as vl,gk as bl,hk as te,jk as vr,kk as dr,lk as it,nm as ge,pm as Tt,sn as Wa,um as Qs,un as qa,vm as Gt,zl as Oo}from"./index-vs4fspgp.js";import{do as We,fo as Pe}from"./index-ts454h5y.js";import{Mv as b,Ns as j,Vs as J,aw as re,cw as Qt,dw as rc,gq as x,gw as ac,ks as ne,ms as ds,ys as D}from"./index-yameqcj7.js";import{yx as c}from"./index-1drsa3aa.js";function Ar(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 Le(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=Ar(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 vn(e){let{config:t,services:r,bootTime:i,endpoints:n,interactions:o}=e,[s,a,l,d,u]=await Promise.all([r.entityService.getEntityCounts(ct("runtime app info reports operator-facing aggregate status")),r.entityService.countEmbeddings(),r.daemonRegistry.getStatuses(),r.jobQueueService.getDiagnostics(),r.legacyBinaryLedger.list()]),p=s.reduce((m,g)=>m+g.count,0);return{model:t.name||"brain-app",version:t.version||"1.0.0",uptime:Math.floor((Date.now()-i)/1000),entities:p,entityCounts:s,embeddings:a,backgroundWork:Le(d,r.jobQueueService.getExecutionRegistrations()),legacyBinaryContent:u,ai:{model:t.ai.model,embeddingModel:r.embeddingService.identity.model},daemons:l,endpoints:n(),interactions:o()}}import{readdir as bn,readFile as pu}from"fs/promises";var mu=10;async function gu(e="/proc"){let t=null;try{t=(await bn(`${e}/self/fd`)).length}catch{}try{let i=(await bn(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 pu(`${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 Sn(e,t,r){return t.status==="fulfilled"?{name:e,status:"healthy",message:r}:{name:e,status:"unhealthy",message:P(t.reason)}}function fu(e){if(!e)return{name:"job-worker",status:"degraded",message:"Worker session state is unavailable"};let t=e.workerSessions,r=Le(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 hu(e){if(!e)return{name:"job-queue-progress",status:"degraded",message:"Queue progress state is unavailable"};let t=Le(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 yu(e,t){if(!e||!t)return{name:"job-execution-inventory",status:"degraded",message:"Job execution inventory is unavailable"};let r=Ar(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 vu(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 bu(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 Su(e){let t=e.entityService.getProjectionStore(),[r,i,n]=await Promise.all([t.getActiveWave(),t.getUnresolvedProjectionIncidentDiagnostics(mu),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 Ru(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 wu(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 Rn(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(ct("runtime readiness database probe")),e.jobQueueService.getDiagnostics(t),Promise.resolve(e.jobQueueService.getExecutionRegistrations()),e.daemonRegistry.getStatuses(),(e.readProcessSignals??gu)(),e.projectionRuntimeSupervisor.getDiagnostics(),Su(e),e.operationalHealthRegistry.getChecks()]),p=n.status==="fulfilled"?n.value:null,m=o.status==="fulfilled"?o.value??null:null,g=s.status==="fulfilled"?s.value:[],f=a.status==="fulfilled"?a.value:{fileDescriptors:null,processCount:null,zombieCount:null},h=l.status==="fulfilled"?l.value:{status:"unhealthy",initialized:!1,trackedRoots:0,openCircuits:[]},v=[Sn("entity-database",i,"Entity database is accessible"),Sn("job-queue-database",n,"Job queue database is accessible"),fu(p),hu(p),yu(p,m),vu(p),l.status==="fulfilled"?bu(h):{name:"projection-circuits",status:"degraded",message:P(l.reason)},d.status==="fulfilled"?Ru(d.value):{name:"projection-waves",status:"degraded",message:P(d.reason)},s.status==="fulfilled"?wu(g):{name:"daemons",status:"degraded",message:P(s.reason)}],y=u.status==="fulfilled"?u.value:[{name:"plugin-operational-health",status:"degraded",message:"Plugin operational health is unavailable"}],S=[...v,...y];return{status:v.some((R)=>R.status==="unhealthy")?"not_ready":"ready",operationalStatus:S.some((R)=>R.status!=="healthy")?"degraded":"operational",checkedAt:new Date(t).toISOString(),checks:S,resources:{memory:{rssBytes:r.rss,heapUsedBytes:r.heapUsed,heapTotalBytes:r.heapTotal},fileDescriptors:f.fileDescriptors,processes:{total:f.processCount,zombies:f.zombieCount},queue:p,projection:{initialized:h.initialized,trackedRoots:h.trackedRoots,openCircuits:h.openCircuits},worker:p?.workerSessions??{total:0,active:0,stale:0,latestHeartbeatAgeMs:null}}}}function wn(){return{dataDir:"./data",cacheDir:"./cache",distDir:"./dist"}}function pe(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 Ue=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")}),lt=Ue.extend({enabled:c.boolean().default(!1),preview:c.boolean().default(!0),port:c.number().default(8080).describe("Port of the production listener")});var Dr=wn(),Iu=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 jr(){return pe(Dr)}var Ie=c.enum(["debug","info","warn","error"]);var zr=c.object({name:c.string().default("brain-app"),version:c.string().default("1.0.0"),database:we,jobQueueDatabase:we,jobQueue:c.object({workerConcurrency:c.number().int().min(1).max(32).default(4)}).prefault({}),conversationDatabase:we,runtimeStateDatabase:we,embeddingDatabase:we,ai:c.object({providerKeys:Be.default({}),model:c.string().refine(In,{error:(e)=>`Unsupported model "${String(e.input)}"`}),embeddingModel:c.string().refine((e)=>kr(e)!==void 0,{error:(e)=>xn(String(e.input))}).default(Cn),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:ee.optional()}).superRefine((e,t)=>{if(e.answerModel&&me(e.answerModel)!=="local")t.addIssue({code:"custom",path:["answerModel"],message:`answerModel must be a local: model, not ${e.answerModel}`});if(e.visionModel&&me(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=[...me(e.model)==="local"?[e.model]:[],...[e.answerModel,e.visionModel].filter((i)=>i!==void 0&&me(i)==="local"),...e.imageModel&&Pn(e.imageModel).provider==="local"?[e.imageModel]:[],...kr(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:Ie.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(dt).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(),Iu).optional(),profileKind:c.string().trim().min(1).optional(),http:lt.prefault({})});function ut(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,...g}=zr.parse({...jr(),...W(p),ai:W({...a}),logging:W({...l}),embedding:W({...d}),jobQueue:W({...u}),plugins:[]});return{...g,plugins:t,permissions:r,...W({entityDisplay:m,identity:i,profile:n,agentInstructions:o,evalHandlerRegistry:s})}}var M={NOTE:"note",BRAIN_CHARACTER:"brain-character",ANCHOR_PROFILE:"anchor-profile"},$e={KNOWLEDGE_QUERY:"shell:knowledge-query",BASE_ENTITY_DISPLAY:"shell:base-entity-display",CONTENT_GENERATION:"shell:content-generation"},Or={ENTITIES:"shell:entities"};var Pu=Tn.extend({templateName:c.string()}),Cu=c.object({slug:c.string()}),xu="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.",Tu="Generate the content described in your instructions.";function Eu(e){return e instanceof c.ZodType}function Au(e){if(!e)return;return e.replace(/^https?:\/\//,"").replace(/\/$/,"")}class mt{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=Au(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=Pu.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 En((v,y)=>i.getEntity(v,y),n.templateName,o.basePrompt):await pt(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),g=i?await this.readIdentities(i,n.representedIdentity):void 0,f=this.buildSystemPrompt(s,n,g);if(!Eu(o.schema))throw Error(`Template ${o.name} cannot be used for AI generation: schema is not an AI generation schema`);r?.throwIfAborted();let h=await this.aiService.generateObject(f,m,o.schema,r);return r?.throwIfAborted(),t.parse(h.object)}async readIdentities(e,t){let r=async(o)=>(await e.getEntity(o,o))?.content??"",[i,n]=await Promise.all([t!=="none"?r(M.BRAIN_CHARACTER):"",t===void 0||t==="anchor"?r(M.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",xu,"");return i.push("# Instructions",e),i.join(`
2
+ import{Qa as Ms,Ra as Ls}from"./index-6hdrx8va.js";import{$a as ct,$f as Yc,$h as kr,Ad as nl,Af as Bd,Be as io,Cb as vo,Cd as Dl,Ce as ys,Cg as wr,Db as Co,Dd as ms,De as Tn,Dg as Ps,Ee as vs,Eg as xe,Fb as le,Fd as X,Ff as tr,Gb as de,Gc as fd,Gd as Ni,Ge as Ks,Gf as Wc,Gg as bd,Gj as _s,Hb as Id,Hc as Vs,He as Vr,Hf as oo,Hg as Cs,Hj as Wo,Ib as Pd,Ic as mo,If as qd,Ig as yc,Ii as gc,Jb as Cd,Jg as Ja,Ji as fc,Kb as xd,Ke as zd,Kg as wi,Ki as is,Kj as Zs,Lb as Td,Lc as ao,Le as Od,Li as dt,Lj as qo,Mb as Ed,Me as Qo,Mj as zs,Nb as Ad,Ne as Ko,Ni as Sd,Nj as Jo,Ob as kd,Oe as Vo,Oi as js,Pb as Dd,Qb as lo,Qe as Yo,Rb as uo,Re as ld,Sb as po,Se as dd,Te as ud,Ub as jt,Uc as ps,Ue as pd,Uh as Be,Uj as Fs,Vb as us,Ve as hd,Vf as En,Vh as cn,Vj as Rd,Wa as Rl,Wb as yt,We as Nl,Wf as pt,Xa as rt,Xb as Fe,Xf as ic,Xh as In,Xj as Os,Yb as Te,Yf as yd,Yh as me,Yj as lc,Zb as wc,Zd as H,Zh as Pn,Zj as Kt,_a as Xi,_b as kl,_d as Ys,_f as Zi,_h as Cn,ab as he,ac as A,ag as Xc,ai as Ts,bb as Ro,bc as ur,bg as bs,bi as xn,cb as O,cc as Yr,cg as Ss,dc as dl,dg as Rs,eb as oe,ec as Lo,fc as Uo,gb as wo,gc as Bo,ic as Mr,ii as Es,jc as Lr,ji as As,ki as zc,li as ks,mi as _o,ni as Ds,ob as Io,pc as pr,pi as Do,qc as Vc,qg as ws,qi as Zo,rd as hr,ri as Fo,sg as Is,si as No,tb as Hr,tg as Ne,ti as Ho,ub as wt,ug as nc,vb as fo,vd as Cl,vg as oc,wb as ho,we as Va,xd as Bs,xe as ft,xg as sc,yb as yo,yf as Ld,yg as vd,zb as wd,zd as $s,zf as Ud,zg as $o}from"./index-4am2hnt4.js";import{Al as Mo,An as te,Bn as K,Dl as to,Em as tc,Hm as qt,In as gs,On as fs,Pn as hs,Ql as J,Rn as ad,Tl as we,Vl as P,Wl as Ze,Wn as xs,Xn as Na,Ym as gd,_n as ce,al as Ga,an as os,bl as W,bm as ro,co as Y,fk as vl,gk as bl,hk as re,jk as vr,kk as dr,lk as it,nm as ge,pm as Tt,sn as Wa,um as Qs,un as qa,vm as Gt,zl as Oo}from"./index-vs4fspgp.js";import{do as We,fo as Pe}from"./index-ts454h5y.js";import{Mv as b,Ns as j,Vs as G,aw as ie,cw as Qt,dw as rc,gq as x,gw as ac,ks as ne,ms as ds,ys as D}from"./index-yameqcj7.js";import{yx as c}from"./index-1drsa3aa.js";function Ar(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 Le(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=Ar(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 vn(e){let{config:t,services:r,bootTime:i,endpoints:n,interactions:o}=e,[s,a,l,d,u]=await Promise.all([r.entityService.getEntityCounts(ct("runtime app info reports operator-facing aggregate status")),r.entityService.countEmbeddings(),r.daemonRegistry.getStatuses(),r.jobQueueService.getDiagnostics(),r.legacyBinaryLedger.list()]),p=s.reduce((m,g)=>m+g.count,0);return{model:t.name||"brain-app",version:t.version||"1.0.0",uptime:Math.floor((Date.now()-i)/1000),entities:p,entityCounts:s,embeddings:a,backgroundWork:Le(d,r.jobQueueService.getExecutionRegistrations()),legacyBinaryContent:u,ai:{model:t.ai.model,embeddingModel:r.embeddingService.identity.model},daemons:l,endpoints:n(),interactions:o()}}import{readdir as bn,readFile as pu}from"fs/promises";var mu=10;async function gu(e="/proc"){let t=null;try{t=(await bn(`${e}/self/fd`)).length}catch{}try{let i=(await bn(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 pu(`${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 Sn(e,t,r){return t.status==="fulfilled"?{name:e,status:"healthy",message:r}:{name:e,status:"unhealthy",message:P(t.reason)}}function fu(e){if(!e)return{name:"job-worker",status:"degraded",message:"Worker session state is unavailable"};let t=e.workerSessions,r=Le(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 hu(e){if(!e)return{name:"job-queue-progress",status:"degraded",message:"Queue progress state is unavailable"};let t=Le(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 yu(e,t){if(!e||!t)return{name:"job-execution-inventory",status:"degraded",message:"Job execution inventory is unavailable"};let r=Ar(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 vu(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 bu(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 Su(e){let t=e.entityService.getProjectionStore(),[r,i,n]=await Promise.all([t.getActiveWave(),t.getUnresolvedProjectionIncidentDiagnostics(mu),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 Ru(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 wu(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 Rn(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(ct("runtime readiness database probe")),e.jobQueueService.getDiagnostics(t),Promise.resolve(e.jobQueueService.getExecutionRegistrations()),e.daemonRegistry.getStatuses(),(e.readProcessSignals??gu)(),e.projectionRuntimeSupervisor.getDiagnostics(),Su(e),e.operationalHealthRegistry.getChecks()]),p=n.status==="fulfilled"?n.value:null,m=o.status==="fulfilled"?o.value??null:null,g=s.status==="fulfilled"?s.value:[],f=a.status==="fulfilled"?a.value:{fileDescriptors:null,processCount:null,zombieCount:null},h=l.status==="fulfilled"?l.value:{status:"unhealthy",initialized:!1,trackedRoots:0,openCircuits:[]},v=[Sn("entity-database",i,"Entity database is accessible"),Sn("job-queue-database",n,"Job queue database is accessible"),fu(p),hu(p),yu(p,m),vu(p),l.status==="fulfilled"?bu(h):{name:"projection-circuits",status:"degraded",message:P(l.reason)},d.status==="fulfilled"?Ru(d.value):{name:"projection-waves",status:"degraded",message:P(d.reason)},s.status==="fulfilled"?wu(g):{name:"daemons",status:"degraded",message:P(s.reason)}],y=u.status==="fulfilled"?u.value:[{name:"plugin-operational-health",status:"degraded",message:"Plugin operational health is unavailable"}],S=[...v,...y];return{status:v.some((R)=>R.status==="unhealthy")?"not_ready":"ready",operationalStatus:S.some((R)=>R.status!=="healthy")?"degraded":"operational",checkedAt:new Date(t).toISOString(),checks:S,resources:{memory:{rssBytes:r.rss,heapUsedBytes:r.heapUsed,heapTotalBytes:r.heapTotal},fileDescriptors:f.fileDescriptors,processes:{total:f.processCount,zombies:f.zombieCount},queue:p,projection:{initialized:h.initialized,trackedRoots:h.trackedRoots,openCircuits:h.openCircuits},worker:p?.workerSessions??{total:0,active:0,stale:0,latestHeartbeatAgeMs:null}}}}function wn(){return{dataDir:"./data",cacheDir:"./cache",distDir:"./dist"}}function pe(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 Ue=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")}),lt=Ue.extend({enabled:c.boolean().default(!1),preview:c.boolean().default(!0),port:c.number().default(8080).describe("Port of the production listener")});var Dr=wn(),Iu=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 jr(){return pe(Dr)}var Ie=c.enum(["debug","info","warn","error"]);var zr=c.object({name:c.string().default("brain-app"),version:c.string().default("1.0.0"),database:we,jobQueueDatabase:we,jobQueue:c.object({workerConcurrency:c.number().int().min(1).max(32).default(4)}).prefault({}),conversationDatabase:we,runtimeStateDatabase:we,embeddingDatabase:we,ai:c.object({providerKeys:Be.default({}),model:c.string().refine(In,{error:(e)=>`Unsupported model "${String(e.input)}"`}),embeddingModel:c.string().refine((e)=>kr(e)!==void 0,{error:(e)=>xn(String(e.input))}).default(Cn),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:te.optional()}).superRefine((e,t)=>{if(e.answerModel&&me(e.answerModel)!=="local")t.addIssue({code:"custom",path:["answerModel"],message:`answerModel must be a local: model, not ${e.answerModel}`});if(e.visionModel&&me(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=[...me(e.model)==="local"?[e.model]:[],...[e.answerModel,e.visionModel].filter((i)=>i!==void 0&&me(i)==="local"),...e.imageModel&&Pn(e.imageModel).provider==="local"?[e.imageModel]:[],...kr(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:Ie.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(dt).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(),Iu).optional(),profileKind:c.string().trim().min(1).optional(),http:lt.prefault({})});function ut(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,...g}=zr.parse({...jr(),...W(p),ai:W({...a}),logging:W({...l}),embedding:W({...d}),jobQueue:W({...u}),plugins:[]});return{...g,plugins:t,permissions:r,...W({entityDisplay:m,identity:i,profile:n,agentInstructions:o,evalHandlerRegistry:s})}}var M={NOTE:"note",BRAIN_CHARACTER:"brain-character",ANCHOR_PROFILE:"anchor-profile"},$e={KNOWLEDGE_QUERY:"shell:knowledge-query",BASE_ENTITY_DISPLAY:"shell:base-entity-display",CONTENT_GENERATION:"shell:content-generation"},Or={ENTITIES:"shell:entities"};var Pu=Tn.extend({templateName:c.string()}),Cu=c.object({slug:c.string()}),xu="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.",Tu="Generate the content described in your instructions.";function Eu(e){return e instanceof c.ZodType}function Au(e){if(!e)return;return e.replace(/^https?:\/\//,"").replace(/\/$/,"")}class mt{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=Au(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=Pu.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 En((v,y)=>i.getEntity(v,y),n.templateName,o.basePrompt):await pt(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),g=i?await this.readIdentities(i,n.representedIdentity):void 0,f=this.buildSystemPrompt(s,n,g);if(!Eu(o.schema))throw Error(`Template ${o.name} cannot be used for AI generation: schema is not an AI generation schema`);r?.throwIfAborted();let h=await this.aiService.generateObject(f,m,o.schema,r);return r?.throwIfAborted(),t.parse(h.object)}async readIdentities(e,t){let r=async(o)=>(await e.getEntity(o,o))?.content??"",[i,n]=await Promise.all([t!=="none"?r(M.BRAIN_CHARACTER):"",t===void 0||t==="anchor"?r(M.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",xu,"");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
- `):Tu}formatRelevantEntity(e,t){let{entity:r,excerpt:i}=e,n=r.entityType,o=Cu.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 ku=c.object({entityType:c.string(),query:c.object({id:c.string()})});class gt{entityService;id=Or.ENTITIES;name="Entity DataSource";description="Fetches entity content from the entity service";constructor(e){this.entityService=e}async fetch(e,t,r){let i=ku.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 An(e,t){e.dataSourceRegistry.register(new mt(e.aiService,e.entityService,e.templateRegistry,()=>e.identityService.getCharacterContent(),()=>e.profileService.getProfileContent(),new ft(t.entityDisplay),t.siteBaseUrl)),e.dataSourceRegistry.register(new gt(e.entityService)),e.logger.debug("Core DataSources registered")}async function kn(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 Dn={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 jn={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 zn={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 On={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 Mn={lexicon:1,id:"ai.rizom.brain.post",defs:{main:{type:"record",description:"Markdown blog post distributed by a Rizom brain.",key:"any",record:{type:"object",required:["title","body","createdAt"],properties:{title:{type:"string",maxLength:300},summary:{type:"string",maxLength:2000},body:{type:"string",maxLength:1e5},format:{type:"string",knownValues:["text/markdown"]},brainDid:{type:"string"},anchorDid:{type:"string"},canonicalUrl:{type:"string",format:"uri"},topics:{type:"array",items:{type:"string"},maxLength:50},coverImage:{type:"ref",ref:"#coverImage"},series:{type:"string",maxLength:200},seriesIndex:{type:"integer"},sourceEntityType:{type:"string",knownValues:["post"]},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},publishedAt:{type:"string",format:"datetime"}}}},coverImage:{type:"object",description:"Cover image attached to the post.",required:["blob"],properties:{blob:{type:"blob"},alt:{type:"string",maxLength:1000},width:{type:"integer"},height:{type:"integer"}}}}};var Ln={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 Un={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 Bn={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 $n={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 _n=c.object({type:c.string()}).catchall(c.unknown()),_u=c.object({type:c.literal("object"),description:c.string().optional(),required:c.array(c.string()).optional(),properties:c.record(c.string(),_n)}),Zu=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(),_n)})})}).catchall(_u)});function _(e){return Zu.parse(e)}var z={"ai.rizom.brain.card":_(Dn),"ai.rizom.brain.deck":_(jn),"ai.rizom.brain.link":_(zn),"ai.rizom.brain.note":_(On),"ai.rizom.brain.post":_(Mn),"ai.rizom.brain.project":_(Ln),"ai.rizom.brain.series":_(Un),"ai.rizom.brain.socialPost":_(Bn),"ai.rizom.brain.topic":_($n)},Fu="Additive optional fields are compatible; required-field, type, or constraint changes require a migration plan or new NSID.";function q(e){return{status:"approved",version:"1.0.0",revision:1,owner:"Rizom",steward:"Rizom protocol registry",projectionPackage:e,compatibility:Fu}}var Zn={"ai.rizom.brain.card":q("@brains/atproto"),"ai.rizom.brain.deck":q("@brains/decks"),"ai.rizom.brain.link":q("@brains/link"),"ai.rizom.brain.note":q("@brains/note"),"ai.rizom.brain.post":q("@brains/blog"),"ai.rizom.brain.project":q("@brains/portfolio"),"ai.rizom.brain.series":q("@brains/series"),"ai.rizom.brain.socialPost":q("@brains/social-media"),"ai.rizom.brain.topic":q("@brains/topics")};function Nu(){return Object.values(z)}function Hu(e){if(!Lr(z,e))return;return z[e]}function Wu(){return Mr(Zn).map(([e,t])=>({id:e,...t}))}var qu=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;function Ju(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)=>qu.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 Gu(e,t){if(typeof e!=="string"||!e.startsWith("#"))return;let r=t[e.slice(1)];return r?.type==="object"?r:void 0}function Nn(e,t){switch(e.type){case"string":return Ju(e);case"integer":return c.number().int();case"boolean":return c.boolean();case"array":{let r=e.items?Nn(e.items,t):c.unknown(),i=c.array(r);if(e.maxLength!==void 0)i=i.max(e.maxLength);return i}case"object":return Fn(e,t);case"ref":{let r=Gu(e.ref,t);if(!r)return c.custom(()=>!1,{message:`unresolvable lexicon ref ${String(e.ref)}`});return c.lazy(()=>Fn(r,t))}case"blob":return c.custom(te,{message:"expected blob"});default:return c.unknown()}}function Hn(e,t){let r=new Set(e.required??[]),i={};for(let[n,o]of Object.entries(e.properties??{})){let s=Nn(o,t);i[n]=r.has(n)?s:s.optional()}return i}function Fn(e,t){return c.strictObject(Hn(e,t))}function U(e){return c.strictObject({...Hn(e.defs.main.record,e.defs),$type:c.literal(e.id).optional()})}var Ur={"ai.rizom.brain.card":U(z["ai.rizom.brain.card"]),"ai.rizom.brain.deck":U(z["ai.rizom.brain.deck"]),"ai.rizom.brain.link":U(z["ai.rizom.brain.link"]),"ai.rizom.brain.note":U(z["ai.rizom.brain.note"]),"ai.rizom.brain.post":U(z["ai.rizom.brain.post"]),"ai.rizom.brain.project":U(z["ai.rizom.brain.project"]),"ai.rizom.brain.series":U(z["ai.rizom.brain.series"]),"ai.rizom.brain.socialPost":U(z["ai.rizom.brain.socialPost"]),"ai.rizom.brain.topic":U(z["ai.rizom.brain.topic"])};function Qu(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(!te(r))return;r=r[String(i)]}return r}function Ku(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"&&Qu(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 Vu(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(Ku(e,t,i))}var Wn="atproto:brain-card-discovered",qn="atproto:brain-discovered",Jn="atproto:brain-card-refreshed",Gn="atproto:brain-card-unavailable",Qn="atproto:brain-card-conflict",Kn="atproto:jetstream-gap",Yu=c.custom((e)=>Ur["ai.rizom.brain.card"].safeParse(e).success),Vn=c.object({repoDid:c.string().min(1),uri:c.string().min(1),cid:c.string().min(1),record:Yu}).strict(),Br=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(),Yn=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(),Xn=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(),eo=c.object({previousCursorTimeUs:c.number().int().nonnegative(),clampedCursorTimeUs:c.number().int().nonnegative(),observedAt:c.string().datetime()}).strict(),Xu=ge(Wn,Vn),ep=ge(qn,Br),tp=ge(Jn,Br),rp=ge(Gn,Yn),ip=ge(Qn,Xn),np=ge(Kn,eo);class ht{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 op({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 vt(e,t,r){let i=await yt(e,to,{actor:r},t);if(i.status==="unavailable")return null;if(i.status==="failed")throw ro(i.error,`Principal resolution failed: ${i.error.message}`);return i.data.principal}function no(e,t){return new io(e,(r)=>vt(t,"shell:content-service",r))}var $r=x.Service("@brains/conversation-service/ConversationService");function sp(e){if(e.service){let r=e.service;return{service:r,close:()=>r.close()}}let t=oo.createFreshFromConfig(e.logger,e.messageBus,e.dbConfig);try{return{service:t,close:()=>t.close()}}catch(r){throw t.close(),r}}function so(e){return re($r,()=>sp(e))}var _r=x.Service("@brains/entity-service/EntityService");function ap(e){return"close"in e&&typeof e.close==="function"}function co(e){return re(_r,()=>{let t=e.service??ao.createFresh(e);return{service:t,close:()=>{if(ap(t))t.close()}}})}var _e=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()}),Zr=c.strictObject({alerts:c.array(_e).optional()});var bt="shell:recurring-check",Nr=86400000,cp=7*Nr,lp=3*Nr,dp=c.strictObject({checkId:c.string().min(1)}),up=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:_e,observedAt:c.string().datetime(),includeInInbox:c.boolean().optional(),deliveredAt:c.string().datetime().optional(),resolvedAt:c.string().datetime().optional()})]);class Rt{brainId;scheduler;state;jobQueue;delivery;logger;clock;checks=new Map;pluginChecks=new Map;alertOperations=new mo;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:up});let t={validateAndParse:(r)=>{let i=dp.safeParse(r);return i.success?i.data:null},process:async(r)=>{await this.runNow(r.checkId)}};this.jobQueue.registerHandler(bt,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(bt),this.handlerRegistered=!1}namespace(e){return{register:(t)=>this.register(e,t)}}register(e,t){mp(e),go(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=Zr.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=b.tryPromise({try:(a)=>(i=n(a),i),catch:(a)=>a}),s=await b.runPromiseExit(o,{signal:t});if(i)await Promise.allSettled([i]);if(D.isSuccess(s))return!0;if(t.aborted)throw t.reason;throw ne.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=St(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=St(this.brainId,r.id,r.cadence),n=Fr(this.currentTime(),i).getTime()+i.periodMs,o=new AbortController,s={controller:o,settled:Promise.resolve()};e.enqueueRetry=s,s.settled=lo(()=>this.enqueue(r.id),t,{firstDelayMs:uo,maxDelayMs:po,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=St(this.brainId,t.id,t.cadence),n=Fr(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:bt,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=_e.parse(t),n=this.alertKey(e,i.dedupeKey);await this.alertOperations.run(n,async()=>{let o=await this.state.get(n);if(o?.kind==="alert"){let a=o.includeInInbox===r.includeInInbox?o:{...o,includeInInbox:r.includeInInbox};if(a!==o)await this.state.set(n,a);if(a.status==="delivered"||a.status==="resolved")return;if(r.deliver)await this.deliverStoredAlert(n,a);return}let s={kind:"alert",checkId:e,dedupeKey:i.dedupeKey,status:r.deliver?"pending":"suppressed",alert:i,observedAt:this.currentTime().toISOString(),includeInInbox:r.includeInInbox};if(await this.state.set(n,s),r.deliver)await this.deliverStoredAlert(n,s)})}async deliverStoredAlert(e,t){if(await this.delivery.deliver(t.alert)===!1)return;await this.state.set(e,{...t,status:"delivered",deliveredAt:this.currentTime().toISOString()})}currentTime(){return this.clock?new Date(this.clock.currentTimeMillisUnsafe()):new Date}lastSuccessKey(e){return`run:${ie(e)}`}alertKeyPrefix(e){return`alert:${ie(e)}:`}alertKey(e,t){return`${this.alertKeyPrefix(e)}${ie(t)}`}}function St(e,t,r){let i=r==="daily"?Nr:cp,n=i/60000,o=ie(`${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:lp}}function Fr(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 pp=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*:[a-z][a-z0-9-]*$/;function mp(e){if(e.length<=200&&pp.test(e))return;go(e,"plugin ID")}function go(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 I=fo("runtime_state_records",{namespace:wt("namespace").notNull(),key:wt("key").notNull(),value:wt("value",{mode:"json"}).notNull(),createdAt:Hr("created_at").notNull(),updatedAt:Hr("updated_at").notNull()},(e)=>({pk:yo({columns:[e.namespace,e.key]}),namespaceUpdatedAtIdx:ho("idx_runtime_state_namespace_updated_at").on(e.namespace,e.updatedAt)}));function bo(e){return vo({url:e.url,schema:{runtimeStateRecords:I},authToken:e.authToken,authTokenEnv:"RUNTIME_STATE_DATABASE_AUTH_TOKEN"})}function It(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 gp}from"util";var fp=/^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,511}$/,Po=512;class Wr{db;namespace;schema;now;constructor(e,t,r,i=()=>new Date){hp(t),this.db=e,this.namespace=t,this.schema=r,this.now=i}async get(e){let t=fe(e),i=(await this.db.select().from(I).where(oe(O(I.namespace,this.namespace),O(I.key,t))).limit(1))[0];if(!i)return null;return this.schema.parse(i.value)}async has(e){let t=fe(e);return(await this.db.select({key:I.key}).from(I).where(oe(O(I.namespace,this.namespace),O(I.key,t))).limit(1)).length>0}async set(e,t){let r=fe(e),i=It(this.schema,t),n=i===null?he`'null'`:i,o=this.now().getTime();await this.db.insert(I).values({namespace:this.namespace,key:r,value:n,createdAt:o,updatedAt:o}).onConflictDoUpdate({target:[I.namespace,I.key],set:{value:n,updatedAt:o}})}async setIfNotExists(e,t){let r=fe(e),i=It(this.schema,t),n=i===null?he`'null'`:i,o=this.now().getTime(),s=await this.db.insert(I).values({namespace:this.namespace,key:r,value:n,createdAt:o,updatedAt:o}).onConflictDoNothing({target:[I.namespace,I.key]});return Number(s.rowsAffected)>0}async compareAndSet(e,t,r){let i=fe(e),n=It(this.schema,r),[o]=await this.db.select({value:I.value}).from(I).where(oe(O(I.namespace,this.namespace),O(I.key,i))).limit(1);if(!o||!gp(this.schema.parse(o.value),t))return!1;let s=o.value===null?he`'null'`:o.value,a=n===null?he`'null'`:n,l=await this.db.update(I).set({value:a,updatedAt:this.now().getTime()}).where(oe(O(I.namespace,this.namespace),O(I.key,i),O(I.value,s)));return Number(l.rowsAffected)===1}async delete(e){let t=fe(e),r=await this.db.delete(I).where(oe(O(I.namespace,this.namespace),O(I.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(I).where(oe(O(I.namespace,this.namespace),So(e.keyPrefix)));return Number(t.rowsAffected)}async listRows(e){let{keyPrefix:t,afterKey:r,limit:i}=e;if(r!==void 0)fe(r);if(i!==void 0)c.number().int().min(1).max(1000).parse(i);let n=this.db.select({...Ro(I),key:he`CAST(${I.key} AS BLOB)`.mapWith((o)=>new TextDecoder("utf-8",{fatal:!0}).decode(o))}).from(I).where(oe(O(I.namespace,this.namespace),So(t),r!==void 0?wo(I.key,r):void 0)).orderBy(Io(I.key)).$dynamic();return i===void 0?n:n.limit(i)}}function hp(e){if(!fp.test(e))throw Error(`Invalid runtime state namespace: ${e}. Use 1-512 alphanumeric, _, ., :, or - characters.`)}function fe(e){if(e.length===0||e.length>Po)throw Error("Runtime state keys must be 1-512 characters long");return e}function So(e){if(e===void 0)return;return yp(e),he`substr(CAST(${I.key} AS BLOB), 1, length(CAST(${e} AS BLOB))) = CAST(${e} AS BLOB)`}function yp(e){if(e.length>Po)throw Error("Runtime state key prefixes must be 512 characters or shorter");return e}class Pt{db;client;logger;databaseUrl;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;static createFresh(e,t){return new Pt(e,t??Pe.getInstance())}constructor(e,t){let{db:r,client:i,url:n}=bo(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 Co(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 Wr(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=x.Service("@brains/runtime-state/RuntimeStateService");function xo(e){return re(qr,()=>{let t=e.service??Pt.createFresh(e.config,e.logger);return{service:t,close:()=>t.close()}})}async function Jr(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=Ze(r),t.warn(`Daemon ${e.name} failed to start: ${P(r)}`),r}}async function Gr(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=Ze(r),t.error(`Failed to stop daemon: ${e.name}`,r),r}}async function To(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 Eo(e){return{name:e.name,pluginId:e.pluginId,status:e.status,health:e.health}}class Ct{daemons=new Map;daemonScopes=new Map;daemonTransitions=new Map;logger;static createFresh(e){return new Ct(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 Jr(t,this.logger);return}let r=b.runSync(j.make()),i=b.acquireRelease(b.promise(()=>Jr(t,this.logger)),()=>b.promise(()=>Gr(t,this.logger)));try{await b.runPromise(j.provide(i,r)),this.daemonScopes.set(e,r)}catch(n){throw await b.runPromise(j.close(r,D.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 Gr(t,this.logger);return}this.daemonScopes.delete(e),await b.runPromise(j.close(r,D.void))}async checkHealth(e){let t=this.daemons.get(e);if(!t)throw Error(`Daemon not registered: ${e}`);return To(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(Eo)}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??=Ze(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 vp=c.object({projectionId:c.string().min(1),reason:c.string().min(1),openedAt:c.number().int().nonnegative(),expiresAt:c.number().int().nonnegative()}),bp=8,Sp=32,Rp=128,wp=5,Ip=600000,Pp=600000,Cp=1000,xp="shell.projection-circuits";class xt{operationContext;options;circuitStore;roots=new Map;reservedJobs=new Map;circuits=new Map;projections;static createFresh(e,t={}){return new xt(e,t)}constructor(e,t){this.operationContext=e,this.options={maxDerivationDepth:t.maxDerivationDepth??bp,maxJobsPerRoot:t.maxJobsPerRoot??Sp,maxMutationsPerRoot:t.maxMutationsPerRoot??Rp,repeatedTargetLimit:t.repeatedTargetLimit??wp,retentionMs:t.retentionMs??Ip,circuitOpenMs:t.circuitOpenMs??Pp,maxTrackedRoots:t.maxTrackedRoots??Cp,now:t.now??Date.now};for(let[r,i]of Object.entries(this.options)){if(r==="now")continue;if(typeof i!=="number"||!Number.isInteger(i)||i<=0)throw Error(`${r} must be a positive integer`)}this.circuitStore=t.runtimeState?.scoped({namespace:xp,schema:vp})}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 Tp={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 Ce(e){return Tp[e??"combined"]}var Ao=[Tt.created,Tt.updated,Tt.deleted];function ko(e,t,r){let i=Ao.map((o)=>e.subscribe(o,(s)=>(t.send({type:o,payload:s.payload}),{success:!0}))),n=t.onEvent((o)=>{if(!Ao.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 Ep=20,Ap=0.5,kp=0.06,Dp=5;function jo(e){return async({answer:t})=>{let i=(await e.entityService.search({query:t,options:{limit:Ep,minScore:Ap,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-kp).slice(0,Dp).map(({entity:o})=>Do(o,e))}}function jp(e,t,r,i,n){return[Lo,Uo,Bo].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 zo(e,t,r,i){return jp(e,t,t,async()=>{await r(),await Te(e,$o,{entityType:t},"shell")},i)}async function zp(e,t,r){let i=Op(e.kind);if(!i)return null;try{let n=t.scoped({namespace:i,refKind:e.kind,routePath:""});return Mp(await n.read(e.id),e)}catch(n){return r.debug("Skipped unavailable prior runtime upload",{uploadKind:e.kind,uploadId:e.id,error:P(n)}),null}}function Op(e){return e===xe.refKind?xe.namespace:null}function Mp(e,t){let{record:r,content:i}=e;if(Lp(r.mediaType))return{kind:"text",filename:r.filename,mediaType:r.mediaType,content:new TextDecoder("utf-8").decode(i).replace(/^\uFEFF/,""),sizeBytes:r.sizeBytes,source:t};return{kind:"file",filename:r.filename,mediaType:r.mediaType,data:new Uint8Array(i),sizeBytes:r.sizeBytes,source:t}}function Lp(e){let t=e.toLowerCase();return t.startsWith("text/")||t==="application/json"}function Go(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=Wo.createFresh(r,i,t.identity);d.push(...zo(n,M.BRAIN_CHARACTER,()=>p.refreshCache(),i));let m=qo.createFresh(r,i,t.profile),g=Jo.createFresh(i,async(R)=>{let w=await vt(n,"shell:canonical-identity-service",R).catch(()=>null);if(!w?.canonicalId)return null;return{userId:w.userId,canonicalId:w.canonicalId,displayName:w.displayName}}),f=Ho({guestPricing:_o(o.getConfig().model),model:o.getModel(),answerModel:o.getAnswerModel?.(),modelId:o.getConfig().model,webSearch:o.getConfig().webSearch,temperature:o.getConfig().temperature,reasoningEffort:o.getConfig().reasoningEffort,messageBus:n}),h=Zo(t.name),v=new ft(t.entityDisplay),y={isCitable:(R)=>v.isCitable(R),urlFor:(R,w)=>v.generateUrl(R,w),siteBaseUrl:t.siteBaseUrl},S=Fo.createFresh(s,a,p,m,i,{agentFactory:f,turnEvents:No(n),canonicalIdentityResolver:g,entityLinks:y,...e.generationUsage?{generationUsage:e.generationUsage}:{},...e.embeddingUsage?{embeddingUsage:e.embeddingUsage}:{},...t.embedding.enabled?{indexReadiness:r,guestAnswerSources:jo({entityService:r,...y})}:{},uploadAttachmentResolver:(R)=>zp(R,l,i),guestAskedBefore:async(R)=>{let w=await Fe(n,Oo,R,"shell:agent-service");return w.status==="answered"?w.answers.find((C)=>C.hit)?.hit:void 0},agentContextProvider:async(R)=>{let w=await Fe(n,Mo,R,"shell:agent-service");return w.status==="answered"?w.answers.flatMap((C)=>C.items):[]},...h?{assistantAgentId:h}:{},...t.agentInstructions&&{agentInstructions:t.agentInstructions}});if(d.push(...zo(n,M.ANCHOR_PROFILE,()=>m.refreshCache(),i)),!u)d.push(n.subscribe(Ne.identityChanged,async()=>(S.invalidateAgent(),{success:!0})));return{identityService:p,profileService:m,canonicalIdentityService:g,agentService:S}}var He=x.Service("@brains/job-queue/JobQueueService"),Et=x.Service("@brains/job-queue/BatchJobManager"),At=x.Service("@brains/job-queue/JobProgressMonitor"),kt=x.Service("@brains/job-queue/JobQueueWorker");function Xo(e){return re(He,()=>{let t=e.service??Qo.createFresh(e.config,e.logger,{...e.operationContext&&{operationContext:e.operationContext},...e.projectionAdmission&&{projectionAdmission:e.projectionAdmission},...e.handlerRegistrationMode&&{handlerRegistrationMode:e.handlerRegistrationMode}});return{service:t,close:()=>t.close()}})}function es(e){let t=!1,r=b.gen(function*(){let i=yield*He,n=e.batchJobManager??Vo.createFresh(i,e.logger),o=e.jobProgressMonitor??Yo.createFresh(i,e.messageBus,n,e.logger,e.progressMonitorMode),s=e.jobQueueWorker??Ko.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 x.make(Et,n).pipe(x.add(At,o),x.add(kt,s))});return{layer:J.effectContext(b.acquireRelease(r,(i)=>t?b.void:Up(i))),abandon:()=>{t=!0}}}function Up(e){let t=x.get(e,kt),r=x.get(e,At),i=x.get(e,Et);return b.gen(function*(){let n=yield*b.exit(b.tryPromise({try:()=>t.stop(),catch:(l)=>l})),o=yield*b.exit(b.tryPromise({try:()=>r.stop(),catch:(l)=>l})),s=yield*b.exit(b.tryPromise({try:async()=>{await i.stop()},catch:(l)=>l})),a=[n,o,s].find(D.isFailure);if(a)yield*b.die(ne.squash(a.cause))})}function Bp(e,t=(r)=>process.exit(r)){return(r)=>{e.error("Job queue worker requires process restart",{reason:r,exitCode:1}),t(1)}}function Dt(e){let t=b.runSyncExit(j.close(e,D.void));if(D.isFailure(t))throw ne.squash(t.cause)}function ts(e){let t=e.operationContext??jt.createFresh(),r=b.runSync(j.make()),i,n;try{let o=b.runSync(J.buildWithScope(Xo({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=x.get(o,He),a=b.runSync(j.make());i=a;let l=es({messageBus:e.messageBus,logger:e.logger,operationContext:t,...e.projectionBatchScope&&{projectionBatchScope:e.projectionBatchScope},onWorkerUnhealthy:Bp(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=b.runSync(J.buildWithScope(l.layer.pipe(J.provide(J.succeed(He,s))),a)),u=x.get(d,Et),p=x.get(d,At),m=x.get(d,kt),g,f=!1,h=!1;return{batchJobManager:u,jobProgressMonitor:p,jobQueueService:s,jobQueueWorker:m,closeRuntime:()=>(f=!0,g??=b.runPromise(j.close(a,D.void)),g),rollbackRuntime:()=>{if(f)return;f=!0,l.abandon(),Dt(a)},closeDatabase:()=>{if(h)return;h=!0,Dt(r)}}}catch(o){if(i)try{n?.abandon(),Dt(i)}catch(s){e.logger.warn("Failed to release partial job runtime acquisition",s)}try{Dt(r)}catch(s){e.logger.warn("Failed to release partial job database acquisition",s)}throw o}}function ns(e){return e.scoped({namespace:"shell.legacy-binary-content",schema:is})}var $p=8;class Qr{store;logger;flushDelayMs;now;pending=new Map;timer;writing=Promise.resolve();constructor(e){this.store=e.store,this.logger=e.logger.child("LegacyBinaryLedger"),this.flushDelayMs=e.flushDelayMs??1000,this.now=e.now??(()=>new Date)}record(e){let t=`${e.method}:${e.entityType}`,r=this.now().toISOString(),i=this.pending.get(t);if(this.pending.set(t,{method:e.method,entityType:e.entityType,count:(i?.count??0)+1,firstAt:i?.firstAt??r,lastAt:r}),this.timer)return;this.timer=setTimeout(()=>{this.timer=void 0,this.flush()},this.flushDelayMs),this.timer.unref()}flush(){return clearTimeout(this.timer),this.timer=void 0,this.writing=this.writing.then(()=>this.writePending()),this.writing}async list(){return await this.flush(),(await this.store.list()).map((t)=>t.value).sort((t,r)=>t.method.localeCompare(r.method)||t.entityType.localeCompare(r.entityType))}dispose(){clearTimeout(this.timer),this.timer=void 0}async writePending(){let e=[...this.pending];this.pending=new Map,await Promise.all(e.map(async([t,r])=>{try{await this.fold(t,r,1)}catch(i){this.keep(t,r),this.logger.warn("Could not record legacy binary content use",{method:r.method,entityType:r.entityType,error:P(i)})}}))}async fold(e,t,r){let i=await this.store.get(e);if(i?await this.store.compareAndSet(e,i,rs(i,t)):await this.store.setIfNotExists(e,t))return;if(r>=$p)throw Error("other processes kept changing the count");await this.fold(e,t,r+1)}keep(e,t){let r=this.pending.get(e);this.pending.set(e,r?rs(t,r):t)}}function rs(e,t){return{method:e.method,entityType:e.entityType,count:e.count+t.count,firstAt:e.firstAt<t.firstAt?e.firstAt:t.firstAt,lastAt:e.lastAt>t.lastAt?e.lastAt:t.lastAt}}function ss(e){return{deliver:async(t)=>{let r=await yt(e,os,{title:t.title,body:t.body,...t.html?{html:t.html}:{}},"shell.recurring-checks");if(r.status==="unavailable")return!1;if(r.status==="failed"||r.data.status!=="sent")throw Error("Recurring alert delivery failed");return!0}}}function cs(e){return{sourceId:"recurring-checks",displayName:"Recurring checks",list:async()=>(await e.listOpenAlerts()).map((t)=>({id:t.id,title:as(t.title,160),summary:as(t.body,1000),receivedAt:t.observedAt,urgency:"high",actions:[{id:"resolve",label:"Dismiss",confirm:!0}]})),act:async(t,r,i)=>{if(i.permissionLevel!=="admin")throw Error("Admin permission required");if(r!=="resolve")throw Error("Invalid recurring-check inbox action");await e.resolveOpenAlert(t)}}}function as(e,t){return e.length<=t?e:e.slice(0,t)}function ls(e,t){if(t)return t;let r={debug:We.DEBUG,info:We.INFO,warn:We.WARN,error:We.ERROR}[e.logging.level];return Pe.createFresh({level:r,context:e.logging.context,format:e.logging.format==="json"?"json":"text",...e.logging.file?{logFile:e.logging.file}:{}})}function Kr(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 Ee(e){return{url:e.url,...e.authToken?{authToken:e.authToken}:{}}}function Us(e){let{config:t,dependencies:r,initializerLogger:i,lifecycle:n,processRole:o,peerChannel:s}=e;i.debug("Initializing Shell services");let a=Ce(o),l=ls(t,r?.logger),d=r?.operationContext??jt.createFresh(),u=[],p=ks.createFresh(!r?.embeddingService),m=r?.embeddingService??As.createFresh({providerKeys:t.ai.providerKeys,profile:Ts(t.ai.embeddingModel),runtimeUrl:t.ai.modelRuntimeUrl,logger:l,usage:p}),g=Ds.createFresh(),f=r?.aiService??Es.createFresh(Kr(t),l,g),h=r?.entityRegistry??ps.createFresh(l),v=r?.messageBus??us.createFresh(l,d);if(s)u.push(ko(v,s,l));let y=r?.templateRegistry??gs.createFresh(l),S=r?.dataSourceRegistry??ms.createFresh(l),R=r?.renderService??hs.createFresh(y),w=r?.daemonRegistry??Ct.createFresh(l),C=r?.pluginManager??Os.createFresh(l,w),E=r?.permissionService??new fs(t.permissions,{spaces:t.spaces,entityActionFloor:(L)=>h.getEntityTypeConfig(L).actionPolicy}),B=r?.profileKindRegistry??new zs(t.profileKind),Re=r?.channelRegistry??new Ss,ue=r?.inboxRegistry??new ws,X=r?.inboxFollowUpRegistry??new Is(l),Qd=r?.operationalHealthRegistry??new js,Kd=r?.accountSettingsRegistry??new bs,Vd=new Rs,Yd=new ht,Xd=r?.attachmentRegistry??Ps.createFresh(),gn=r?.runtimeUploadRegistry??Cs.createFresh({dataDir:t.dataDir,logger:l}),eu=n.buildLayer(xo({config:Ee(t.runtimeStateDatabase),logger:l,...r?.runtimeStateService&&{service:r.runtimeStateService}})),ot=x.get(eu,qr),Ir=new Qr({store:ns(ot),logger:l});n.addSyncFinalizer(()=>Ir.dispose());let Pr=r?.projectionRuntimeSupervisor??xt.createFresh(d,{runtimeState:ot}),fn=r?.mcpService??xs.createFresh(v,l),Cr={},tu={runFreshBatchScope:(L)=>Cr.current?Cr.current.runFreshBatchScope(L):L()},st=ts({dependencies:r,jobQueueConfig:{...Ee(t.jobQueueDatabase),brainVersion:t.version},workerConcurrency:t.jobQueue.workerConcurrency,messageBus:v,operationContext:d,projectionBatchScope:tu,projectionAdmission:Pr,handlerRegistrationMode:a.handlerRegistrationMode,progressMonitorMode:a.progressMonitorMode,logger:l}),{batchJobManager:ru,jobProgressMonitor:iu,jobQueueService:xr,jobQueueWorker:nu}=st;n.addSyncFinalizer(()=>st.closeDatabase()),n.addSyncFinalizer(()=>st.rollbackRuntime());let Me=r?.recurringCheckService??new Rt({brainId:t.siteBaseUrl??t.dataDir,scheduler:new Ms,runtimeState:ot,clock:b.runSync(ds.Clock),jobQueue:xr,logger:l,delivery:ss(v)});n.addSyncFinalizer(()=>Me.abandon()),ue.registerSource("shell.recurring-checks",cs(Me)),n.addSyncFinalizer(()=>ue.unregisterPlugin("shell.recurring-checks"));let hn=(L,Er)=>{if(!a.serves)return;w.register(L,Er,"shell"),n.addSyncFinalizer(()=>w.abandon(L))};hn("shell:recurring-checks",{start:()=>Me.start(),stop:()=>Me.stop()});let ou=n.buildLayer(co({embeddingService:m,embeddingsEnabled:t.embedding.enabled,entityRegistry:h,logger:l,jobQueueService:xr,messageBus:v,mutationAdmission:Pr,onLegacyBinaryMaterialization:(L)=>Ir.record(L),...r?.projectionRuntime?.now&&{projectionNow:r.projectionRuntime.now},dbConfig:Ee(t.database),embeddingDbConfig:Ee(t.embeddingDatabase),...r?.entityService&&{service:r.entityService}})),at=x.get(ou,_r);Cr.current=at.getProjectionStore();let su=n.buildLayer(so({dbConfig:Ee(t.conversationDatabase),logger:l,messageBus:v,...r?.conversationService&&{service:r.conversationService}})),Tr=x.get(su,$r);hn("shell:guest-retention",Ls({intervalMs:60000,logger:l,run:async()=>{await Tr.deleteExpiredGuestConversations(100)}})),n.addSyncFinalizer(()=>{for(let L of u.splice(0))try{L()}catch(Er){l.warn("Failed to dispose shell subscription",Er)}});let yn=no(E,v),au=r?.contentService??new vs({logger:l,entityService:at,aiService:f,templateRegistry:y,dataSourceRegistry:S,generationAuthorizer:new ys(E,yn)}),{identityService:cu,profileService:lu,canonicalIdentityService:du,agentService:uu}=Go({config:t,entityService:at,embeddingService:m,embeddingUsage:p,...!r?.aiService?{generationUsage:g}:{},entityRegistry:h,logger:l,messageBus:v,aiService:f,mcpService:fn,conversationService:Tr,runtimeUploadRegistry:gn,disposables:u,executionOnly:!a.serves});return{logger:l,operationContext:d,projectionRuntimeSupervisor:Pr,disposables:u,entityRegistry:h,messageBus:v,renderService:R,daemonRegistry:w,pluginManager:C,templateRegistry:y,dataSourceRegistry:S,mcpService:fn,embeddingService:m,entityService:at,aiService:f,conversationService:Tr,contentService:au,callerAuthorizer:yn,jobQueueService:xr,jobQueueWorker:nu,batchJobManager:ru,jobProgressMonitor:iu,jobServicesLifecycle:st,permissionService:E,identityService:cu,profileService:lu,canonicalIdentityService:du,profileKindRegistry:B,channelRegistry:Re,inboxRegistry:ue,inboxFollowUpRegistry:X,operationalHealthRegistry:Qd,accountSettingsRegistry:Kd,authRegistry:Vd,atprotoProjectionRegistry:Yd,agentService:uu,attachmentRegistry:Xd,runtimeUploadRegistry:gn,runtimeStateService:ot,legacyBinaryLedger:Ir,recurringCheckService:Me}}function Ns(e,t){e.register(Vr.name,Vr),t.debug("Shell system templates registered")}function Hs(e,t){e.register($e.BASE_ENTITY_DISPLAY,{name:"base-entity-display",description:"Display template for base entities",schema:Yr,formatter:new Bs,requiredPermission:"public"}),t.debug("Base entity display template registered")}function Ws(e,t){e.registerEntityType(M.NOTE,Yr,new $s,{projectionSourceRole:"primary"}),t.debug("Fallback base entity adapter registered")}function qs(e,t){let r=new _s;e.registerEntityType(M.BRAIN_CHARACTER,r.schema,r,{classification:"system",projectionSource:!1,projectionSourceRole:"excluded"}),t.debug("Brain character entity support registered")}function Js(e,t){let r=new Zs;e.registerEntityType(M.ANCHOR_PROFILE,r.schema,r,{classification:"system",projectionSourceRole:"canonical"}),t.debug("Anchor profile entity support registered")}async function Gs(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 Fs||d?.requiresDaemonStartup?.())throw l}i.debug("Plugin initialization complete")}class zt{logger;config;processRole;peerChannel;static createFresh(e,t,r,i){return new zt(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){Ns(e,this.logger)}registerBaseEntityDisplayTemplate(e){Hs(e,this.logger)}registerFallbackBaseEntity(e){Ws(e,this.logger)}registerBrainCharacterSupport(e){qs(e,this.logger)}registerAnchorProfileSupport(e){Js(e,this.logger)}async initializePlugins(e,t){await Gs({plugins:this.config.plugins,pluginManager:e,logger:this.logger,initOptions:t})}initializeServices(e,t){return Us({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=Ks.createFresh(t,r);e.registerHandler(Qs.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(M.NOTE))this.registerFallbackBaseEntity(t);this.logger.debug("Shell registration phase complete")}catch(n){throw this.logger.error("Shell initialization failed",n),n}}}var Xr=c.strictObject({waveId:c.string().trim().min(1),ruleId:c.string().trim().min(1)});class ei{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=Xr.safeParse(e);return t.success?t.data:null}async onTerminalError(e,t,r){let i=Xr.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=Xr.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((C)=>C.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 C=await this.store.listPendingInputs();return await this.recordDiagnostic({...p,event:"apply-completed",applyOutcome:"superseded",highestPendingGeneration:Ot(C)}),{waveId:n.waveId,ruleId:o.id,outcome:"superseded",inputFingerprint:null,changedTargets:[]}}if(await this.store.supersedeWaveIfStale(n.waveId,this.now())){let C=await this.store.listPendingInputs();return await this.recordDiagnostic({...p,event:"apply-completed",applyOutcome:"superseded",highestPendingGeneration:Ot(C)}),await this.coordinator.continueAfterSupersession(n.waveId),{waveId:n.waveId,ruleId:o.id,outcome:"superseded",inputFingerprint:null,changedTargets:[]}}let m=Fp(s,a,u.level),g=await o.selectInput({waveId:n.waveId,inputs:m},this.inputContext,i),f=o.fingerprint(g),h={...p,inputFingerprint:f,selectedSourceCount:Zp(g,m)};await this.recordDiagnostic({...h,event:"input-selected"});let v={ruleId:o.id,ruleVersion:o.version,inputFingerprint:f},y=await this.store.getRuleMemo(v);await this.recordDiagnostic({...h,event:"memo-resolved",memoHit:y!==null});let S;if(y)S=y.writeIntents;else{await this.recordDiagnostic({...h,event:"derive-started",memoHit:!1});try{S=await o.derive(g,this.executionContext,i),await this.recordDiagnostic({...h,event:"derive-completed",memoHit:!1})}catch(C){throw await this.recordDiagnostic({...h,event:i.aborted?"derive-cancelled":"derive-failed",memoHit:!1}),C}}let R=await this.store.applyRuleResult({waveId:n.waveId,ruleId:o.id,ruleVersion:o.version,inputFingerprint:f,writeIntents:S,completedAt:this.now()}),w=await this.store.listPendingInputs();if(!R)return await this.recordDiagnostic({...h,event:"apply-completed",memoHit:y!==null,applyOutcome:"superseded",highestPendingGeneration:Ot(w)}),await this.coordinator.continueAfterSupersession(n.waveId),{waveId:n.waveId,ruleId:o.id,outcome:"superseded",inputFingerprint:f,changedTargets:[]};return await this.recordDiagnostic({...h,event:"apply-completed",memoHit:y!==null,applyOutcome:"applied",highestPendingGeneration:Ot(w)}),await this.reconcileTargets(R.changedTargets),await this.coordinator.advanceActiveWave(n.waveId),{waveId:n.waveId,ruleId:o.id,outcome:"applied",inputFingerprint:f,changedTargets:R.changedTargets}}async settleRetiredRuleJob(e){let t=await this.store.getWave(e);if(t?.status==="superseded")return!0;if(t?.status!=="running"||t.graphFingerprint===this.graphFingerprint)return!1;if((await this.store.supersedeWave(e,this.now())).status!=="superseded")return!1;return await this.coordinator.continueAfterSupersession(e),!0}async recordDiagnostic(e){if(!this.onDiagnostic)return;try{await this.onDiagnostic(e)}catch(t){this.executionContext.logger.warn("Projection diagnostics callback failed",t)}}}function Zp(e,t){if(typeof e==="object"&&e!==null&&"sources"in e&&Array.isArray(e.sources))return e.sources.length;return t.length}function Ot(e){if(e.length===0)return null;return e.reduce((t,r)=>Math.max(t,r.generation),e[0]?.generation??0)}function Fp(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 Np(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 Ae="shell:projection-rule";class ri{store;queue;graph;ruleById;graphFingerprint;createWaveId;beforeWaveCompletion;scheduleWakeup;onScheduledWakeupError;now;operationQueue=new Vs;scheduledWakeup;constructor(e){this.store=e.store,this.queue=e.queue,this.graph=e.graph,this.ruleById=qp(e.graph,e.rules),this.graphFingerprint=Jp(e.graph,e.rules),this.createWaveId=e.createWaveId,this.beforeWaveCompletion=e.beforeWaveCompletion??(async()=>{}),this.scheduleWakeup=e.scheduleWakeup??Hp,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(ti(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(ti(s))await this.startNextWaveInternal();return s}let t=await this.store.listPendingInputs();if(t.length===0)return this.cancelScheduledWakeup(),null;let r=Wp(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(ti(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=Xs(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:Np(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:Ae,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 ti(e){return e.status==="completed"||e.status==="superseded"}function Hp(e,t){let r=setTimeout(()=>{t()},e);return()=>clearTimeout(r)}function Wp(e,t,r){let n=Xs(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 qp(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 Jp(e,t){return Ys({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 Xs(e,t,r){let i=new Map(e.projections.map((l)=>[l.id,l])),n=ea(e,(l)=>[l.from,l.to]),o=new Set(e.projections.filter((l)=>Gp(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=Qp(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 Gp(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 Qp(e,t){let r=ea(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 ea(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 ta(e){let t=new ri({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 ei({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(Ae,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??Kp)(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(Ae),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(Ae)}}}function Kp(e,t){let r=setInterval(()=>{t()},e);return r.unref(),()=>clearInterval(r)}import{existsSync as _m}from"fs";import{mkdir as Zm,writeFile as Fm}from"fs/promises";import{join as Nm,resolve as Ka}from"path";var ra=5000;async function ia(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 na(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 Lm,sep as Um}from"path";var oa=Symbol();var sa=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,(r)=>r.toLowerCase())}}).formData();var Vp=1e4,Mt=(e)=>("headers"in e),la=async(e,t=Object.create(null))=>{let{all:r=!1,dot:i=!1}=t,n=(Mt(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 Yp(e,{all:r,dot:i});return{}};async function Yp(e,t){if(!Mt(e)&&e.bodyCache.formData)return aa(await e.bodyCache.formData,t);let r=Mt(e)?e.headers:e.raw.headers,i=await e.arrayBuffer(),n=sa(i,r.get("Content-Type")||"");if(!Mt(e))e.bodyCache.formData=n;let o=await n;if(o)return aa(o,t);return{}}function aa(e,t){let r=Object.create(null),i={count:0};if(e.forEach((n,o)=>{if(!(t.all||o.endsWith("[]")))r[o]=n;else Xp(r,o,n)}),t.dot)Object.entries(r).forEach(([n,o])=>{if(n.includes("."))em(r,n,o,i),delete r[n]});return r}var Xp=(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]},em=(e,t,r,i)=>{if(/(?:^|\.)__proto__\./.test(t))return;let n=e,o=t.split(".",34);if(o.length>33)ca();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++>=Vp)ca();n[s]=Object.create(null)}n=n[s]}})},ca=()=>{throw Error("Nesting limit exceeded")};var ni=(e)=>{let t=e.split("/");if(t[0]==="")t.shift();return t},da=(e)=>{let{groups:t,path:r}=tm(e),i=ni(r);return rm(i,t)},tm=(e)=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,i)=>{let n=`@${i}`;return t.push([n,r]),n}),{groups:t,path:e}},rm=(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},Lt={},ua=(e,t)=>{if(e==="*")return"*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let i=`${e}#${t}`;if(!Lt[i])if(r[2])Lt[i]=t&&t[0]!==":"&&t[0]!=="*"?[i,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)];else Lt[i]=[e,r[1],!0];return Lt[i]}return null},pa=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,(r)=>{try{return t(r)}catch{return r}})}},oi=(e)=>pa(e,decodeURI),si=(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 oi(l.includes("%25")?l.replace(/%25/g,"%2525"):l)}else if(n===63||n===35)break}return t.slice(r,i)};var ma=(e)=>{let t=si(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},se=(e,t,...r)=>{if(r.length)t=se(t,...r);return`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`},Ut=(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)},Bt=(e)=>e.indexOf("%")!==-1?pa(e,im):e,ii=(e)=>{if(e.indexOf("+")!==-1)e=e.replace(/\+/g," ");return Bt(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 ii(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=ii(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=ii(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},fa=ga,ha=(e,t)=>ga(e,t,!0),im=decodeURIComponent;var ya=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&&Bt(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]=Bt(i)}return e}#i(e){return this.#e[1]?this.#e[1][e]:e}query(e){return fa(this.url,e)}queries(e){return ha(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 la(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[oa](){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 va={Stringify:1,BeforeStream:2,Stream:3},ba=(e,t)=>{let r=new String(e);return r.isEscaped=!0,r.callbacks=t,r};var ai=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)=>ai(l,t,!1,i,n))).then(()=>n[0]));if(r)return ba(await s,o);else return s};var nm="text/plain; charset=UTF-8",ci=(e,t)=>({"Content-Type":e,...t}),qe=(e,t)=>new Response(e,t),li=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 ya(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||=qe(null,{headers:this.#a??=new Headers})}set res(e){if(this.#n&&e){e=qe(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=qe(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 qe(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,ci(nm,r));json=(e,t,r)=>this.#s(JSON.stringify(e),t,ci("application/json",r));html=(e,t,r)=>{let i=(n)=>this.#s(n,t,ci("text/html; charset=UTF-8",r));return typeof e==="object"?ai(e,va.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??=()=>qe(),this.#l(this))};var di=(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 Sa=["get","post","put","delete","options","patch","query"],$t="Can not add a route since the matcher is already built.",_t=class extends Error{};var ui="__COMPOSED_HANDLER";var om=(e)=>e.text("404 Not Found",404),Ra=(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)},wa=class e{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...Sa,"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??si:ma}#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=om;errorHandler=Ra;route(t,r){let i=this.basePath(t);return r.routes.map((n)=>{let o;if(r.errorHandler===Ra)o=n.handler;else o=async(s,a)=>(await di([],r.errorHandler)(s,()=>n.handler(s,a))).res,o[ui]=n.handler;i.#o(n.method,n.path,o,n.basePath)}),this}basePath(t){let r=this.#e();return r._basePath=se(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=se(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",se(t,"*"),a),this}#o(t,r,i,n){r=se(this._basePath,r);let o={basePath:n!==void 0?se(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 li(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=di(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${se("/",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 Zt=[];function pi(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[[],Zt];let d=l.indexOf("",1);return[s[1][d],l]};return this.match=i,i(e,t)}var mi="[^/]+";var gi="(?:|/.*)",ae=Symbol(),Ia=new Set(".\\+*[^]$()");function sm(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?["","",".*"]:["","",mi]:null:d==="/*"?["","",gi]:d.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),p;if(u){let m=u[1],g=u[2]||"[^/]+";if(m&&u[2]){if(g===".*")throw ae;if(g=g.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(g))throw ae;if(g.length===1&&Ia.has(g))throw ae}if(p=s.#r[g],!p){if(g!==".*"&&g!=="(?:|/.*)"){for(let f in s.#r)if((g.length>1||f.length>1)&&f!==".*"&&f!=="(?:|/.*)")throw ae}p=s.#r[g]=new e}if(m!=="")p.#e??=n.varIndex++,i.push([m,p.#e])}else if(p=s.#r[d],!p){for(let m in s.#r)if(m.length>1&&m!==".*"&&m!=="(?:|/.*)")throw ae;p=s.#r[d]=new e}s=p}if(s.#t!==void 0)throw ae;s.#t=o?-1:r}buildRegExpStr(){let t=Object.keys(this.#r).sort(sm).map((r)=>{let i=this.#r[r],n=i.buildRegExpStr();return n===""?"":(typeof i.#e==="number"?`(${r})@${i.#e}`:Ia.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 fi=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 xa(e){return Ca[e]??=new RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(t,r)=>r?`\\${r}`:t==="/*"?gi:t==="*"?".*":`/:${mi}`)}$`)}function Ft(e,t){for(let r of Object.keys(e).sort((i,n)=>n.length-i.length))if(xa(r).test(t))return[...e[r]]}var Nt=class{name="RegExpRouter";#t;#e;#r;constructor(){this.#t={["ALL"]:k()},this.#e={["ALL"]:k()},this.#r={["ALL"]:new fi}}#o(e,t){try{this.#r[e].insert(t,!/\*|\/:/.test(t))}catch(r){throw r===ae?new _t(t):r}}add(e,t,r){let i=this.#t,n=this.#e;if(!i)throw Error($t);if(!i[e]){this.#r[e]=new fi;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=xa(t);for(let l of o)if(!i[l][t])this.#o(l,t),i[l][t]=Ft(i[l],t)||Ft(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=Ut(t)||[t];for(let a of s)for(let l of o){if(!n[l][a])this.#o(l,a),n[l][a]=Ft(i[l],a)||Ft(i.ALL,a)||[];n[l][a].push([r,a])}}match=pi;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(([g])=>[g,k()]),Zt];continue}o[m[0]]=p.map(([g,f])=>[g,i.paths[f][1].reduceRight((h,[v],y)=>(h[v]=l[m[1][y][1]],h),k())])}return[s,a.map((d)=>o[d]),n]}};var Ta=class{name="SmartRouter";#t=[];#e=[];constructor(e){this.#t=e.routers}add(e,t,r){if(!this.#e)throw Error($t);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 _t)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 hi=k(),am=0,Ea=class e{#t=[];#e=k();#r=[];#o;#i=hi;insert(t,r,i){let n=this,o=da(r),s=new Set,a=0;for(let l of o){let d=o[++a],u=ua(l,d)||(d===void 0&&l&&l.indexOf("*")===l.length-1?l:null),p=Array.isArray(u),m=p?u[0]:u||l,g=n.#e[m]||=new e;if(u&&!g.#o)g.#o=u,n.#r.push(g);if(n=g,p)s.add(u[1])}n.#t.push({[t]:{handler:i,possibleKeys:[...s],score:++am}})}#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=hi;let n=[this],o=ni(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 f=0,h=n.length;f<h;f++){let v=n[f],y=v.#e[u];if(y)if(y.#i=v.#i,p){if(y.#e["*"])this.#n(i,y.#e["*"],t,v.#i);this.#n(i,y,t,v.#i)}else m.push(y);for(let S of v.#r){let R=S.#o,w=v.#i===hi?{}:{...v.#i};if(typeof R==="string"){if(R==="*"||u.startsWith(R.slice(0,-1))){if(this.#n(i,S,t,v.#i),R==="*")S.#i=w,m.push(S)}continue}let[,C,E]=R;if(!u&&E===!0)continue;if(E!==!0){if(!l){l=[];let ue=r[0]==="/"?1:0;for(let X=0;X<a;X++)l[X]=ue,ue+=o[X].length+1}let B=r.slice(l[d]),Re=E.exec(B);if(Re){if(w[C]=Re[0],this.#n(i,S,t,v.#i,w),Re[0].length===B.length&&S.#e["*"])this.#n(i,S.#e["*"],t,v.#i,w);for(let ue in S.#e){S.#i=w;let X=Re[0].match(/\//g)?.length??0;(s[X]||=[]).push(S);break}continue}}if(E===!0||E.test(u))if(w[C]=u,p){if(this.#n(i,S,t,w,v.#i),S.#e["*"])this.#n(i,S.#e["*"],t,w,v.#i)}else S.#i=w,m.push(S)}}let g=s.shift();n=g?m.concat(g):m}if(i[1])i.sort((d,u)=>d.score-u.score);return[i.map(({handler:d,params:u})=>[d,u])]}};var yi=class{name="TrieRouter";#t=new Ea;add(e,t,r){for(let i of Ut(t)||[t])this.#t.insert(e,i,r)}match(e,t){return this.#t.search(e,t)}};var vi=class extends wa{constructor(e={}){super(e);this.router=e.router??new Ta({routers:[new Nt,new yi]})}};var Ht=(e)=>("server"in e.env)?e.env.server:e.env;var ke=/^\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 bi=(e,t=cm)=>{let r=e.match(/\.([a-zA-Z0-9]+?)$/);if(!r)return;return t[r[1].toLowerCase()]};var cm={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 Aa=(...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 ka={br:".br",zstd:".zst",gzip:".gz"},lm=Object.keys(ka),dm="index.html",Da=(e)=>{let t=e.root??"./",r=e.path,i=e.join??Aa;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=oi(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,dm);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&&bi(a,e.mimes)||bi(a);if(n.header("Content-Type",u||"application/octet-stream"),e.precompressed&&(!u||ke.test(u))){let p=new Set(n.req.header("Accept-Encoding")?.split(",").map((m)=>m.trim()));for(let m of lm){if(!p.has(m))continue;let g=await l(a+ka[m],n);if(g){d=g,n.header("Content-Encoding",m),n.header("Vary","Accept-Encoding",{append:!0});break}}}return await e.onFound?.(a,n),n.body(d)}await e.onNotFound?.(a,n),await o()}};import{stat as um}from"fs/promises";import{join as pm}from"path";var Si=(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 um(s)).isDirectory()}catch{}return a}})(r,i)};var ja="x-hono-disable-ssg",kw=(()=>{try{return new Response("SSG is disabled",{status:404,headers:{[ja]:"true"}})}catch{return null}})();var{write:bI}=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 hm=za((e,t)=>{let r=Ht(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 Ma=(e)=>e===32||e===9||e===10||e===13,Wt=(e,t)=>{while(t<e.length){if(!Ma(e.charCodeAt(t)))break;t++}return t},Je=(e,t)=>{while(t>0){if(!Ma(e.charCodeAt(t-1)))break;t--}return t},Oa=(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]},ym=(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},vm=(e,t)=>{t=Wt(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,Je(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=Wt(e,r),e.charCodeAt(r)===61){let l=Oa(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=Wt(e,r+1),u=e.charCodeAt(d);if(d<e.length&&!(u===59||u===44)){let p=Oa(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,Je(e,r)),l===59)o=!0;r++;break}r++}return[r,i,n??e.slice(a,Je(e,r)),o]},bm=(e,t)=>{let r={type:"",params:Object.create(null),q:1};t=Wt(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,Je(e,i)),i++,a===44)return[i,r.type?r:void 0];if(!r.type)return[ym(e,i),void 0];break}i++}if(!r.type)return r.type=e.slice(t,Je(e,e.length)),[e.length,r.type?r:void 0];let n,o,s;while(i<e.length){if([i,n,o,s]=vm(e,i),n&&o)r.params[n]=o;if(!s)break}return[i,r]},La=(e)=>{if(!e)return[];let t=[],r=0,i,n=!1,o;while(r<e.length)if([r,i]=bm(e,r),i){if(i.q=Sm(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},Sm=(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 Rm=["gzip","deflate"],wm=/(?:^|,)\s*?no-transform\s*?(?:,|$)/i,Im=(e,t)=>{if(e===void 0)return;let r=La(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},Pm=/(?:^|,)\s*accept-encoding\s*(?:,|$)/i,Ua=(e)=>{let t=e?.threshold??1024,r=e?.encoding?[e.encoding]:Rm,i=e?.contentTypeFilter??ke,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)||!Cm(s.res))return;let d=s.res.headers.get("Vary");if(d!=="*"&&!(d&&Pm.test(d)))s.header("Vary",d?`${d}, Accept-Encoding`:"Accept-Encoding");let u=s.req.header("Accept-Encoding"),p=Im(u,r);if(!p||!s.res.body)return;let m=new CompressionStream(p);s.res=new Response(s.res.body.pipeThrough(m),s.res),s.res.headers.delete("Content-Length"),s.res.headers.set("Content-Encoding",p);let g=s.res.headers.get("ETag");if(g&&!g.startsWith("W/"))s.res.headers.set("ETag",`W/${g}`)}},Cm=(e)=>{let t=e.headers.get("Cache-Control");return!t||!wm.test(t)};import{Readable as Ba}from"stream";import{createDeflate as xm,createGzip as Tm}from"zlib";var Em=["gzip","deflate"],Am=/(?:^|,)\s*?no-transform\s*?(?:,|$)/i,$a=(e)=>{if(typeof CompressionStream<"u")return Ua(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||!km(i.res)||!Dm(i.res))return;let s=i.req.header("Accept-Encoding"),a=e?.encoding??Em.find((l)=>s?.includes(l));if(!a||!i.res.body)return;try{let l=a==="gzip"?Tm():xm(),d=Ba.fromWeb(i.res.body).pipe(l),u=Ba.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)}}},km=(e)=>{let t=e.headers.get("Content-Type");return t&&ke.test(t)},Dm=(e)=>{let t=e.headers.get("Cache-Control");return!t||!Am.test(t)};var jm=(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 _a=async(e,t)=>{if(!e)return null;let r=void 0,i,n=0,o=async(a)=>{r=await t(jm(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 g=new Uint8Array(new ArrayBuffer(Math.min(262144,Math.max(p,i.byteLength*2))));g.set(i.subarray(0,n)),i=g}i.set(a.subarray(d),n)}n=p;break}let m=262144-n;if(i?.byteLength!==262144){let g=new Uint8Array(new ArrayBuffer(262144));if(i)g.set(i.subarray(0,n));i=g}i.set(a.subarray(d,d+m),n),await o(i),n=0,d+=m}}if(i&&n>0)await o(i.subarray(0,n));if(!r)return null;return Array.prototype.map.call(new Uint8Array(r),(a)=>a.toString(16).padStart(2,"0")).join("")};var zm=["cache-control","content-location","date","etag","expires","vary"],Za=(e)=>e.replace(/^W\//,"");function Om(e,t){return t!=null&&t.split(",").some((r)=>Za(r.trim())===Za(e))}function Mm(e){if(!e){if(crypto&&crypto.subtle)e=(t)=>crypto.subtle.digest({name:"SHA-1"},t)}return e}var Fa=(e)=>{let t=new Set((e?.retainedHeaders??zm).map((n)=>n.toLowerCase())),r=e?.weak??!1,i=Mm(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 _a(l.clone().body,i);if(u===null)return;d=r?`W/"${u}"`:`"${u}"`}if(a==="*"||Om(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 Ri(e,t){return async(r)=>{let i=r.req.raw,n=i.headers.get("content-type")??"",o=i.headers.get("accept")?.includes("application/json"),s={};if(n.includes("application/json"))s=await i.json();else if(n.includes("form")){let m=await i.formData();for(let[g,f]of m.entries())s[g]=f}let a=await t(e,s),l=typeof a==="object"&&a!==null&&"data"in a?a.data:a,d=Na.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 Ge(e,t){return e===t||e.startsWith(t+Um)}var Ha="public, max-age=31536000, immutable";function Bm(e){return e.getRoutes?.()??[]}var $m=255;class Jt{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(!Ge(n,Z(e)))return;let o=Bun.file(n);if(!await o.exists())return;let s=`<div ${Ja}="${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([...Bm(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??$m,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 ia(e,{drainMs:this.options.shutdownDrainMs??ra,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 vi;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("/*",Fa()),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",Ha);else r.header("Cache-Control",e.defaultCache)}),t.use("/*",async(r,i)=>{if(r.req.path===qt)return r.notFound();return i()}),t.use("/*",this.createCleanUrlMiddleware(e.distDir)),t.use("/*",Si({root:e.distDir})),t.get(Wa,(r)=>r.body(qa,200,{"Content-Type":"image/svg+xml; charset=utf-8","Cache-Control":"public, max-age=86400"})),t.notFound(async(r)=>{let i=Bun.file(Lm(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=na(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 wi&&s.slot)return await this.fillSitePage(t.distDir,i,s)??s;if(r==="GET"&&s instanceof wi&&s.status===200){let a=Z(t.distDir,`.${i}`,"index.html");if(Ge(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 Ri({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(!Ge(i,this.options.sharedImagesDir))return null;let n=Bun.file(i);if(!await n.exists())return null;return new Response(n,{headers:{"Cache-Control":Ha}})}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(!Ge(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(Ge(s,e)){let a=Bun.file(s);if(await a.exists())return t.html(await a.text())}await r()}}}function Ii(e,t){return(r,i)=>e.send({type:Gt.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:Ga(t,"anonymous")}},sender:t})}var Pi=`<!DOCTYPE html>
10
+ `):Tu}formatRelevantEntity(e,t){let{entity:r,excerpt:i}=e,n=r.entityType,o=Cu.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 ku=c.object({entityType:c.string(),query:c.object({id:c.string()})});class gt{entityService;id=Or.ENTITIES;name="Entity DataSource";description="Fetches entity content from the entity service";constructor(e){this.entityService=e}async fetch(e,t,r){let i=ku.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 An(e,t){e.dataSourceRegistry.register(new mt(e.aiService,e.entityService,e.templateRegistry,()=>e.identityService.getCharacterContent(),()=>e.profileService.getProfileContent(),new ft(t.entityDisplay),t.siteBaseUrl)),e.dataSourceRegistry.register(new gt(e.entityService)),e.logger.debug("Core DataSources registered")}async function kn(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 Dn={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 jn={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 zn={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 On={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 Mn={lexicon:1,id:"ai.rizom.brain.post",defs:{main:{type:"record",description:"Markdown blog post distributed by a Rizom brain.",key:"any",record:{type:"object",required:["title","body","createdAt"],properties:{title:{type:"string",maxLength:300},summary:{type:"string",maxLength:2000},body:{type:"string",maxLength:1e5},format:{type:"string",knownValues:["text/markdown"]},brainDid:{type:"string"},anchorDid:{type:"string"},canonicalUrl:{type:"string",format:"uri"},topics:{type:"array",items:{type:"string"},maxLength:50},coverImage:{type:"ref",ref:"#coverImage"},series:{type:"string",maxLength:200},seriesIndex:{type:"integer"},sourceEntityType:{type:"string",knownValues:["post"]},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},publishedAt:{type:"string",format:"datetime"}}}},coverImage:{type:"object",description:"Cover image attached to the post.",required:["blob"],properties:{blob:{type:"blob"},alt:{type:"string",maxLength:1000},width:{type:"integer"},height:{type:"integer"}}}}};var Ln={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 Un={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 Bn={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 $n={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 _n=c.object({type:c.string()}).catchall(c.unknown()),_u=c.object({type:c.literal("object"),description:c.string().optional(),required:c.array(c.string()).optional(),properties:c.record(c.string(),_n)}),Zu=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(),_n)})})}).catchall(_u)});function _(e){return Zu.parse(e)}var z={"ai.rizom.brain.card":_(Dn),"ai.rizom.brain.deck":_(jn),"ai.rizom.brain.link":_(zn),"ai.rizom.brain.note":_(On),"ai.rizom.brain.post":_(Mn),"ai.rizom.brain.project":_(Ln),"ai.rizom.brain.series":_(Un),"ai.rizom.brain.socialPost":_(Bn),"ai.rizom.brain.topic":_($n)},Fu="Additive optional fields are compatible; required-field, type, or constraint changes require a migration plan or new NSID.";function q(e){return{status:"approved",version:"1.0.0",revision:1,owner:"Rizom",steward:"Rizom protocol registry",projectionPackage:e,compatibility:Fu}}var Zn={"ai.rizom.brain.card":q("@brains/atproto"),"ai.rizom.brain.deck":q("@brains/decks"),"ai.rizom.brain.link":q("@brains/link"),"ai.rizom.brain.note":q("@brains/note"),"ai.rizom.brain.post":q("@brains/blog"),"ai.rizom.brain.project":q("@brains/portfolio"),"ai.rizom.brain.series":q("@brains/series"),"ai.rizom.brain.socialPost":q("@brains/social-media"),"ai.rizom.brain.topic":q("@brains/topics")};function Nu(){return Object.values(z)}function Hu(e){if(!Lr(z,e))return;return z[e]}function Wu(){return Mr(Zn).map(([e,t])=>({id:e,...t}))}var qu=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;function Ju(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)=>qu.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 Gu(e,t){if(typeof e!=="string"||!e.startsWith("#"))return;let r=t[e.slice(1)];return r?.type==="object"?r:void 0}function Nn(e,t){switch(e.type){case"string":return Ju(e);case"integer":return c.number().int();case"boolean":return c.boolean();case"array":{let r=e.items?Nn(e.items,t):c.unknown(),i=c.array(r);if(e.maxLength!==void 0)i=i.max(e.maxLength);return i}case"object":return Fn(e,t);case"ref":{let r=Gu(e.ref,t);if(!r)return c.custom(()=>!1,{message:`unresolvable lexicon ref ${String(e.ref)}`});return c.lazy(()=>Fn(r,t))}case"blob":return c.custom(re,{message:"expected blob"});default:return c.unknown()}}function Hn(e,t){let r=new Set(e.required??[]),i={};for(let[n,o]of Object.entries(e.properties??{})){let s=Nn(o,t);i[n]=r.has(n)?s:s.optional()}return i}function Fn(e,t){return c.strictObject(Hn(e,t))}function U(e){return c.strictObject({...Hn(e.defs.main.record,e.defs),$type:c.literal(e.id).optional()})}var Ur={"ai.rizom.brain.card":U(z["ai.rizom.brain.card"]),"ai.rizom.brain.deck":U(z["ai.rizom.brain.deck"]),"ai.rizom.brain.link":U(z["ai.rizom.brain.link"]),"ai.rizom.brain.note":U(z["ai.rizom.brain.note"]),"ai.rizom.brain.post":U(z["ai.rizom.brain.post"]),"ai.rizom.brain.project":U(z["ai.rizom.brain.project"]),"ai.rizom.brain.series":U(z["ai.rizom.brain.series"]),"ai.rizom.brain.socialPost":U(z["ai.rizom.brain.socialPost"]),"ai.rizom.brain.topic":U(z["ai.rizom.brain.topic"])};function Qu(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(!re(r))return;r=r[String(i)]}return r}function Ku(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"&&Qu(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 Vu(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(Ku(e,t,i))}var Wn="atproto:brain-card-discovered",qn="atproto:brain-discovered",Jn="atproto:brain-card-refreshed",Gn="atproto:brain-card-unavailable",Qn="atproto:brain-card-conflict",Kn="atproto:jetstream-gap",Yu=c.custom((e)=>Ur["ai.rizom.brain.card"].safeParse(e).success),Vn=c.object({repoDid:c.string().min(1),uri:c.string().min(1),cid:c.string().min(1),record:Yu}).strict(),Br=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(),Yn=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(),Xn=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(),eo=c.object({previousCursorTimeUs:c.number().int().nonnegative(),clampedCursorTimeUs:c.number().int().nonnegative(),observedAt:c.string().datetime()}).strict(),Xu=ge(Wn,Vn),ep=ge(qn,Br),tp=ge(Jn,Br),rp=ge(Gn,Yn),ip=ge(Qn,Xn),np=ge(Kn,eo);class ht{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 op({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 vt(e,t,r){let i=await yt(e,to,{actor:r},t);if(i.status==="unavailable")return null;if(i.status==="failed")throw ro(i.error,`Principal resolution failed: ${i.error.message}`);return i.data.principal}function no(e,t){return new io(e,(r)=>vt(t,"shell:content-service",r))}var $r=x.Service("@brains/conversation-service/ConversationService");function sp(e){if(e.service){let r=e.service;return{service:r,close:()=>r.close()}}let t=oo.createFreshFromConfig(e.logger,e.messageBus,e.dbConfig);try{return{service:t,close:()=>t.close()}}catch(r){throw t.close(),r}}function so(e){return ie($r,()=>sp(e))}var _r=x.Service("@brains/entity-service/EntityService");function ap(e){return"close"in e&&typeof e.close==="function"}function co(e){return ie(_r,()=>{let t=e.service??ao.createFresh(e);return{service:t,close:()=>{if(ap(t))t.close()}}})}var _e=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()}),Zr=c.strictObject({alerts:c.array(_e).optional()});var bt="shell:recurring-check",Nr=86400000,cp=7*Nr,lp=3*Nr,dp=c.strictObject({checkId:c.string().min(1)}),up=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:_e,observedAt:c.string().datetime(),includeInInbox:c.boolean().optional(),deliveredAt:c.string().datetime().optional(),resolvedAt:c.string().datetime().optional()})]);class Rt{brainId;scheduler;state;jobQueue;delivery;logger;clock;checks=new Map;pluginChecks=new Map;alertOperations=new mo;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:up});let t={validateAndParse:(r)=>{let i=dp.safeParse(r);return i.success?i.data:null},process:async(r)=>{await this.runNow(r.checkId)}};this.jobQueue.registerHandler(bt,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(bt),this.handlerRegistered=!1}namespace(e){return{register:(t)=>this.register(e,t)}}register(e,t){gp(e),go(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=Zr.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=b.tryPromise({try:(a)=>(i=n(a),i),catch:(a)=>a}),s=await b.runPromiseExit(o,{signal:t});if(i)await Promise.allSettled([i]);if(D.isSuccess(s))return!0;if(t.aborted)throw t.reason;throw ne.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=St(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=St(this.brainId,r.id,r.cadence),n=Fr(this.currentTime(),i).getTime()+i.periodMs,o=new AbortController,s={controller:o,settled:Promise.resolve()};e.enqueueRetry=s,s.settled=lo(()=>this.enqueue(r.id),t,{firstDelayMs:uo,maxDelayMs:po,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=St(this.brainId,t.id,t.cadence),n=Fr(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:bt,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=_e.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:pp(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:${J(e)}`}alertKeyPrefix(e){return`alert:${J(e)}:`}alertKey(e,t){return`${this.alertKeyPrefix(e)}${J(t)}`}}function pp(e,t){return`recurring-alert:${J(`${e}\x00${t}`)}`}function St(e,t,r){let i=r==="daily"?Nr:cp,n=i/60000,o=J(`${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:lp}}function Fr(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 mp=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*:[a-z][a-z0-9-]*$/;function gp(e){if(e.length<=200&&mp.test(e))return;go(e,"plugin ID")}function go(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 I=fo("runtime_state_records",{namespace:wt("namespace").notNull(),key:wt("key").notNull(),value:wt("value",{mode:"json"}).notNull(),createdAt:Hr("created_at").notNull(),updatedAt:Hr("updated_at").notNull()},(e)=>({pk:yo({columns:[e.namespace,e.key]}),namespaceUpdatedAtIdx:ho("idx_runtime_state_namespace_updated_at").on(e.namespace,e.updatedAt)}));function bo(e){return vo({url:e.url,schema:{runtimeStateRecords:I},authToken:e.authToken,authTokenEnv:"RUNTIME_STATE_DATABASE_AUTH_TOKEN"})}function It(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 fp}from"util";var hp=/^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,511}$/,Po=512;class Wr{db;namespace;schema;now;constructor(e,t,r,i=()=>new Date){yp(t),this.db=e,this.namespace=t,this.schema=r,this.now=i}async get(e){let t=fe(e),i=(await this.db.select().from(I).where(oe(O(I.namespace,this.namespace),O(I.key,t))).limit(1))[0];if(!i)return null;return this.schema.parse(i.value)}async has(e){let t=fe(e);return(await this.db.select({key:I.key}).from(I).where(oe(O(I.namespace,this.namespace),O(I.key,t))).limit(1)).length>0}async set(e,t){let r=fe(e),i=It(this.schema,t),n=i===null?he`'null'`:i,o=this.now().getTime();await this.db.insert(I).values({namespace:this.namespace,key:r,value:n,createdAt:o,updatedAt:o}).onConflictDoUpdate({target:[I.namespace,I.key],set:{value:n,updatedAt:o}})}async setIfNotExists(e,t){let r=fe(e),i=It(this.schema,t),n=i===null?he`'null'`:i,o=this.now().getTime(),s=await this.db.insert(I).values({namespace:this.namespace,key:r,value:n,createdAt:o,updatedAt:o}).onConflictDoNothing({target:[I.namespace,I.key]});return Number(s.rowsAffected)>0}async compareAndSet(e,t,r){let i=fe(e),n=It(this.schema,r),[o]=await this.db.select({value:I.value}).from(I).where(oe(O(I.namespace,this.namespace),O(I.key,i))).limit(1);if(!o||!fp(this.schema.parse(o.value),t))return!1;let s=o.value===null?he`'null'`:o.value,a=n===null?he`'null'`:n,l=await this.db.update(I).set({value:a,updatedAt:this.now().getTime()}).where(oe(O(I.namespace,this.namespace),O(I.key,i),O(I.value,s)));return Number(l.rowsAffected)===1}async delete(e){let t=fe(e),r=await this.db.delete(I).where(oe(O(I.namespace,this.namespace),O(I.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(I).where(oe(O(I.namespace,this.namespace),So(e.keyPrefix)));return Number(t.rowsAffected)}async listRows(e){let{keyPrefix:t,afterKey:r,limit:i}=e;if(r!==void 0)fe(r);if(i!==void 0)c.number().int().min(1).max(1000).parse(i);let n=this.db.select({...Ro(I),key:he`CAST(${I.key} AS BLOB)`.mapWith((o)=>new TextDecoder("utf-8",{fatal:!0}).decode(o))}).from(I).where(oe(O(I.namespace,this.namespace),So(t),r!==void 0?wo(I.key,r):void 0)).orderBy(Io(I.key)).$dynamic();return i===void 0?n:n.limit(i)}}function yp(e){if(!hp.test(e))throw Error(`Invalid runtime state namespace: ${e}. Use 1-512 alphanumeric, _, ., :, or - characters.`)}function fe(e){if(e.length===0||e.length>Po)throw Error("Runtime state keys must be 1-512 characters long");return e}function So(e){if(e===void 0)return;return vp(e),he`substr(CAST(${I.key} AS BLOB), 1, length(CAST(${e} AS BLOB))) = CAST(${e} AS BLOB)`}function vp(e){if(e.length>Po)throw Error("Runtime state key prefixes must be 512 characters or shorter");return e}class Pt{db;client;logger;databaseUrl;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;static createFresh(e,t){return new Pt(e,t??Pe.getInstance())}constructor(e,t){let{db:r,client:i,url:n}=bo(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 Co(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 Wr(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=x.Service("@brains/runtime-state/RuntimeStateService");function xo(e){return ie(qr,()=>{let t=e.service??Pt.createFresh(e.config,e.logger);return{service:t,close:()=>t.close()}})}async function Jr(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=Ze(r),t.warn(`Daemon ${e.name} failed to start: ${P(r)}`),r}}async function Gr(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=Ze(r),t.error(`Failed to stop daemon: ${e.name}`,r),r}}async function To(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 Eo(e){return{name:e.name,pluginId:e.pluginId,status:e.status,health:e.health}}class Ct{daemons=new Map;daemonScopes=new Map;daemonTransitions=new Map;logger;static createFresh(e){return new Ct(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 Jr(t,this.logger);return}let r=b.runSync(j.make()),i=b.acquireRelease(b.promise(()=>Jr(t,this.logger)),()=>b.promise(()=>Gr(t,this.logger)));try{await b.runPromise(j.provide(i,r)),this.daemonScopes.set(e,r)}catch(n){throw await b.runPromise(j.close(r,D.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 Gr(t,this.logger);return}this.daemonScopes.delete(e),await b.runPromise(j.close(r,D.void))}async checkHealth(e){let t=this.daemons.get(e);if(!t)throw Error(`Daemon not registered: ${e}`);return To(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(Eo)}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??=Ze(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 bp=c.object({projectionId:c.string().min(1),reason:c.string().min(1),openedAt:c.number().int().nonnegative(),expiresAt:c.number().int().nonnegative()}),Sp=8,Rp=32,wp=128,Ip=5,Pp=600000,Cp=600000,xp=1000,Tp="shell.projection-circuits";class xt{operationContext;options;circuitStore;roots=new Map;reservedJobs=new Map;circuits=new Map;projections;static createFresh(e,t={}){return new xt(e,t)}constructor(e,t){this.operationContext=e,this.options={maxDerivationDepth:t.maxDerivationDepth??Sp,maxJobsPerRoot:t.maxJobsPerRoot??Rp,maxMutationsPerRoot:t.maxMutationsPerRoot??wp,repeatedTargetLimit:t.repeatedTargetLimit??Ip,retentionMs:t.retentionMs??Pp,circuitOpenMs:t.circuitOpenMs??Cp,maxTrackedRoots:t.maxTrackedRoots??xp,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:Tp,schema:bp})}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 Ep={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 Ce(e){return Ep[e??"combined"]}var Ao=[Tt.created,Tt.updated,Tt.deleted];function ko(e,t,r){let i=Ao.map((o)=>e.subscribe(o,(s)=>(t.send({type:o,payload:s.payload}),{success:!0}))),n=t.onEvent((o)=>{if(!Ao.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 Ap=20,kp=0.5,Dp=0.06,jp=5;function jo(e){return async({answer:t})=>{let i=(await e.entityService.search({query:t,options:{limit:Ap,minScore:kp,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-Dp).slice(0,jp).map(({entity:o})=>Do(o,e))}}function zp(e,t,r,i,n){return[Lo,Uo,Bo].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 zo(e,t,r,i){return zp(e,t,t,async()=>{await r(),await Te(e,$o,{entityType:t},"shell")},i)}async function Op(e,t,r){let i=Mp(e.kind);if(!i)return null;try{let n=t.scoped({namespace:i,refKind:e.kind,routePath:""});return Lp(await n.read(e.id),e)}catch(n){return r.debug("Skipped unavailable prior runtime upload",{uploadKind:e.kind,uploadId:e.id,error:P(n)}),null}}function Mp(e){return e===xe.refKind?xe.namespace:null}function Lp(e,t){let{record:r,content:i}=e;if(Up(r.mediaType))return{kind:"text",filename:r.filename,mediaType:r.mediaType,content:new TextDecoder("utf-8").decode(i).replace(/^\uFEFF/,""),sizeBytes:r.sizeBytes,source:t};return{kind:"file",filename:r.filename,mediaType:r.mediaType,data:new Uint8Array(i),sizeBytes:r.sizeBytes,source:t}}function Up(e){let t=e.toLowerCase();return t.startsWith("text/")||t==="application/json"}function Go(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=Wo.createFresh(r,i,t.identity);d.push(...zo(n,M.BRAIN_CHARACTER,()=>p.refreshCache(),i));let m=qo.createFresh(r,i,t.profile),g=Jo.createFresh(i,async(R)=>{let w=await vt(n,"shell:canonical-identity-service",R).catch(()=>null);if(!w?.canonicalId)return null;return{userId:w.userId,canonicalId:w.canonicalId,displayName:w.displayName}}),f=Ho({guestPricing:_o(o.getConfig().model),model:o.getModel(),answerModel:o.getAnswerModel?.(),modelId:o.getConfig().model,webSearch:o.getConfig().webSearch,temperature:o.getConfig().temperature,reasoningEffort:o.getConfig().reasoningEffort,messageBus:n}),h=Zo(t.name),v=new ft(t.entityDisplay),y={isCitable:(R)=>v.isCitable(R),urlFor:(R,w)=>v.generateUrl(R,w),siteBaseUrl:t.siteBaseUrl},S=Fo.createFresh(s,a,p,m,i,{agentFactory:f,turnEvents:No(n),canonicalIdentityResolver:g,entityLinks:y,...e.generationUsage?{generationUsage:e.generationUsage}:{},...e.embeddingUsage?{embeddingUsage:e.embeddingUsage}:{},...t.embedding.enabled?{indexReadiness:r,guestAnswerSources:jo({entityService:r,...y})}:{},uploadAttachmentResolver:(R)=>Op(R,l,i),guestAskedBefore:async(R)=>{let w=await Fe(n,Oo,R,"shell:agent-service");return w.status==="answered"?w.answers.find((C)=>C.hit)?.hit:void 0},agentContextProvider:async(R)=>{let w=await Fe(n,Mo,R,"shell:agent-service");return w.status==="answered"?w.answers.flatMap((C)=>C.items):[]},...h?{assistantAgentId:h}:{},...t.agentInstructions&&{agentInstructions:t.agentInstructions}});if(d.push(...zo(n,M.ANCHOR_PROFILE,()=>m.refreshCache(),i)),!u)d.push(n.subscribe(Ne.identityChanged,async()=>(S.invalidateAgent(),{success:!0})));return{identityService:p,profileService:m,canonicalIdentityService:g,agentService:S}}var He=x.Service("@brains/job-queue/JobQueueService"),Et=x.Service("@brains/job-queue/BatchJobManager"),At=x.Service("@brains/job-queue/JobProgressMonitor"),kt=x.Service("@brains/job-queue/JobQueueWorker");function Xo(e){return ie(He,()=>{let t=e.service??Qo.createFresh(e.config,e.logger,{...e.operationContext&&{operationContext:e.operationContext},...e.projectionAdmission&&{projectionAdmission:e.projectionAdmission},...e.handlerRegistrationMode&&{handlerRegistrationMode:e.handlerRegistrationMode}});return{service:t,close:()=>t.close()}})}function es(e){let t=!1,r=b.gen(function*(){let i=yield*He,n=e.batchJobManager??Vo.createFresh(i,e.logger),o=e.jobProgressMonitor??Yo.createFresh(i,e.messageBus,n,e.logger,e.progressMonitorMode),s=e.jobQueueWorker??Ko.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 x.make(Et,n).pipe(x.add(At,o),x.add(kt,s))});return{layer:G.effectContext(b.acquireRelease(r,(i)=>t?b.void:Bp(i))),abandon:()=>{t=!0}}}function Bp(e){let t=x.get(e,kt),r=x.get(e,At),i=x.get(e,Et);return b.gen(function*(){let n=yield*b.exit(b.tryPromise({try:()=>t.stop(),catch:(l)=>l})),o=yield*b.exit(b.tryPromise({try:()=>r.stop(),catch:(l)=>l})),s=yield*b.exit(b.tryPromise({try:async()=>{await i.stop()},catch:(l)=>l})),a=[n,o,s].find(D.isFailure);if(a)yield*b.die(ne.squash(a.cause))})}function $p(e,t=(r)=>process.exit(r)){return(r)=>{e.error("Job queue worker requires process restart",{reason:r,exitCode:1}),t(1)}}function Dt(e){let t=b.runSyncExit(j.close(e,D.void));if(D.isFailure(t))throw ne.squash(t.cause)}function ts(e){let t=e.operationContext??jt.createFresh(),r=b.runSync(j.make()),i,n;try{let o=b.runSync(G.buildWithScope(Xo({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=x.get(o,He),a=b.runSync(j.make());i=a;let l=es({messageBus:e.messageBus,logger:e.logger,operationContext:t,...e.projectionBatchScope&&{projectionBatchScope:e.projectionBatchScope},onWorkerUnhealthy:$p(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=b.runSync(G.buildWithScope(l.layer.pipe(G.provide(G.succeed(He,s))),a)),u=x.get(d,Et),p=x.get(d,At),m=x.get(d,kt),g,f=!1,h=!1;return{batchJobManager:u,jobProgressMonitor:p,jobQueueService:s,jobQueueWorker:m,closeRuntime:()=>(f=!0,g??=b.runPromise(j.close(a,D.void)),g),rollbackRuntime:()=>{if(f)return;f=!0,l.abandon(),Dt(a)},closeDatabase:()=>{if(h)return;h=!0,Dt(r)}}}catch(o){if(i)try{n?.abandon(),Dt(i)}catch(s){e.logger.warn("Failed to release partial job runtime acquisition",s)}try{Dt(r)}catch(s){e.logger.warn("Failed to release partial job database acquisition",s)}throw o}}function ns(e){return e.scoped({namespace:"shell.legacy-binary-content",schema:is})}var _p=8;class Qr{store;logger;flushDelayMs;now;pending=new Map;timer;writing=Promise.resolve();constructor(e){this.store=e.store,this.logger=e.logger.child("LegacyBinaryLedger"),this.flushDelayMs=e.flushDelayMs??1000,this.now=e.now??(()=>new Date)}record(e){let t=`${e.method}:${e.entityType}`,r=this.now().toISOString(),i=this.pending.get(t);if(this.pending.set(t,{method:e.method,entityType:e.entityType,count:(i?.count??0)+1,firstAt:i?.firstAt??r,lastAt:r}),this.timer)return;this.timer=setTimeout(()=>{this.timer=void 0,this.flush()},this.flushDelayMs),this.timer.unref()}flush(){return clearTimeout(this.timer),this.timer=void 0,this.writing=this.writing.then(()=>this.writePending()),this.writing}async list(){return await this.flush(),(await this.store.list()).map((t)=>t.value).sort((t,r)=>t.method.localeCompare(r.method)||t.entityType.localeCompare(r.entityType))}dispose(){clearTimeout(this.timer),this.timer=void 0}async writePending(){let e=[...this.pending];this.pending=new Map,await Promise.all(e.map(async([t,r])=>{try{await this.fold(t,r,1)}catch(i){this.keep(t,r),this.logger.warn("Could not record legacy binary content use",{method:r.method,entityType:r.entityType,error:P(i)})}}))}async fold(e,t,r){let i=await this.store.get(e);if(i?await this.store.compareAndSet(e,i,rs(i,t)):await this.store.setIfNotExists(e,t))return;if(r>=_p)throw Error("other processes kept changing the count");await this.fold(e,t,r+1)}keep(e,t){let r=this.pending.get(e);this.pending.set(e,r?rs(t,r):t)}}function rs(e,t){return{method:e.method,entityType:e.entityType,count:e.count+t.count,firstAt:e.firstAt<t.firstAt?e.firstAt:t.firstAt,lastAt:e.lastAt>t.lastAt?e.lastAt:t.lastAt}}function ss(e){return{deliver:async(t,{idempotencyKey:r})=>{let i=await yt(e,os,{title:t.title,body:t.body,...t.html?{html:t.html}:{},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 cs(e){return{sourceId:"recurring-checks",displayName:"Recurring checks",list:async()=>(await e.listOpenAlerts()).map((t)=>({id:t.id,title:as(t.title,160),summary:as(t.body,1000),receivedAt:t.observedAt,urgency:"high",actions:[{id:"resolve",label:"Dismiss",confirm:!0}]})),act:async(t,r,i)=>{if(i.permissionLevel!=="admin")throw Error("Admin permission required");if(r!=="resolve")throw Error("Invalid recurring-check inbox action");await e.resolveOpenAlert(t)}}}function as(e,t){return e.length<=t?e:e.slice(0,t)}function ls(e,t){if(t)return t;let r={debug:We.DEBUG,info:We.INFO,warn:We.WARN,error:We.ERROR}[e.logging.level];return Pe.createFresh({level:r,context:e.logging.context,format:e.logging.format==="json"?"json":"text",...e.logging.file?{logFile:e.logging.file}:{}})}function Kr(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 Ee(e){return{url:e.url,...e.authToken?{authToken:e.authToken}:{}}}function Us(e){let{config:t,dependencies:r,initializerLogger:i,lifecycle:n,processRole:o,peerChannel:s}=e;i.debug("Initializing Shell services");let a=Ce(o),l=ls(t,r?.logger),d=r?.operationContext??jt.createFresh(),u=[],p=ks.createFresh(!r?.embeddingService),m=r?.embeddingService??As.createFresh({providerKeys:t.ai.providerKeys,profile:Ts(t.ai.embeddingModel),runtimeUrl:t.ai.modelRuntimeUrl,logger:l,usage:p}),g=Ds.createFresh(),f=r?.aiService??Es.createFresh(Kr(t),l,g),h=r?.entityRegistry??ps.createFresh(l),v=r?.messageBus??us.createFresh(l,d);if(s)u.push(ko(v,s,l));let y=r?.templateRegistry??gs.createFresh(l),S=r?.dataSourceRegistry??ms.createFresh(l),R=r?.renderService??hs.createFresh(y),w=r?.daemonRegistry??Ct.createFresh(l),C=r?.pluginManager??Os.createFresh(l,w),E=r?.permissionService??new fs(t.permissions,{spaces:t.spaces,entityActionFloor:(L)=>h.getEntityTypeConfig(L).actionPolicy}),B=r?.profileKindRegistry??new zs(t.profileKind),Re=r?.channelRegistry??new Ss,ue=r?.inboxRegistry??new ws,ee=r?.inboxFollowUpRegistry??new Is(l),Qd=r?.operationalHealthRegistry??new js,Kd=r?.accountSettingsRegistry??new bs,Vd=new Rs,Yd=new ht,Xd=r?.attachmentRegistry??Ps.createFresh(),gn=r?.runtimeUploadRegistry??Cs.createFresh({dataDir:t.dataDir,logger:l}),eu=n.buildLayer(xo({config:Ee(t.runtimeStateDatabase),logger:l,...r?.runtimeStateService&&{service:r.runtimeStateService}})),ot=x.get(eu,qr),Ir=new Qr({store:ns(ot),logger:l});n.addSyncFinalizer(()=>Ir.dispose());let Pr=r?.projectionRuntimeSupervisor??xt.createFresh(d,{runtimeState:ot}),fn=r?.mcpService??xs.createFresh(v,l),Cr={},tu={runFreshBatchScope:(L)=>Cr.current?Cr.current.runFreshBatchScope(L):L()},st=ts({dependencies:r,jobQueueConfig:{...Ee(t.jobQueueDatabase),brainVersion:t.version},workerConcurrency:t.jobQueue.workerConcurrency,messageBus:v,operationContext:d,projectionBatchScope:tu,projectionAdmission:Pr,handlerRegistrationMode:a.handlerRegistrationMode,progressMonitorMode:a.progressMonitorMode,logger:l}),{batchJobManager:ru,jobProgressMonitor:iu,jobQueueService:xr,jobQueueWorker:nu}=st;n.addSyncFinalizer(()=>st.closeDatabase()),n.addSyncFinalizer(()=>st.rollbackRuntime());let Me=r?.recurringCheckService??new Rt({brainId:t.siteBaseUrl??t.dataDir,scheduler:new Ms,runtimeState:ot,clock:b.runSync(ds.Clock),jobQueue:xr,logger:l,delivery:ss(v)});n.addSyncFinalizer(()=>Me.abandon()),ue.registerSource("shell.recurring-checks",cs(Me)),n.addSyncFinalizer(()=>ue.unregisterPlugin("shell.recurring-checks"));let hn=(L,Er)=>{if(!a.serves)return;w.register(L,Er,"shell"),n.addSyncFinalizer(()=>w.abandon(L))};hn("shell:recurring-checks",{start:()=>Me.start(),stop:()=>Me.stop()});let ou=n.buildLayer(co({embeddingService:m,embeddingsEnabled:t.embedding.enabled,entityRegistry:h,logger:l,jobQueueService:xr,messageBus:v,mutationAdmission:Pr,onLegacyBinaryMaterialization:(L)=>Ir.record(L),...r?.projectionRuntime?.now&&{projectionNow:r.projectionRuntime.now},dbConfig:Ee(t.database),embeddingDbConfig:Ee(t.embeddingDatabase),...r?.entityService&&{service:r.entityService}})),at=x.get(ou,_r);Cr.current=at.getProjectionStore();let su=n.buildLayer(so({dbConfig:Ee(t.conversationDatabase),logger:l,messageBus:v,...r?.conversationService&&{service:r.conversationService}})),Tr=x.get(su,$r);hn("shell:guest-retention",Ls({intervalMs:60000,logger:l,run:async()=>{await Tr.deleteExpiredGuestConversations(100)}})),n.addSyncFinalizer(()=>{for(let L of u.splice(0))try{L()}catch(Er){l.warn("Failed to dispose shell subscription",Er)}});let yn=no(E,v),au=r?.contentService??new vs({logger:l,entityService:at,aiService:f,templateRegistry:y,dataSourceRegistry:S,generationAuthorizer:new ys(E,yn)}),{identityService:cu,profileService:lu,canonicalIdentityService:du,agentService:uu}=Go({config:t,entityService:at,embeddingService:m,embeddingUsage:p,...!r?.aiService?{generationUsage:g}:{},entityRegistry:h,logger:l,messageBus:v,aiService:f,mcpService:fn,conversationService:Tr,runtimeUploadRegistry:gn,disposables:u,executionOnly:!a.serves});return{logger:l,operationContext:d,projectionRuntimeSupervisor:Pr,disposables:u,entityRegistry:h,messageBus:v,renderService:R,daemonRegistry:w,pluginManager:C,templateRegistry:y,dataSourceRegistry:S,mcpService:fn,embeddingService:m,entityService:at,aiService:f,conversationService:Tr,contentService:au,callerAuthorizer:yn,jobQueueService:xr,jobQueueWorker:nu,batchJobManager:ru,jobProgressMonitor:iu,jobServicesLifecycle:st,permissionService:E,identityService:cu,profileService:lu,canonicalIdentityService:du,profileKindRegistry:B,channelRegistry:Re,inboxRegistry:ue,inboxFollowUpRegistry:ee,operationalHealthRegistry:Qd,accountSettingsRegistry:Kd,authRegistry:Vd,atprotoProjectionRegistry:Yd,agentService:uu,attachmentRegistry:Xd,runtimeUploadRegistry:gn,runtimeStateService:ot,legacyBinaryLedger:Ir,recurringCheckService:Me}}function Ns(e,t){e.register(Vr.name,Vr),t.debug("Shell system templates registered")}function Hs(e,t){e.register($e.BASE_ENTITY_DISPLAY,{name:"base-entity-display",description:"Display template for base entities",schema:Yr,formatter:new Bs,requiredPermission:"public"}),t.debug("Base entity display template registered")}function Ws(e,t){e.registerEntityType(M.NOTE,Yr,new $s,{projectionSourceRole:"primary"}),t.debug("Fallback base entity adapter registered")}function qs(e,t){let r=new _s;e.registerEntityType(M.BRAIN_CHARACTER,r.schema,r,{classification:"system",projectionSource:!1,projectionSourceRole:"excluded"}),t.debug("Brain character entity support registered")}function Js(e,t){let r=new Zs;e.registerEntityType(M.ANCHOR_PROFILE,r.schema,r,{classification:"system",projectionSourceRole:"canonical"}),t.debug("Anchor profile entity support registered")}async function Gs(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 Fs||d?.requiresDaemonStartup?.())throw l}i.debug("Plugin initialization complete")}class zt{logger;config;processRole;peerChannel;static createFresh(e,t,r,i){return new zt(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){Ns(e,this.logger)}registerBaseEntityDisplayTemplate(e){Hs(e,this.logger)}registerFallbackBaseEntity(e){Ws(e,this.logger)}registerBrainCharacterSupport(e){qs(e,this.logger)}registerAnchorProfileSupport(e){Js(e,this.logger)}async initializePlugins(e,t){await Gs({plugins:this.config.plugins,pluginManager:e,logger:this.logger,initOptions:t})}initializeServices(e,t){return Us({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=Ks.createFresh(t,r);e.registerHandler(Qs.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(M.NOTE))this.registerFallbackBaseEntity(t);this.logger.debug("Shell registration phase complete")}catch(n){throw this.logger.error("Shell initialization failed",n),n}}}var Xr=c.strictObject({waveId:c.string().trim().min(1),ruleId:c.string().trim().min(1)});class ei{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=Xr.safeParse(e);return t.success?t.data:null}async onTerminalError(e,t,r){let i=Xr.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=Xr.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((C)=>C.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 C=await this.store.listPendingInputs();return await this.recordDiagnostic({...p,event:"apply-completed",applyOutcome:"superseded",highestPendingGeneration:Ot(C)}),{waveId:n.waveId,ruleId:o.id,outcome:"superseded",inputFingerprint:null,changedTargets:[]}}if(await this.store.supersedeWaveIfStale(n.waveId,this.now())){let C=await this.store.listPendingInputs();return await this.recordDiagnostic({...p,event:"apply-completed",applyOutcome:"superseded",highestPendingGeneration:Ot(C)}),await this.coordinator.continueAfterSupersession(n.waveId),{waveId:n.waveId,ruleId:o.id,outcome:"superseded",inputFingerprint:null,changedTargets:[]}}let m=Np(s,a,u.level),g=await o.selectInput({waveId:n.waveId,inputs:m},this.inputContext,i),f=o.fingerprint(g),h={...p,inputFingerprint:f,selectedSourceCount:Fp(g,m)};await this.recordDiagnostic({...h,event:"input-selected"});let v={ruleId:o.id,ruleVersion:o.version,inputFingerprint:f},y=await this.store.getRuleMemo(v);await this.recordDiagnostic({...h,event:"memo-resolved",memoHit:y!==null});let S;if(y)S=y.writeIntents;else{await this.recordDiagnostic({...h,event:"derive-started",memoHit:!1});try{S=await o.derive(g,this.executionContext,i),await this.recordDiagnostic({...h,event:"derive-completed",memoHit:!1})}catch(C){throw await this.recordDiagnostic({...h,event:i.aborted?"derive-cancelled":"derive-failed",memoHit:!1}),C}}let R=await this.store.applyRuleResult({waveId:n.waveId,ruleId:o.id,ruleVersion:o.version,inputFingerprint:f,writeIntents:S,completedAt:this.now()}),w=await this.store.listPendingInputs();if(!R)return await this.recordDiagnostic({...h,event:"apply-completed",memoHit:y!==null,applyOutcome:"superseded",highestPendingGeneration:Ot(w)}),await this.coordinator.continueAfterSupersession(n.waveId),{waveId:n.waveId,ruleId:o.id,outcome:"superseded",inputFingerprint:f,changedTargets:[]};return await this.recordDiagnostic({...h,event:"apply-completed",memoHit:y!==null,applyOutcome:"applied",highestPendingGeneration:Ot(w)}),await this.reconcileTargets(R.changedTargets),await this.coordinator.advanceActiveWave(n.waveId),{waveId:n.waveId,ruleId:o.id,outcome:"applied",inputFingerprint:f,changedTargets:R.changedTargets}}async settleRetiredRuleJob(e){let t=await this.store.getWave(e);if(t?.status==="superseded")return!0;if(t?.status!=="running"||t.graphFingerprint===this.graphFingerprint)return!1;if((await this.store.supersedeWave(e,this.now())).status!=="superseded")return!1;return await this.coordinator.continueAfterSupersession(e),!0}async recordDiagnostic(e){if(!this.onDiagnostic)return;try{await this.onDiagnostic(e)}catch(t){this.executionContext.logger.warn("Projection diagnostics callback failed",t)}}}function Fp(e,t){if(typeof e==="object"&&e!==null&&"sources"in e&&Array.isArray(e.sources))return e.sources.length;return t.length}function Ot(e){if(e.length===0)return null;return e.reduce((t,r)=>Math.max(t,r.generation),e[0]?.generation??0)}function Np(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 Hp(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 Ae="shell:projection-rule";class ri{store;queue;graph;ruleById;graphFingerprint;createWaveId;beforeWaveCompletion;scheduleWakeup;onScheduledWakeupError;now;operationQueue=new Vs;scheduledWakeup;constructor(e){this.store=e.store,this.queue=e.queue,this.graph=e.graph,this.ruleById=Jp(e.graph,e.rules),this.graphFingerprint=Gp(e.graph,e.rules),this.createWaveId=e.createWaveId,this.beforeWaveCompletion=e.beforeWaveCompletion??(async()=>{}),this.scheduleWakeup=e.scheduleWakeup??Wp,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(ti(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(ti(s))await this.startNextWaveInternal();return s}let t=await this.store.listPendingInputs();if(t.length===0)return this.cancelScheduledWakeup(),null;let r=qp(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(ti(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=Xs(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:Hp(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:Ae,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 ti(e){return e.status==="completed"||e.status==="superseded"}function Wp(e,t){let r=setTimeout(()=>{t()},e);return()=>clearTimeout(r)}function qp(e,t,r){let n=Xs(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 Jp(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 Gp(e,t){return Ys({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 Xs(e,t,r){let i=new Map(e.projections.map((l)=>[l.id,l])),n=ea(e,(l)=>[l.from,l.to]),o=new Set(e.projections.filter((l)=>Qp(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=Kp(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 Qp(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 Kp(e,t){let r=ea(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 ea(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 ta(e){let t=new ri({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 ei({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(Ae,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??Vp)(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(Ae),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(Ae)}}}function Vp(e,t){let r=setInterval(()=>{t()},e);return r.unref(),()=>clearInterval(r)}import{existsSync as Zm}from"fs";import{mkdir as Fm,writeFile as Nm}from"fs/promises";import{join as Hm,resolve as Ka}from"path";var ra=5000;async function ia(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 na(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 Um,sep as Bm}from"path";var oa=Symbol();var sa=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,(r)=>r.toLowerCase())}}).formData();var Yp=1e4,Mt=(e)=>("headers"in e),la=async(e,t=Object.create(null))=>{let{all:r=!1,dot:i=!1}=t,n=(Mt(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 Xp(e,{all:r,dot:i});return{}};async function Xp(e,t){if(!Mt(e)&&e.bodyCache.formData)return aa(await e.bodyCache.formData,t);let r=Mt(e)?e.headers:e.raw.headers,i=await e.arrayBuffer(),n=sa(i,r.get("Content-Type")||"");if(!Mt(e))e.bodyCache.formData=n;let o=await n;if(o)return aa(o,t);return{}}function aa(e,t){let r=Object.create(null),i={count:0};if(e.forEach((n,o)=>{if(!(t.all||o.endsWith("[]")))r[o]=n;else em(r,o,n)}),t.dot)Object.entries(r).forEach(([n,o])=>{if(n.includes("."))tm(r,n,o,i),delete r[n]});return r}var em=(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]},tm=(e,t,r,i)=>{if(/(?:^|\.)__proto__\./.test(t))return;let n=e,o=t.split(".",34);if(o.length>33)ca();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++>=Yp)ca();n[s]=Object.create(null)}n=n[s]}})},ca=()=>{throw Error("Nesting limit exceeded")};var ni=(e)=>{let t=e.split("/");if(t[0]==="")t.shift();return t},da=(e)=>{let{groups:t,path:r}=rm(e),i=ni(r);return im(i,t)},rm=(e)=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,i)=>{let n=`@${i}`;return t.push([n,r]),n}),{groups:t,path:e}},im=(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},Lt={},ua=(e,t)=>{if(e==="*")return"*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let i=`${e}#${t}`;if(!Lt[i])if(r[2])Lt[i]=t&&t[0]!==":"&&t[0]!=="*"?[i,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)];else Lt[i]=[e,r[1],!0];return Lt[i]}return null},pa=(e,t)=>{try{return t(e)}catch{return e.replace(/(?:%[0-9A-Fa-f]{2})+/g,(r)=>{try{return t(r)}catch{return r}})}},oi=(e)=>pa(e,decodeURI),si=(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 oi(l.includes("%25")?l.replace(/%25/g,"%2525"):l)}else if(n===63||n===35)break}return t.slice(r,i)};var ma=(e)=>{let t=si(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},se=(e,t,...r)=>{if(r.length)t=se(t,...r);return`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`},Ut=(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)},Bt=(e)=>e.indexOf("%")!==-1?pa(e,nm):e,ii=(e)=>{if(e.indexOf("+")!==-1)e=e.replace(/\+/g," ");return Bt(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 ii(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=ii(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=ii(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},fa=ga,ha=(e,t)=>ga(e,t,!0),nm=decodeURIComponent;var ya=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&&Bt(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]=Bt(i)}return e}#i(e){return this.#e[1]?this.#e[1][e]:e}query(e){return fa(this.url,e)}queries(e){return ha(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 la(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[oa](){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 va={Stringify:1,BeforeStream:2,Stream:3},ba=(e,t)=>{let r=new String(e);return r.isEscaped=!0,r.callbacks=t,r};var ai=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)=>ai(l,t,!1,i,n))).then(()=>n[0]));if(r)return ba(await s,o);else return s};var om="text/plain; charset=UTF-8",ci=(e,t)=>({"Content-Type":e,...t}),qe=(e,t)=>new Response(e,t),li=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 ya(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||=qe(null,{headers:this.#a??=new Headers})}set res(e){if(this.#n&&e){e=qe(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=qe(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 qe(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,ci(om,r));json=(e,t,r)=>this.#s(JSON.stringify(e),t,ci("application/json",r));html=(e,t,r)=>{let i=(n)=>this.#s(n,t,ci("text/html; charset=UTF-8",r));return typeof e==="object"?ai(e,va.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??=()=>qe(),this.#l(this))};var di=(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 Sa=["get","post","put","delete","options","patch","query"],$t="Can not add a route since the matcher is already built.",_t=class extends Error{};var ui="__COMPOSED_HANDLER";var sm=(e)=>e.text("404 Not Found",404),Ra=(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)},wa=class e{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...Sa,"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??si:ma}#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=sm;errorHandler=Ra;route(t,r){let i=this.basePath(t);return r.routes.map((n)=>{let o;if(r.errorHandler===Ra)o=n.handler;else o=async(s,a)=>(await di([],r.errorHandler)(s,()=>n.handler(s,a))).res,o[ui]=n.handler;i.#o(n.method,n.path,o,n.basePath)}),this}basePath(t){let r=this.#e();return r._basePath=se(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=se(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",se(t,"*"),a),this}#o(t,r,i,n){r=se(this._basePath,r);let o={basePath:n!==void 0?se(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 li(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=di(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${se("/",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 Zt=[];function pi(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[[],Zt];let d=l.indexOf("",1);return[s[1][d],l]};return this.match=i,i(e,t)}var mi="[^/]+";var gi="(?:|/.*)",ae=Symbol(),Ia=new Set(".\\+*[^]$()");function am(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?["","",".*"]:["","",mi]:null:d==="/*"?["","",gi]:d.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/),p;if(u){let m=u[1],g=u[2]||"[^/]+";if(m&&u[2]){if(g===".*")throw ae;if(g=g.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(g))throw ae;if(g.length===1&&Ia.has(g))throw ae}if(p=s.#r[g],!p){if(g!==".*"&&g!=="(?:|/.*)"){for(let f in s.#r)if((g.length>1||f.length>1)&&f!==".*"&&f!=="(?:|/.*)")throw ae}p=s.#r[g]=new e}if(m!=="")p.#e??=n.varIndex++,i.push([m,p.#e])}else if(p=s.#r[d],!p){for(let m in s.#r)if(m.length>1&&m!==".*"&&m!=="(?:|/.*)")throw ae;p=s.#r[d]=new e}s=p}if(s.#t!==void 0)throw ae;s.#t=o?-1:r}buildRegExpStr(){let t=Object.keys(this.#r).sort(am).map((r)=>{let i=this.#r[r],n=i.buildRegExpStr();return n===""?"":(typeof i.#e==="number"?`(${r})@${i.#e}`:Ia.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 fi=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 xa(e){return Ca[e]??=new RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(t,r)=>r?`\\${r}`:t==="/*"?gi:t==="*"?".*":`/:${mi}`)}$`)}function Ft(e,t){for(let r of Object.keys(e).sort((i,n)=>n.length-i.length))if(xa(r).test(t))return[...e[r]]}var Nt=class{name="RegExpRouter";#t;#e;#r;constructor(){this.#t={["ALL"]:k()},this.#e={["ALL"]:k()},this.#r={["ALL"]:new fi}}#o(e,t){try{this.#r[e].insert(t,!/\*|\/:/.test(t))}catch(r){throw r===ae?new _t(t):r}}add(e,t,r){let i=this.#t,n=this.#e;if(!i)throw Error($t);if(!i[e]){this.#r[e]=new fi;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=xa(t);for(let l of o)if(!i[l][t])this.#o(l,t),i[l][t]=Ft(i[l],t)||Ft(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=Ut(t)||[t];for(let a of s)for(let l of o){if(!n[l][a])this.#o(l,a),n[l][a]=Ft(i[l],a)||Ft(i.ALL,a)||[];n[l][a].push([r,a])}}match=pi;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(([g])=>[g,k()]),Zt];continue}o[m[0]]=p.map(([g,f])=>[g,i.paths[f][1].reduceRight((h,[v],y)=>(h[v]=l[m[1][y][1]],h),k())])}return[s,a.map((d)=>o[d]),n]}};var Ta=class{name="SmartRouter";#t=[];#e=[];constructor(e){this.#t=e.routers}add(e,t,r){if(!this.#e)throw Error($t);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 _t)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 hi=k(),cm=0,Ea=class e{#t=[];#e=k();#r=[];#o;#i=hi;insert(t,r,i){let n=this,o=da(r),s=new Set,a=0;for(let l of o){let d=o[++a],u=ua(l,d)||(d===void 0&&l&&l.indexOf("*")===l.length-1?l:null),p=Array.isArray(u),m=p?u[0]:u||l,g=n.#e[m]||=new e;if(u&&!g.#o)g.#o=u,n.#r.push(g);if(n=g,p)s.add(u[1])}n.#t.push({[t]:{handler:i,possibleKeys:[...s],score:++cm}})}#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=hi;let n=[this],o=ni(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 f=0,h=n.length;f<h;f++){let v=n[f],y=v.#e[u];if(y)if(y.#i=v.#i,p){if(y.#e["*"])this.#n(i,y.#e["*"],t,v.#i);this.#n(i,y,t,v.#i)}else m.push(y);for(let S of v.#r){let R=S.#o,w=v.#i===hi?{}:{...v.#i};if(typeof R==="string"){if(R==="*"||u.startsWith(R.slice(0,-1))){if(this.#n(i,S,t,v.#i),R==="*")S.#i=w,m.push(S)}continue}let[,C,E]=R;if(!u&&E===!0)continue;if(E!==!0){if(!l){l=[];let ue=r[0]==="/"?1:0;for(let ee=0;ee<a;ee++)l[ee]=ue,ue+=o[ee].length+1}let B=r.slice(l[d]),Re=E.exec(B);if(Re){if(w[C]=Re[0],this.#n(i,S,t,v.#i,w),Re[0].length===B.length&&S.#e["*"])this.#n(i,S.#e["*"],t,v.#i,w);for(let ue in S.#e){S.#i=w;let ee=Re[0].match(/\//g)?.length??0;(s[ee]||=[]).push(S);break}continue}}if(E===!0||E.test(u))if(w[C]=u,p){if(this.#n(i,S,t,w,v.#i),S.#e["*"])this.#n(i,S.#e["*"],t,w,v.#i)}else S.#i=w,m.push(S)}}let g=s.shift();n=g?m.concat(g):m}if(i[1])i.sort((d,u)=>d.score-u.score);return[i.map(({handler:d,params:u})=>[d,u])]}};var yi=class{name="TrieRouter";#t=new Ea;add(e,t,r){for(let i of Ut(t)||[t])this.#t.insert(e,i,r)}match(e,t){return this.#t.search(e,t)}};var vi=class extends wa{constructor(e={}){super(e);this.router=e.router??new Ta({routers:[new Nt,new yi]})}};var Ht=(e)=>("server"in e.env)?e.env.server:e.env;var ke=/^\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 bi=(e,t=lm)=>{let r=e.match(/\.([a-zA-Z0-9]+?)$/);if(!r)return;return t[r[1].toLowerCase()]};var lm={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 Aa=(...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 ka={br:".br",zstd:".zst",gzip:".gz"},dm=Object.keys(ka),um="index.html",Da=(e)=>{let t=e.root??"./",r=e.path,i=e.join??Aa;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=oi(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,um);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&&bi(a,e.mimes)||bi(a);if(n.header("Content-Type",u||"application/octet-stream"),e.precompressed&&(!u||ke.test(u))){let p=new Set(n.req.header("Accept-Encoding")?.split(",").map((m)=>m.trim()));for(let m of dm){if(!p.has(m))continue;let g=await l(a+ka[m],n);if(g){d=g,n.header("Content-Encoding",m),n.header("Vary","Accept-Encoding",{append:!0});break}}}return await e.onFound?.(a,n),n.body(d)}await e.onNotFound?.(a,n),await o()}};import{stat as pm}from"fs/promises";import{join as mm}from"path";var Si=(e={})=>async function(r,i){return Da({...e,getContent:async(s)=>{let a=Bun.file(s);return await a.exists()?a:null},join:mm,isDir:async(s)=>{let a;try{a=(await pm(s)).isDirectory()}catch{}return a}})(r,i)};var ja="x-hono-disable-ssg",Dw=(()=>{try{return new Response("SSG is disabled",{status:404,headers:{[ja]:"true"}})}catch{return null}})();var{write:SI}=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 ym=za((e,t)=>{let r=Ht(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 Ma=(e)=>e===32||e===9||e===10||e===13,Wt=(e,t)=>{while(t<e.length){if(!Ma(e.charCodeAt(t)))break;t++}return t},Je=(e,t)=>{while(t>0){if(!Ma(e.charCodeAt(t-1)))break;t--}return t},Oa=(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]},vm=(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},bm=(e,t)=>{t=Wt(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,Je(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=Wt(e,r),e.charCodeAt(r)===61){let l=Oa(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=Wt(e,r+1),u=e.charCodeAt(d);if(d<e.length&&!(u===59||u===44)){let p=Oa(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,Je(e,r)),l===59)o=!0;r++;break}r++}return[r,i,n??e.slice(a,Je(e,r)),o]},Sm=(e,t)=>{let r={type:"",params:Object.create(null),q:1};t=Wt(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,Je(e,i)),i++,a===44)return[i,r.type?r:void 0];if(!r.type)return[vm(e,i),void 0];break}i++}if(!r.type)return r.type=e.slice(t,Je(e,e.length)),[e.length,r.type?r:void 0];let n,o,s;while(i<e.length){if([i,n,o,s]=bm(e,i),n&&o)r.params[n]=o;if(!s)break}return[i,r]},La=(e)=>{if(!e)return[];let t=[],r=0,i,n=!1,o;while(r<e.length)if([r,i]=Sm(e,r),i){if(i.q=Rm(i.params.q??i.params.Q),t.push(i),o&&o.q<i.q)n=!0;o=i}if(n)t.sort((s,a)=>a.q-s.q);return t},Rm=(e)=>{if(e===void 0)return 1;if(e==="")return 1;if(e==="NaN")return 0;let t=Number(e);if(Number.isNaN(t))return 1;if(t<0)return 0;if(t>1)return 1;return t};var wm=["gzip","deflate"],Im=/(?:^|,)\s*?no-transform\s*?(?:,|$)/i,Pm=(e,t)=>{if(e===void 0)return;let r=La(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},Cm=/(?:^|,)\s*accept-encoding\s*(?:,|$)/i,Ua=(e)=>{let t=e?.threshold??1024,r=e?.encoding?[e.encoding]:wm,i=e?.contentTypeFilter??ke,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)||!xm(s.res))return;let d=s.res.headers.get("Vary");if(d!=="*"&&!(d&&Cm.test(d)))s.header("Vary",d?`${d}, Accept-Encoding`:"Accept-Encoding");let u=s.req.header("Accept-Encoding"),p=Pm(u,r);if(!p||!s.res.body)return;let m=new CompressionStream(p);s.res=new Response(s.res.body.pipeThrough(m),s.res),s.res.headers.delete("Content-Length"),s.res.headers.set("Content-Encoding",p);let g=s.res.headers.get("ETag");if(g&&!g.startsWith("W/"))s.res.headers.set("ETag",`W/${g}`)}},xm=(e)=>{let t=e.headers.get("Cache-Control");return!t||!Im.test(t)};import{Readable as Ba}from"stream";import{createDeflate as Tm,createGzip as Em}from"zlib";var Am=["gzip","deflate"],km=/(?:^|,)\s*?no-transform\s*?(?:,|$)/i,$a=(e)=>{if(typeof CompressionStream<"u")return Ua(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||!Dm(i.res)||!jm(i.res))return;let s=i.req.header("Accept-Encoding"),a=e?.encoding??Am.find((l)=>s?.includes(l));if(!a||!i.res.body)return;try{let l=a==="gzip"?Em():Tm(),d=Ba.fromWeb(i.res.body).pipe(l),u=Ba.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)}}},Dm=(e)=>{let t=e.headers.get("Content-Type");return t&&ke.test(t)},jm=(e)=>{let t=e.headers.get("Cache-Control");return!t||!km.test(t)};var zm=(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 _a=async(e,t)=>{if(!e)return null;let r=void 0,i,n=0,o=async(a)=>{r=await t(zm(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 g=new Uint8Array(new ArrayBuffer(Math.min(262144,Math.max(p,i.byteLength*2))));g.set(i.subarray(0,n)),i=g}i.set(a.subarray(d),n)}n=p;break}let m=262144-n;if(i?.byteLength!==262144){let g=new Uint8Array(new ArrayBuffer(262144));if(i)g.set(i.subarray(0,n));i=g}i.set(a.subarray(d,d+m),n),await o(i),n=0,d+=m}}if(i&&n>0)await o(i.subarray(0,n));if(!r)return null;return Array.prototype.map.call(new Uint8Array(r),(a)=>a.toString(16).padStart(2,"0")).join("")};var Om=["cache-control","content-location","date","etag","expires","vary"],Za=(e)=>e.replace(/^W\//,"");function Mm(e,t){return t!=null&&t.split(",").some((r)=>Za(r.trim())===Za(e))}function Lm(e){if(!e){if(crypto&&crypto.subtle)e=(t)=>crypto.subtle.digest({name:"SHA-1"},t)}return e}var Fa=(e)=>{let t=new Set((e?.retainedHeaders??Om).map((n)=>n.toLowerCase())),r=e?.weak??!1,i=Lm(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 _a(l.clone().body,i);if(u===null)return;d=r?`W/"${u}"`:`"${u}"`}if(a==="*"||Mm(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 Ri(e,t){return async(r)=>{let i=r.req.raw,n=i.headers.get("content-type")??"",o=i.headers.get("accept")?.includes("application/json"),s={};if(n.includes("application/json"))s=await i.json();else if(n.includes("form")){let m=await i.formData();for(let[g,f]of m.entries())s[g]=f}let a=await t(e,s),l=typeof a==="object"&&a!==null&&"data"in a?a.data:a,d=Na.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 Ge(e,t){return e===t||e.startsWith(t+Bm)}var Ha="public, max-age=31536000, immutable";function $m(e){return e.getRoutes?.()??[]}var _m=255;class Jt{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(!Ge(n,Z(e)))return;let o=Bun.file(n);if(!await o.exists())return;let s=`<div ${Ja}="${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([...$m(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??_m,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 ia(e,{drainMs:this.options.shutdownDrainMs??ra,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 vi;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("/*",Fa()),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",Ha);else r.header("Cache-Control",e.defaultCache)}),t.use("/*",async(r,i)=>{if(r.req.path===qt)return r.notFound();return i()}),t.use("/*",this.createCleanUrlMiddleware(e.distDir)),t.use("/*",Si({root:e.distDir})),t.get(Wa,(r)=>r.body(qa,200,{"Content-Type":"image/svg+xml; charset=utf-8","Cache-Control":"public, max-age=86400"})),t.notFound(async(r)=>{let i=Bun.file(Um(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=na(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 wi&&s.slot)return await this.fillSitePage(t.distDir,i,s)??s;if(r==="GET"&&s instanceof wi&&s.status===200){let a=Z(t.distDir,`.${i}`,"index.html");if(Ge(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 Ri({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(!Ge(i,this.options.sharedImagesDir))return null;let n=Bun.file(i);if(!await n.exists())return null;return new Response(n,{headers:{"Cache-Control":Ha}})}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(!Ge(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(Ge(s,e)){let a=Bun.file(s);if(await a.exists())return t.html(await a.text())}await r()}}}function Ii(e,t){return(r,i)=>e.send({type:Gt.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:Ga(t,"anonymous")}},sender:t})}var Pi=`<!DOCTYPE html>
11
11
  <html lang="en">
12
12
  <head>
13
13
  <meta charset="UTF-8">
@@ -74,32 +74,32 @@ ${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 Qa=c.strictObject({productionOutputDir:c.string().min(1),previewOutputDir:c.string().min(1),sharedImagesDir:c.string().min(1)});var F="webserver",G=`${F}:${F}`,Hm="./dist/site-production",Wm="./dist/site-preview",qm="./dist/images";function Jm(e){return[...e].flatMap((t)=>{let r=t.getStaticSiteOutput?.();return r?[{...Qa.parse(r),ownerPluginId:t.id}]:[]})}function Gm(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&&Ka(d)!==Ka(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",Hm),previewDistDir:n("previewDistDir",r?.previewOutputDir,"preview site",Wm),sharedImagesDir:n("sharedImagesDir",r?.sharedImagesDir,"shared images",qm)}}async function Qm(e,t,r){let i=[e.productionDistDir,...t?[e.previewDistDir]:[]];for(let n of i){if(_m(n))continue;await Zm(n,{recursive:!0}),await Fm(Nm(n,"index.html"),Pi),r.debug(`Created site directory at ${n}`)}}function Ya(e){return e?{siteUrl:`https://${e}`,previewUrl:`https://${Va(e)}`}:{siteUrl:void 0,previewUrl:void 0}}function Xa(e){let{config:t,logger:r}=e,{siteUrl:i,previewUrl:n}=Ya(e.domain),o;return{start:async()=>{let s=Gm(t,Jm(e.getPlugins()));await Qm(s,t.preview,r),o??=new Jt({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:Ii(e.messageBus,F)}),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 ec(e,t){let{siteUrl:r,previewUrl:i}=Ya(t);if(!r)return{endpoints:[],interactions:[]};let n=e.preview&&i?i:void 0;return{endpoints:[{pluginId:F,label:"Site",url:r,priority:10},...n?[{pluginId:F,label:"Preview",url:n,priority:20,visibility:"admin"}]:[]],interactions:[{pluginId:F,id:"site",label:"Public site",description:"Visit the published public site for this brain.",href:r,kind:"human",priority:10},...n?[{pluginId:F,id:"preview",label:"Preview site",description:"Open the private preview build.",href:n,kind:"admin",priority:20,visibility:"admin"}]:[]]}}var Km=250,Vm=c.object({projectionBatch:c.object({operationId:c.string().min(1),childKey:c.string().min(1)})});class Ci{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=Ce(n),this.hooks=o}async boot(e){this.services.logger.debug("Starting Shell boot");let t=this.initializer;await Qt([()=>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 ta({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 Fe(this.services.messageBus,tc,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:rc,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=Vm.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 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=ac();if(this.services.disposables.push(this.services.messageBus.subscribe(Ne.initialSyncCompleted,async(l)=>(s.resolve(oc.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(G))return;await this.services.daemonRegistry.start(G),this.services.logger.debug("Started the HTTP host before initial sync")}async emitPluginsRegistered(){let e=await this.services.messageBus.collect({type:Ne.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)&&nc.safeParse(t.data).data?.initialSyncPending===!0)}async settleStartupContent(){await this.prepareReadyState(),await Te(this.services.messageBus,sc,{timestamp:new Date().toISOString()},"shell"),this.services.logger.debug("Emitted startup content settled event")}async loadIdentityServices(){await Qt([()=>this.services.identityService.refreshCache(),()=>this.services.profileService.refreshCache(),()=>this.services.canonicalIdentityService.refreshCache()]),this.services.logger.debug("Identity services loaded")}async initializeIdentityServices(){await Qt([()=>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 ic(this.services.templateRegistry,this.services.entityService);if(t.created.length>0)e.debug(`Materialized ${t.created.length} prompt entities`);if(t.refreshed.length>0)e.info("Refreshed untouched prompts to their current defaults",{targets:t.refreshed});if(t.retitled.length>0)e.info("Corrected generated prompt titles",{targets:t.retitled});if(t.staleOverrides.length>0)e.info("Edited prompts are based on an older default",{targets:t.staleOverrides});if(t.unverifiedOverrides.length>0)e.info("Prompts without provenance differ from their default and are kept; delete one to restore its default",{targets:t.unverifiedOverrides});for(let{target:r,error:i}of t.failed)e.warn(`Could not sync prompt ${r}: ${i}`)}async startRuntimeServices(){for(let e of["shell:recurring-checks","shell:guest-retention"])if(this.services.daemonRegistry.has(e))await this.services.daemonRegistry.start(e);if(await this.services.pluginManager.startPluginDaemons(),this.role.executes)await this.services.jobQueueWorker.start();this.services.jobProgressMonitor.start(),await this.services.batchJobManager.start()}async startIndexReadinessMonitor(){await this.lifecycle.fork(this.runIndexReadinessMonitor())}runIndexReadinessMonitor(){let{entityService:e,logger:t}=this.services;return b.tryPromise({try:()=>e.backfillMissingEmbeddings(),catch:(i)=>i}).pipe(b.tap((i)=>b.sync(()=>{t.debug("Queued missing embedding backfill jobs",i)})),b.catch((i)=>b.sync(()=>{t.warn("Embedding backfill failed",i)}))).pipe(b.andThen(b.tryPromise({try:(i)=>e.awaitIndexReady({intervalMs:Km,signal:i}),catch:(i)=>i}).pipe(b.tap((i)=>b.sync(()=>{if(i.degraded)t.warn("Semantic index ready with degraded embeddings",i);else t.debug("Semantic index ready",i)})),b.catch((i)=>b.sync(()=>{t.warn("Semantic index readiness monitor stopped",i)})))))}}var Ym=c.object({}),cc=c.string().regex(/^\d{4}-(0[1-9]|1[0-2])$/,"Expected YYYY-MM"),dc=c.array(c.string().min(1)).min(1).optional().describe("Only these entity types"),Xm=c.object({entityTypes:dc,from:cc.optional().describe("First month, YYYY-MM"),to:cc.optional().describe("Last month, YYYY-MM")}),eg=c.object({staleDays:c.number().int().min(1).max(3650).default(90).describe("Days without an update before content counts as stale"),entityTypes:dc});function uc(e){let t=new lc;return t.register(Kt({type:"overview",description:"Entity counts by type, recent activity, and draft and published totals.",params:Ym,handler:async(r,{entityService:i,visibilityScope:n})=>tg(i,n)})),t.register(Kt({type:"publishing-cadence",description:"Pieces per month, by type: counted in the month they were published, or created when never published.",params:Xm,handler:async(r,{entityService:i,visibilityScope:n})=>ig(i,n,r)})),t.register(Kt({type:"content-health",description:"Drafts and content not updated for a long time.",params:eg,handler:async(r,{entityService:i,visibilityScope:n})=>ng(i,n,e,r)})),t}async function tg(e,t){let r=await e.getEntityCounts(t),i={},n=0;for(let{entityType:g,count:f}of r)i[g]=f,n+=f;let o=await xi(e,t),s=Date.now(),a=s-604800000,l=s-2592000000,d=0,u=0;for(let g of o){let f=new Date(g.created).getTime();if(f>=a)d++;if(f>=l)u++}let p=mc(o),m=o.filter((g)=>g.metadata.status==="published");return{entityCounts:i,totalEntities:n,recentActivity:{last7days:d,last30days:u},contentHealth:{drafts:p.length,published:m.length}}}function rg(e){let t=e.metadata.publishedAt;return new Date(typeof t==="string"&&t?t:e.created)}function pc(e,t){return t?e.filter((r)=>t.includes(r.entityType)):e}async function ig(e,t,r){let i=pc(await xi(e,t),r.entityTypes),n=new Map;for(let s of i){let a=rg(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 ng(e,t,r,i){let n=pc(await xi(e,t),i.entityTypes),o=mc(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 mc(e){return e.filter((t)=>t.metadata.status==="draft")}async function xi(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},binaryContent:"reference"}});i.push(...o)}return i}class Qe{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 Ti extends Qe{constructor(){super((e)=>gc.parse(e),(e)=>e.url)}}class Ei extends Qe{constructor(){super((e)=>fc.parse(e),(e)=>e.id)}}function hc(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 og=["/health","/images"],sg=new Set([qt]),ag=new Set(yc),cg=new Set(["GET","POST","PUT","DELETE"]);function vc(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 bc(e){return sg.has(e)||og.some((t)=>e===t||e.startsWith(`${t}/`))}function Ai(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&&bc(e))throw Error(`Invalid HTTP route path "${e}" declared by plugin "${t}"`)}function Sc(e,t,r){if(!e.has(t))throw Error(`Invalid HTTP route method "${t}" declared by plugin "${r}"`)}function lg(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 dg(e,t){Ai(t.path,e.pluginId);let r=t.method??"GET";Sc(ag,r,e.pluginId);let i=t.match??"exact";lg(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)=>!bc(o)&&n(o)}:{},handler:t.handler})}function ug(e,t){Ai(t.path,e.pluginId,!1);let r=`/api/${e.pluginId}${t.path}`;if(Ai(r,e.pluginId),Sc(cg,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 pg(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 mg(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 Vt{routes;manifest;apiRoutes;webRoutes;static createFresh(){return new Vt}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(dg(n,o)),r.push(Object.freeze({pluginId:n.pluginId,fullPath:o.path,definition:Object.freeze({...o})}));for(let o of n.apiRoutes){let s=ug(n,o);t.push(s),i.push(Object.freeze({pluginId:n.pluginId,fullPath:s.fullPath,definition:s.definition}))}}return pg(t),this.routes=Object.freeze(t),this.manifest=mg(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 Rc(e,t){e.addFinalizer(()=>t.legacyBinaryLedger.flush()),e.addFinalizer(async()=>{let{entityService:r}=t;if(gg(r))await r.releaseDatabaseLease()}),e.addFinalizer(()=>t.pluginManager.shutdownPlugins()),e.addFinalizer(async()=>{if(t.daemonRegistry.has(G))await t.daemonRegistry.unregister(G)}),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 gg(e){return"releaseDatabaseLease"in e&&typeof e.releaseDatabaseLease==="function"}function ki(e){return Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength)}function eC(e,t){return`data:${e};base64,${ki(t).toString("base64")}`}var fg=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")]),Ic=c.object({query:c.string().describe("Search term"),scope:fg.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")}),Pc=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.")}),Cc=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)")}),xc=c.string().min(1).describe("Upload id from the conversation's upload refs"),Tc=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(),Ec=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."),Ve=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:xc,transform:Ec,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(),Tc,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:xc,transform:Ec},{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}),Ve,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()]),hg=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."),prompt:c.string().min(1).describe("Prompt for creating new generated content from the resolved source, written from the user's request without added voice, tone or engagement directions; the style guide supplies the voice.")}).strict(),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()]),Yt=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. Leave it out when saving several uploads: each item in source.items takes its own title."),visibility:wc.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(),Ac=c.object({operation:hg.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(),yg=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(),Ke="An update operation is exactly one of `fields`, `content`, `edits` or `source`.",ji=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(yg).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:Tc.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 te(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(", ")}: ${Ke}`}}).refine((e)=>[e.fields,e.content,e.edits,e.source].filter((t)=>t!==void 0).length===1,{message:Ke}).describe(Ke),Xt=c.object({entityType:c.string().describe("Entity type"),id:c.string().describe("Entity ID, slug, or title"),operation:ji.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(),kc=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")}),oC=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")}),Dc=c.object({batchId:c.string().optional().describe("Specific batch ID to check"),jobTypes:c.array(c.string()).optional().describe("Filter by job types")}),vg=c.object({entityType:c.string().optional(),entityId:c.string().optional(),attachmentType:c.string().optional()}),bg=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:vg.optional()}),sC=c.object({entityId:c.string().optional(),status:c.enum(["created","generating"]),jobId:c.string().optional(),attachment:bg.optional()}),aC=c.object({status:c.literal("extracting"),jobId:c.string(),entityType:c.string(),source:c.string().optional(),mode:c.enum(["derive","rebuild"]).optional()});function Oc(e,t,r){return r==="create"?e.getCreateFieldsSchema(t):e.getEditableFieldsSchema(t)}function Mc(e){if(e instanceof c.ZodOptional||e instanceof c.ZodNullable||e instanceof c.ZodDefault)return Mc(e.unwrap());return e instanceof c.ZodType?e:void 0}function jc(e){try{let{$schema:t,...r}=c.toJSONSchema(e,{target:"draft-7",io:"input"});return r}catch{return}}function Sg(e){return zc({type:"object",properties:{value:e},required:["value"]})!==void 0}function Lc(e,t){let r=new Map,i=new Map,n=e.getAllEntityTypes();for(let d of n){let u=Oc(e,d,t.on);for(let[p,m]of Object.entries(u?.shape??{})){if(t.omit?.includes(p))continue;let g=Mc(m),f=g&&jc(g);if(!g||!f||!Sg(f))continue;let h=r.get(p)??new Map;h.set(JSON.stringify(f),g),r.set(p,h),i.set(p,[...i.get(p)??[],d])}}let o=new Map;for(let[d,u]of r){let[p,...m]=[...u.values()];if(!p)continue;let g=m.length>0?c.union([p,...m]):p,f=JSON.stringify(jc(g)),h=o.get(f)??{value:g,names:[]};h.names.push(d),o.set(f,h)}let s=[...o.values()].map(({value:d,names:u})=>{let[p,...m]=u,g=u.map((f)=>{let h=i.get(f)??[];return`${f} (${h.length===n.length?"every type":h.join(", ")})`}).join("; ");return 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: ${g}.`),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 Rg(e){return Object.fromEntries((Array.isArray(e)?e:[]).flatMap((t)=>Q(t)&&typeof t.name==="string"?[[t.name,t.value]]:[]))}function er(e,t,r,i){if(!r)return;let{allow:n}=i,o=new Set(Object.keys(Oc(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 Oi(e){return"fields"in e&&e.fields!==void 0?{...e,fields:Rg(e.fields)}:e}function Uc(e){return{prepare:()=>e.ensureGroupingsCurrent(),inputSchema:()=>{let t=Lc(e,{on:"create",omit:["visibility"]}),r=Ve.shape.items.element,i=Ve.extend({items:c.array(r.extend({fields:t.optional().describe("Field changes the user stated for this file alone, one { name, value } per field, such as the date and address it was first published at: [{ name: 'publishedAt', value }, { name: 'canonicalUrl', value }]; facts shared by every file go in the top-level fields.")})).min(2).max(20)}),[n,...o]=Di.options.map((s)=>s===Ve?i:s);if(!n)throw Error("system_create has no source branches");return{...Yt.shape,source:c.discriminatedUnion("kind",[n,...o]).describe("Concrete source selector. Use exactly one source branch. For AI generation or source-derived artifacts, use system_generate instead."),fields:t.optional().describe("Field changes for facts the user states outside the source text, one { name, value } per field, e.g. a post first published elsewhere: [{ name: 'status', value: 'published' }, { name: 'publishedAt', value: '2025-03-12' }, { name: 'canonicalUrl', value }]; the section a doc goes in, named exactly as the user names it: [{ name: 'section', value }]; the year a project began: [{ name: 'year', value }]. Never copy values from the text or its frontmatter; omit when nothing extra is stated.")}},toToolInput:(t)=>{let r=t.source;return Oi({...t,...Q(r)&&Array.isArray(r.items)&&{source:{...r,items:r.items.map((i)=>Q(i)?Oi(i):i)}}})}}}function zi(e){let t=e.unwrap();return e.description?t.describe(e.description):t}function Bc(e){let{content:t,edits:r,source:i}=ji.shape;return{prepare:()=>e.ensureGroupingsCurrent(),inputSchema:()=>({...Xt.shape,operation:c.union([c.strictObject({fields:Lc(e,{on:"update"}).describe("Change frontmatter or metadata fields, one { name, value } per field changed. Use this for status, title, coverImageId, ogImageId, and metadata changes such as approving an agent. To set an existing image as an entity cover, change coverImageId to that image id. To remove a field, such as a cover image, give it the value null, not an empty string. Do not use fields for anchor-profile; anchor-profile updates require the content operation.")}),c.strictObject({content:zi(t)}),c.strictObject({edits:zi(r)}),c.strictObject({source:zi(i)})]).describe("Exactly one update operation")}),toToolInput:(n)=>{let o=n.operation;return Q(o)?{...n,operation:Oi(o)}:n}}}function K(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}}var wg="system";function ye(e){return{kind:"error",result:e}}function T(e,t){return ye({success:!1,error:e,...t!==void 0&&{code:t}})}function N(e,t,r,i,n={}){let{visibility:o="admin",sideEffects:s}=n;return{name:`${wg}_${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 rr(e){return{interfaceType:e.interfaceType,actor:e.actor,userPermissionLevel:e.userPermissionLevel??"public",...e.channelId&&{channelId:e.channelId},...e.channelName&&{channelName:e.channelName}}}async function $c(e,t,r,i){let n=await t(r,rr(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=K(e,o.entityType,"create",i);if(s)return{kind:"error",result:s};return{kind:"continue",createInput:o}}function De(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 je(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 Mi(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 ir(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var Ig={base:"note"};function _c(e){return Ig[e]??e.replaceAll("-"," ")}function nr(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 Zc(e){return!!e&&Object.keys(e.shape).length>0}async function Fc(e,t,r){if(!r)return!1;let i=await e.conversationService.getMessages(r,{limit:100});for(let n of i){let s=tr(n.metadata)?.attachments;if(!Array.isArray(s))continue;for(let a of s){if(!te(a))continue;let l=a.source;if(!te(l))continue;if(l.kind===t.kind&&l.id===t.id)return!0}}return!1}async function or(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"&&!K(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 Nc(e){return`Replaces: failed ${e.entityType} "${e.id}"`}async function Hc(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 sr(e,t,r){let i=De(e,t);if(i)return ye(i);let n=K(e,t,"create",r);if(n)return ye(n);return{kind:"ok",value:{interceptor:e.entityRegistry.getCreateInterceptor(t)}}}async function ar(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
- ${Nc(i)}`:a,args:t.buildArgs((d)=>({...l,confirmed:!0,confirmationToken:d}))}}async function Ye(e,t,r){let i=await Hc(e,r.replacesFailed);if(i)return i;if(!r.interceptor)return r.persist(r.createInput);let n=await $c(e,r.interceptor,r.createInput,t);if(n.kind!=="continue")return n.result;return r.persist(n.createInput)}async function cr(e,t,r,{confirmed:i}){let n=r.conversationId??r.channelId;if(!n)return{success:!1,error:"Conversation message is not accessible in this conversation or does not exist."};let o=await e.conversationService.getMessages(n,{limit:100}),s=t.kind==="user-message",a=s?o.filter((y)=>{if(y.role!=="user")return!1;let S=r.userPermissionLevel??"public";if(S==="admin")return!0;let R=tr(y.metadata)?.userPermissionLevel;return(R==="public"||R==="trusted"||R==="admin")&&e.permissionService.hasPermission(S,R)}):o.filter(Wc),l=t.messageId?a.find((y)=>y.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=Tg(xg(t,l.content),l.content),u=(y,S,R,w)=>{if(!S)return{offset:R};let C=`${y} ${JSON.stringify(S)}`;if(d.boundaryMode==="lines"&&/[\r\n]/.test(S))return{problem:`${C} contains a newline; in lines mode give the marker line's text only`};let E=Pg(l.content,S,d.boundaryMode==="lines"?"lines":"literal",w),[B]=E;if(E.length===1&&B!==void 0)return{offset:B};return{problem:E.length===0?`${C} does not occur in the message`:`${C} occurs ${E.length} times in the message`}},p=u("startAfter",d.startAfter,0,!0),m=d.boundaryMode==="frontmatter"&&"offset"in p?Ag(l.content,p.offset):p,g=u("endBefore",d.endBefore,l.content.length,!1),f=[m,g].flatMap((y)=>("problem"in y)?[y.problem]:[]);if(f.length===0&&"offset"in m&&"offset"in g&&m.offset>=g.offset)f.push("startAfter must come before endBefore with content between them");if(!("offset"in m)||!("offset"in g)||f.length>0)return{success:!1,error:`User-message boundary ${f.join("; ")}; each boundary must occur exactly once. ${Eg(l.content)}`};let h=l.content.slice(m.offset,g.offset).replace(/^(?:[ \t]*\r?\n)+(?=---\r?\n)/,""),v=i?t.contentHash:void 0;if(v&&v!==ie(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 lr(e,t){let{startAfter:r,endBefore:i,...n}=t.source??e;return{...n,...r?{startAfter:r}:{},...i?{endBefore:i}:{},messageId:t.messageId,contentHash:ie(t.content)}}function Pg(e,t,r,i){if(r==="lines"){let o=Li(e,t,i);return o.length>0||!t.trim()?o:Li(e,t,i,Cg)}let n=qc(e,t,i);return n.length>0?n:kg(e,t,i)}function Cg(e){return e.trim().replace(/\s+/g," ")}function xg(e,t){let r=(a)=>a?.trim()==="---";if(!r(e.startAfter)&&!r(e.endBefore))return e;if((t.match(/^---\r?$/gm)?.length??0)!==2||Ui(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 Tg(e,t){let{startAfter:r,endBefore:i}=e;if(e.boundaryMode!==void 0||!r||!i)return e;let n=(o)=>!/[\r\n]/.test(o)&&Li(t,o,!0).length===1;return n(r)&&n(i)?{...e,boundaryMode:"lines"}:e}function Eg(e){return Ui(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 Ag(e,t){let r=Ui(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 Ui(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 Li(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 kg(e,t,r){let i=t.trim().split(/\s+/);if(i.join("")===""||!/\s/.test(t))return[];let n=(s)=>s?"\\s*":"",o=new RegExp(n(/^\s/.test(t))+i.map(Dg).join("\\s+")+n(/\s$/.test(t)),"g");return Array.from(e.matchAll(o),(s)=>s.index+(r?s[0].length:0))}function Dg(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function qc(e,t,r,i=0){let n=e.indexOf(t,i);if(n<0)return[];return[n+(r?t.length:0),...qc(e,t,r,n+1)]}var jg=/^[ \t]*---[ \t]*$/gm;function Jc(e){return e.replace(/\s+/g," ").trim()}function zg(e){return e.kind==="user-message"?e.messageId:void 0}class Bi{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=zg(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&&Jc(t.content.replace(jg,""))===Jc(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 Gc(e){if(e.kind!=="user-message")return e;let{contentHash:t,...r}=e;return r}function _i(e){return`${e.entityType} "${e.title}"`}function Og(e){return Object.entries(e).map(([t,r])=>`${t}: ${typeof r==="string"?r:JSON.stringify(r)}`).join(", ")}function Qc(e){return"error"in e?e.error:"the save was not completed"}function Mg(e){let t=new Map;for(let r of e){let i=`${r.entityType}:${Y(r.title)}`,n=t.get(i);if(n)return`${n.filename} and ${r.filename} would both be saved as ${_i(r)}. Give them different titles in source.items.`;t.set(i,r)}return}function Lg(e,t){return{summary:`Save ${e.length} uploaded files?`,completionSummary:`Saved ${e.length} uploaded files: ${e.map(_i).join(", ")}.`,preview:[...e.map((r,i)=>[`${i+1}. ${r.filename} \u2192 ${_i(r)}`,...r.fields?[` ${Og(r.fields)}`]:[],...r.replacesFailed?[` Replaces failed ${r.replacesFailed}`]:[]].join(`
77
+ </html>`;var Qa=c.strictObject({productionOutputDir:c.string().min(1),previewOutputDir:c.string().min(1),sharedImagesDir:c.string().min(1)});var F="webserver",Q=`${F}:${F}`,Wm="./dist/site-production",qm="./dist/site-preview",Jm="./dist/images";function Gm(e){return[...e].flatMap((t)=>{let r=t.getStaticSiteOutput?.();return r?[{...Qa.parse(r),ownerPluginId:t.id}]:[]})}function Qm(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&&Ka(d)!==Ka(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",Wm),previewDistDir:n("previewDistDir",r?.previewOutputDir,"preview site",qm),sharedImagesDir:n("sharedImagesDir",r?.sharedImagesDir,"shared images",Jm)}}async function Km(e,t,r){let i=[e.productionDistDir,...t?[e.previewDistDir]:[]];for(let n of i){if(Zm(n))continue;await Fm(n,{recursive:!0}),await Nm(Hm(n,"index.html"),Pi),r.debug(`Created site directory at ${n}`)}}function Ya(e){return e?{siteUrl:`https://${e}`,previewUrl:`https://${Va(e)}`}:{siteUrl:void 0,previewUrl:void 0}}function Xa(e){let{config:t,logger:r}=e,{siteUrl:i,previewUrl:n}=Ya(e.domain),o;return{start:async()=>{let s=Qm(t,Gm(e.getPlugins()));await Km(s,t.preview,r),o??=new Jt({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:Ii(e.messageBus,F)}),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 ec(e,t){let{siteUrl:r,previewUrl:i}=Ya(t);if(!r)return{endpoints:[],interactions:[]};let n=e.preview&&i?i:void 0;return{endpoints:[{pluginId:F,label:"Site",url:r,priority:10},...n?[{pluginId:F,label:"Preview",url:n,priority:20,visibility:"admin"}]:[]],interactions:[{pluginId:F,id:"site",label:"Public site",description:"Visit the published public site for this brain.",href:r,kind:"human",priority:10},...n?[{pluginId:F,id:"preview",label:"Preview site",description:"Open the private preview build.",href:n,kind:"admin",priority:20,visibility:"admin"}]:[]]}}var Vm=250,Ym=c.object({projectionBatch:c.object({operationId:c.string().min(1),childKey:c.string().min(1)})});class Ci{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=Ce(n),this.hooks=o}async boot(e){this.services.logger.debug("Starting Shell boot");let t=this.initializer;await Qt([()=>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 ta({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 Fe(this.services.messageBus,tc,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:rc,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=Ym.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 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=ac();if(this.services.disposables.push(this.services.messageBus.subscribe(Ne.initialSyncCompleted,async(l)=>(s.resolve(oc.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(Q))return;await this.services.daemonRegistry.start(Q),this.services.logger.debug("Started the HTTP host before initial sync")}async emitPluginsRegistered(){let e=await this.services.messageBus.collect({type:Ne.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)&&nc.safeParse(t.data).data?.initialSyncPending===!0)}async settleStartupContent(){await this.prepareReadyState(),await Te(this.services.messageBus,sc,{timestamp:new Date().toISOString()},"shell"),this.services.logger.debug("Emitted startup content settled event")}async loadIdentityServices(){await Qt([()=>this.services.identityService.refreshCache(),()=>this.services.profileService.refreshCache(),()=>this.services.canonicalIdentityService.refreshCache()]),this.services.logger.debug("Identity services loaded")}async initializeIdentityServices(){await Qt([()=>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 ic(this.services.templateRegistry,this.services.entityService);if(t.created.length>0)e.debug(`Materialized ${t.created.length} prompt entities`);if(t.refreshed.length>0)e.info("Refreshed untouched prompts to their current defaults",{targets:t.refreshed});if(t.retitled.length>0)e.info("Corrected generated prompt titles",{targets:t.retitled});if(t.staleOverrides.length>0)e.info("Edited prompts are based on an older default",{targets:t.staleOverrides});if(t.unverifiedOverrides.length>0)e.info("Prompts without provenance differ from their default and are kept; delete one to restore its default",{targets:t.unverifiedOverrides});for(let{target:r,error:i}of t.failed)e.warn(`Could not sync prompt ${r}: ${i}`)}async startRuntimeServices(){for(let e of["shell:recurring-checks","shell:guest-retention"])if(this.services.daemonRegistry.has(e))await this.services.daemonRegistry.start(e);if(await this.services.pluginManager.startPluginDaemons(),this.role.executes)await this.services.jobQueueWorker.start();this.services.jobProgressMonitor.start(),await this.services.batchJobManager.start()}async startIndexReadinessMonitor(){await this.lifecycle.fork(this.runIndexReadinessMonitor())}runIndexReadinessMonitor(){let{entityService:e,logger:t}=this.services;return b.tryPromise({try:()=>e.backfillMissingEmbeddings(),catch:(i)=>i}).pipe(b.tap((i)=>b.sync(()=>{t.debug("Queued missing embedding backfill jobs",i)})),b.catch((i)=>b.sync(()=>{t.warn("Embedding backfill failed",i)}))).pipe(b.andThen(b.tryPromise({try:(i)=>e.awaitIndexReady({intervalMs:Vm,signal:i}),catch:(i)=>i}).pipe(b.tap((i)=>b.sync(()=>{if(i.degraded)t.warn("Semantic index ready with degraded embeddings",i);else t.debug("Semantic index ready",i)})),b.catch((i)=>b.sync(()=>{t.warn("Semantic index readiness monitor stopped",i)})))))}}var Xm=c.object({}),cc=c.string().regex(/^\d{4}-(0[1-9]|1[0-2])$/,"Expected YYYY-MM"),dc=c.array(c.string().min(1)).min(1).optional().describe("Only these entity types"),eg=c.object({entityTypes:dc,from:cc.optional().describe("First month, YYYY-MM"),to:cc.optional().describe("Last month, YYYY-MM")}),tg=c.object({staleDays:c.number().int().min(1).max(3650).default(90).describe("Days without an update before content counts as stale"),entityTypes:dc});function uc(e){let t=new lc;return t.register(Kt({type:"overview",description:"Entity counts by type, recent activity, and draft and published totals.",params:Xm,handler:async(r,{entityService:i,visibilityScope:n})=>rg(i,n)})),t.register(Kt({type:"publishing-cadence",description:"Pieces per month, by type: counted in the month they were published, or created when never published.",params:eg,handler:async(r,{entityService:i,visibilityScope:n})=>ng(i,n,r)})),t.register(Kt({type:"content-health",description:"Drafts and content not updated for a long time.",params:tg,handler:async(r,{entityService:i,visibilityScope:n})=>og(i,n,e,r)})),t}async function rg(e,t){let r=await e.getEntityCounts(t),i={},n=0;for(let{entityType:g,count:f}of r)i[g]=f,n+=f;let o=await xi(e,t),s=Date.now(),a=s-604800000,l=s-2592000000,d=0,u=0;for(let g of o){let f=new Date(g.created).getTime();if(f>=a)d++;if(f>=l)u++}let p=mc(o),m=o.filter((g)=>g.metadata.status==="published");return{entityCounts:i,totalEntities:n,recentActivity:{last7days:d,last30days:u},contentHealth:{drafts:p.length,published:m.length}}}function ig(e){let t=e.metadata.publishedAt;return new Date(typeof t==="string"&&t?t:e.created)}function pc(e,t){return t?e.filter((r)=>t.includes(r.entityType)):e}async function ng(e,t,r){let i=pc(await xi(e,t),r.entityTypes),n=new Map;for(let s of i){let a=ig(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 og(e,t,r,i){let n=pc(await xi(e,t),i.entityTypes),o=mc(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 mc(e){return e.filter((t)=>t.metadata.status==="draft")}async function xi(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},binaryContent:"reference"}});i.push(...o)}return i}class Qe{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 Ti extends Qe{constructor(){super((e)=>gc.parse(e),(e)=>e.url)}}class Ei extends Qe{constructor(){super((e)=>fc.parse(e),(e)=>e.id)}}function hc(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 sg=["/health","/images"],ag=new Set([qt]),cg=new Set(yc),lg=new Set(["GET","POST","PUT","DELETE"]);function vc(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 bc(e){return ag.has(e)||sg.some((t)=>e===t||e.startsWith(`${t}/`))}function Ai(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&&bc(e))throw Error(`Invalid HTTP route path "${e}" declared by plugin "${t}"`)}function Sc(e,t,r){if(!e.has(t))throw Error(`Invalid HTTP route method "${t}" declared by plugin "${r}"`)}function dg(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 ug(e,t){Ai(t.path,e.pluginId);let r=t.method??"GET";Sc(cg,r,e.pluginId);let i=t.match??"exact";dg(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)=>!bc(o)&&n(o)}:{},handler:t.handler})}function pg(e,t){Ai(t.path,e.pluginId,!1);let r=`/api/${e.pluginId}${t.path}`;if(Ai(r,e.pluginId),Sc(lg,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 mg(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 gg(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 Vt{routes;manifest;apiRoutes;webRoutes;static createFresh(){return new Vt}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(ug(n,o)),r.push(Object.freeze({pluginId:n.pluginId,fullPath:o.path,definition:Object.freeze({...o})}));for(let o of n.apiRoutes){let s=pg(n,o);t.push(s),i.push(Object.freeze({pluginId:n.pluginId,fullPath:s.fullPath,definition:s.definition}))}}return mg(t),this.routes=Object.freeze(t),this.manifest=gg(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 Rc(e,t){e.addFinalizer(()=>t.legacyBinaryLedger.flush()),e.addFinalizer(async()=>{let{entityService:r}=t;if(fg(r))await r.releaseDatabaseLease()}),e.addFinalizer(()=>t.pluginManager.shutdownPlugins()),e.addFinalizer(async()=>{if(t.daemonRegistry.has(Q))await t.daemonRegistry.unregister(Q)}),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 fg(e){return"releaseDatabaseLease"in e&&typeof e.releaseDatabaseLease==="function"}function ki(e){return Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength)}function tC(e,t){return`data:${e};base64,${ki(t).toString("base64")}`}var hg=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")]),Ic=c.object({query:c.string().describe("Search term"),scope:hg.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")}),Pc=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.")}),Cc=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)")}),xc=c.string().min(1).describe("Upload id from the conversation's upload refs"),Tc=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(),Ec=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."),Ve=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:xc,transform:Ec,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(),Tc,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:xc,transform:Ec},{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}),Ve,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()]),yg=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."),prompt:c.string().min(1).describe("Prompt for creating new generated content from the resolved source, written from the user's request without added voice, tone or engagement directions; the style guide supplies the voice.")}).strict(),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()]),Yt=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. Leave it out when saving several uploads: each item in source.items takes its own title."),visibility:wc.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(),Ac=c.object({operation:yg.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(),vg=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(),Ke="An update operation is exactly one of `fields`, `content`, `edits` or `source`.",ji=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(vg).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:Tc.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 re(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(", ")}: ${Ke}`}}).refine((e)=>[e.fields,e.content,e.edits,e.source].filter((t)=>t!==void 0).length===1,{message:Ke}).describe(Ke),Xt=c.object({entityType:c.string().describe("Entity type"),id:c.string().describe("Entity ID, slug, or title"),operation:ji.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(),kc=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")}),sC=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")}),Dc=c.object({batchId:c.string().optional().describe("Specific batch ID to check"),jobTypes:c.array(c.string()).optional().describe("Filter by job types")}),bg=c.object({entityType:c.string().optional(),entityId:c.string().optional(),attachmentType:c.string().optional()}),Sg=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:bg.optional()}),aC=c.object({entityId:c.string().optional(),status:c.enum(["created","generating"]),jobId:c.string().optional(),attachment:Sg.optional()}),cC=c.object({status:c.literal("extracting"),jobId:c.string(),entityType:c.string(),source:c.string().optional(),mode:c.enum(["derive","rebuild"]).optional()});function Oc(e,t,r){return r==="create"?e.getCreateFieldsSchema(t):e.getEditableFieldsSchema(t)}function Mc(e){if(e instanceof c.ZodOptional||e instanceof c.ZodNullable||e instanceof c.ZodDefault)return Mc(e.unwrap());return e instanceof c.ZodType?e:void 0}function jc(e){try{let{$schema:t,...r}=c.toJSONSchema(e,{target:"draft-7",io:"input"});return r}catch{return}}function Rg(e){return zc({type:"object",properties:{value:e},required:["value"]})!==void 0}function Lc(e,t){let r=new Map,i=new Map,n=e.getAllEntityTypes();for(let d of n){let u=Oc(e,d,t.on);for(let[p,m]of Object.entries(u?.shape??{})){if(t.omit?.includes(p))continue;let g=Mc(m),f=g&&jc(g);if(!g||!f||!Rg(f))continue;let h=r.get(p)??new Map;h.set(JSON.stringify(f),g),r.set(p,h),i.set(p,[...i.get(p)??[],d])}}let o=new Map;for(let[d,u]of r){let[p,...m]=[...u.values()];if(!p)continue;let g=m.length>0?c.union([p,...m]):p,f=JSON.stringify(jc(g)),h=o.get(f)??{value:g,names:[]};h.names.push(d),o.set(f,h)}let s=[...o.values()].map(({value:d,names:u})=>{let[p,...m]=u,g=u.map((f)=>{let h=i.get(f)??[];return`${f} (${h.length===n.length?"every type":h.join(", ")})`}).join("; ");return 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: ${g}.`),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 wg(e){return Object.fromEntries((Array.isArray(e)?e:[]).flatMap((t)=>K(t)&&typeof t.name==="string"?[[t.name,t.value]]:[]))}function er(e,t,r,i){if(!r)return;let{allow:n}=i,o=new Set(Object.keys(Oc(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 Oi(e){return"fields"in e&&e.fields!==void 0?{...e,fields:wg(e.fields)}:e}function Uc(e){return{prepare:()=>e.ensureGroupingsCurrent(),inputSchema:()=>{let t=Lc(e,{on:"create",omit:["visibility"]}),r=Ve.shape.items.element,i=Ve.extend({items:c.array(r.extend({fields:t.optional().describe("Field changes the user stated for this file alone, one { name, value } per field, such as the date and address it was first published at: [{ name: 'publishedAt', value }, { name: 'canonicalUrl', value }]; facts shared by every file go in the top-level fields.")})).min(2).max(20)}),[n,...o]=Di.options.map((s)=>s===Ve?i:s);if(!n)throw Error("system_create has no source branches");return{...Yt.shape,source:c.discriminatedUnion("kind",[n,...o]).describe("Concrete source selector. Use exactly one source branch. For AI generation or source-derived artifacts, use system_generate instead."),fields:t.optional().describe("Field changes for facts the user states outside the source text, one { name, value } per field, e.g. a post first published elsewhere: [{ name: 'status', value: 'published' }, { name: 'publishedAt', value: '2025-03-12' }, { name: 'canonicalUrl', value }]; the section a doc goes in, named exactly as the user names it: [{ name: 'section', value }]; the year a project began: [{ name: 'year', value }]. Never copy values from the text or its frontmatter; omit when nothing extra is stated.")}},toToolInput:(t)=>{let r=t.source;return Oi({...t,...K(r)&&Array.isArray(r.items)&&{source:{...r,items:r.items.map((i)=>K(i)?Oi(i):i)}}})}}}function zi(e){let t=e.unwrap();return e.description?t.describe(e.description):t}function Bc(e){let{content:t,edits:r,source:i}=ji.shape;return{prepare:()=>e.ensureGroupingsCurrent(),inputSchema:()=>({...Xt.shape,operation:c.union([c.strictObject({fields:Lc(e,{on:"update"}).describe("Change frontmatter or metadata fields, one { name, value } per field changed. Use this for status, title, coverImageId, ogImageId, and metadata changes such as approving an agent. To set an existing image as an entity cover, change coverImageId to that image id. To remove a field, such as a cover image, give it the value null, not an empty string. Do not use fields for anchor-profile; anchor-profile updates require the content operation.")}),c.strictObject({content:zi(t)}),c.strictObject({edits:zi(r)}),c.strictObject({source:zi(i)})]).describe("Exactly one update operation")}),toToolInput:(n)=>{let o=n.operation;return K(o)?{...n,operation:Oi(o)}:n}}}function V(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}}var Ig="system";function ye(e){return{kind:"error",result:e}}function T(e,t){return ye({success:!1,error:e,...t!==void 0&&{code:t}})}function N(e,t,r,i,n={}){let{visibility:o="admin",sideEffects:s}=n;return{name:`${Ig}_${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 rr(e){return{interfaceType:e.interfaceType,actor:e.actor,userPermissionLevel:e.userPermissionLevel??"public",...e.channelId&&{channelId:e.channelId},...e.channelName&&{channelName:e.channelName}}}async function $c(e,t,r,i){let n=await t(r,rr(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=V(e,o.entityType,"create",i);if(s)return{kind:"error",result:s};return{kind:"continue",createInput:o}}function De(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 je(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 Mi(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 ir(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var Pg={base:"note"};function _c(e){return Pg[e]??e.replaceAll("-"," ")}function nr(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 Zc(e){return!!e&&Object.keys(e.shape).length>0}async function Fc(e,t,r){if(!r)return!1;let i=await e.conversationService.getMessages(r,{limit:100});for(let n of i){let s=tr(n.metadata)?.attachments;if(!Array.isArray(s))continue;for(let a of s){if(!re(a))continue;let l=a.source;if(!re(l))continue;if(l.kind===t.kind&&l.id===t.id)return!0}}return!1}async function or(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"&&!V(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 Nc(e){return`Replaces: failed ${e.entityType} "${e.id}"`}async function Hc(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 sr(e,t,r){let i=De(e,t);if(i)return ye(i);let n=V(e,t,"create",r);if(n)return ye(n);return{kind:"ok",value:{interceptor:e.entityRegistry.getCreateInterceptor(t)}}}async function ar(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
+ ${Nc(i)}`:a,args:t.buildArgs((d)=>({...l,confirmed:!0,confirmationToken:d}))}}async function Ye(e,t,r){let i=await Hc(e,r.replacesFailed);if(i)return i;if(!r.interceptor)return r.persist(r.createInput);let n=await $c(e,r.interceptor,r.createInput,t);if(n.kind!=="continue")return n.result;return r.persist(n.createInput)}async function cr(e,t,r,{confirmed:i}){let n=r.conversationId??r.channelId;if(!n)return{success:!1,error:"Conversation message is not accessible in this conversation or does not exist."};let o=await e.conversationService.getMessages(n,{limit:100}),s=t.kind==="user-message",a=s?o.filter((y)=>{if(y.role!=="user")return!1;let S=r.userPermissionLevel??"public";if(S==="admin")return!0;let R=tr(y.metadata)?.userPermissionLevel;return(R==="public"||R==="trusted"||R==="admin")&&e.permissionService.hasPermission(S,R)}):o.filter(Wc),l=t.messageId?a.find((y)=>y.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=Eg(Tg(t,l.content),l.content),u=(y,S,R,w)=>{if(!S)return{offset:R};let C=`${y} ${JSON.stringify(S)}`;if(d.boundaryMode==="lines"&&/[\r\n]/.test(S))return{problem:`${C} contains a newline; in lines mode give the marker line's text only`};let E=Cg(l.content,S,d.boundaryMode==="lines"?"lines":"literal",w),[B]=E;if(E.length===1&&B!==void 0)return{offset:B};return{problem:E.length===0?`${C} does not occur in the message`:`${C} occurs ${E.length} times in the message`}},p=u("startAfter",d.startAfter,0,!0),m=d.boundaryMode==="frontmatter"&&"offset"in p?kg(l.content,p.offset):p,g=u("endBefore",d.endBefore,l.content.length,!1),f=[m,g].flatMap((y)=>("problem"in y)?[y.problem]:[]);if(f.length===0&&"offset"in m&&"offset"in g&&m.offset>=g.offset)f.push("startAfter must come before endBefore with content between them");if(!("offset"in m)||!("offset"in g)||f.length>0)return{success:!1,error:`User-message boundary ${f.join("; ")}; each boundary must occur exactly once. ${Ag(l.content)}`};let h=l.content.slice(m.offset,g.offset).replace(/^(?:[ \t]*\r?\n)+(?=---\r?\n)/,""),v=i?t.contentHash:void 0;if(v&&v!==J(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 lr(e,t){let{startAfter:r,endBefore:i,...n}=t.source??e;return{...n,...r?{startAfter:r}:{},...i?{endBefore:i}:{},messageId:t.messageId,contentHash:J(t.content)}}function Cg(e,t,r,i){if(r==="lines"){let o=Li(e,t,i);return o.length>0||!t.trim()?o:Li(e,t,i,xg)}let n=qc(e,t,i);return n.length>0?n:Dg(e,t,i)}function xg(e){return e.trim().replace(/\s+/g," ")}function Tg(e,t){let r=(a)=>a?.trim()==="---";if(!r(e.startAfter)&&!r(e.endBefore))return e;if((t.match(/^---\r?$/gm)?.length??0)!==2||Ui(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 Eg(e,t){let{startAfter:r,endBefore:i}=e;if(e.boundaryMode!==void 0||!r||!i)return e;let n=(o)=>!/[\r\n]/.test(o)&&Li(t,o,!0).length===1;return n(r)&&n(i)?{...e,boundaryMode:"lines"}:e}function Ag(e){return Ui(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 kg(e,t){let r=Ui(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 Ui(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 Li(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 Dg(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(jg).join("\\s+")+n(/\s$/.test(t)),"g");return Array.from(e.matchAll(o),(s)=>s.index+(r?s[0].length:0))}function jg(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function qc(e,t,r,i=0){let n=e.indexOf(t,i);if(n<0)return[];return[n+(r?t.length:0),...qc(e,t,r,n+1)]}var zg=/^[ \t]*---[ \t]*$/gm;function Jc(e){return e.replace(/\s+/g," ").trim()}function Og(e){return e.kind==="user-message"?e.messageId:void 0}class Bi{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=Og(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&&Jc(t.content.replace(zg,""))===Jc(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 Gc(e){if(e.kind!=="user-message")return e;let{contentHash:t,...r}=e;return r}function _i(e){return`${e.entityType} "${e.title}"`}function Mg(e){return Object.entries(e).map(([t,r])=>`${t}: ${typeof r==="string"?r:JSON.stringify(r)}`).join(", ")}function Qc(e){return"error"in e?e.error:"the save was not completed"}function Lg(e){let t=new Map;for(let r of e){let i=`${r.entityType}:${X(r.title)}`,n=t.get(i);if(n)return`${n.filename} and ${r.filename} would both be saved as ${_i(r)}. Give them different titles in source.items.`;t.set(i,r)}return}function Ug(e,t){return{summary:`Save ${e.length} uploaded files?`,completionSummary:`Saved ${e.length} uploaded files: ${e.map(_i).join(", ")}.`,preview:[...e.map((r,i)=>[`${i+1}. ${r.filename} \u2192 ${_i(r)}`,...r.fields?[` ${Mg(r.fields)}`]:[],...r.replacesFailed?[` Replaces failed ${r.replacesFailed}`]:[]].join(`
79
79
  `)),`Visibility: ${t??"public"}`].join(`
80
- `)}}async function Ug(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,...Q(n.data)?n.data:{}});else r.push(`${i.filename}: ${Qc(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 Kc(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}): ${Qc(d.result)}`};i.push(d.value)}let n=Mg(i);if(n)return{success:!1,error:n};if(t.confirmed){let a=r.validateConfirmed(t.confirmationToken,t);if(a)return a;return Ug(i)}let o=Lg(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 Bg(e){return{summary:`Save uploaded file${e.title?` as "${e.title}"`:""}?`,preview:[`Filename: ${e.filename}`,`Media type: ${e.mediaType}`,`Entity type: ${e.entityType}`,`Visibility: ${e.visibility??"public"}`,...e.title?[`Title: ${e.title}`]:[]].join(`
81
- `)}}function $g(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 _g(e){let t=e.title?` "${e.title}"`:"";return`Saved ${e.entityType}${t}.`}function Zg(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 Fg(e,t,r){let i=await H(e.entityService,t.entityType,t.entityId,e.logger,"Source entity",A(r.userPermissionLevel));if(!i.ok)return T(i.error);let{entity:n}=i,o=Vc(n.content);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 Ng(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 lr(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 Hg(e,t){let r=rr(t);return e.handler({upload:e.upload,...e.title&&{title:e.title},...e.visibility!==void 0?{visibility:e.visibility}:{}},r)}async function Wg(e,t,r){let{entityService:i,entityRegistry:n}=e,o=Y(t.title??`${t.entityType}-${Date.now()}`),s=n.getEffectiveFrontmatterSchema(t.entityType),a=t.content!==void 0&&Zc(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:t.fields?dr(t.fields,t.content):t.content,...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 qg(e,t,r){let{content:i,url:n,from:o,uploadRef:s,conversationMessageRef:a,entityRef:l,transform:d}=Zg(t.source),u=l?await Fg(e,l,r):void 0;if(u?.kind==="error")return u;let p=a?await cr(e,a,r,{confirmed:t.confirmed===!0}):void 0;if(p&&!p.success)return ye(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 Jg(e,t){if(!Zi(t.mediaType))return;let{content:r}=await e.runtimeUploads.scoped(xe).read(t.id);return ki(r).toString("utf8")}async function Gg(e,t,r){if(!await Fc(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(xe).readRecord(t.uploadRef.id),o=t.transform==="extract-markdown"?await Jg(e,{id:t.uploadRef.id,mediaType:n.mediaType}):void 0}catch{return T("Upload ref not found")}let s=Xc({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=Zi(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 Qg(e,t,r){let i=t?pr(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(!ur(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 Kg(e,t,r){return or(e,{entityType:t.entityType,candidateId:t.title?Y(t.title):void 0,replace:t.replace===!0,copyHint:"create a new copy intentionally"},r)}function Vg(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 Yg(e,t,r){let i=e.entityRegistry.getCreateCheck(t.entityType);if(!i)return{kind:"ready"};try{return await i(t,rr(r))}catch(n){return{kind:"error",error:P(n,`Could not check the ${t.entityType}`)}}}function Xg(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(Gc(t))}.`,e.answerWith].join(" ")}function ef(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 el='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 tf(e,t,r,i,n){let o=await qg(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 rf(e,t,{source:r,retry:i},n){let o=r.uploadRef?await Gg(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=Vg(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 nf(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=Qg(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=ir(e.title),g=(a&&Yc(m,a.filename)?void 0:m)??r?.title??a?.title,f=e.replace===!0;return{kind:"ok",value:{entityType:i,...g&&{title:g},...u.value!==void 0?{visibility:u.value}:{},...n&&{content:n},...t&&{url:t},...o&&{from:o},...s&&{transform:s},...p&&{fields:p},...f&&{replace:f}}}}async function of(e,t,r,i){let n=await Yg(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(Xg(n,i.source,i.several))}return{kind:"ok",value:ef(t,n)}}async function tl(e,t,r,i,n){if(!(t.source.kind==="upload"&&t.source.transform==="preserve")){let C=De(e,t.entityType);if(C)return ye(C)}let s=$i(r.conversationId??r.channelId,t.entityType),a=await tf(e,t,r,i,s);if(a.kind==="error")return a;let{source:l}=a.value,d=await rf(e,t,a.value,r);if(d.kind==="error")return d;let{content:u,upload:p}=d.value,m=p?.uploadPreserve,g=nf(t,l,d.value,r);if(g.kind==="error")return g;let f=g.value,h=sr(e,f.entityType,r);if(h.kind==="error")return h;let{interceptor:v}=h.value;if(!f.content&&!v&&!m)return T(el);let y=Ng(t.source,a.value,u),S=t.confirmed||m?{kind:"ok",value:f}:await of(e,f,r,{source:y,several:n,pinnable:l.uploadRef?void 0:u,pending:i,pendingKey:s});if(S.kind==="error")return S;let R=S.value,w=await Kg(e,R,r);if(w.kind==="error")return w;return{kind:"ok",value:{createInput:R,confirmationSource:y,interceptor:v,eventContext:je(r),...p&&{uploadFilename:p.filename},...l.uploadRef&&{uploadId:l.uploadRef.id},...w.value&&{replacesFailed:w.value},...m&&{uploadPreserve:m}}}}async function rl(e,t,r,i){let n=await sf(e,t,r,i),{uploadId:o}=t;if(o===void 0||!("success"in n)||!n.success)return n;if(!Q(n.data))return n;return{...n,data:{entityType:t.createInput.entityType,...n.data,uploadId:o}}}async function sf(e,t,r,i){let{createInput:n,eventContext:o,uploadPreserve:s,replacesFailed:a}=t;if(s)return Ye(e,r,{createInput:n,interceptor:void 0,replacesFailed:a,persist:()=>Hg({upload:s.upload,...n.title&&{title:n.title},...n.visibility!==void 0?{visibility:n.visibility}:{},handler:s.handler},r)});let l=await Ye(e,r,{createInput:n,interceptor:t.interceptor,replacesFailed:a,persist:async(u)=>u.content?Wg(e,u,o):{success:!1,error:el}}),d=$i(r.conversationId??r.channelId,n.entityType);if(d&&"success"in l&&l.success)i.clear(d);return l}async function af(e,t,r,i,n){let o={...t.fields,...r.fields},s=await tl(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:()=>rl(e,a,i,n)}}}function cf(e){let{createInput:t,uploadPreserve:r}=e,{summary:i,preview:n}=r?Bg({...t.title&&{title:t.title},filename:r.filename,mediaType:r.mediaType,entityType:t.entityType,visibility:t.visibility}):$g(t);return{toolName:"system_create",summary:i,completionSummary:_g(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 il(e){let t=V({label:"create",requestNoun:"creation"}),r=new Bi;return{...N("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.",Yt,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)=>er(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 Kc({input:{...n,source:n.source},gate:t,prepare:(d)=>af(e,n,d,o,r)});let a=await tl(e,n,o,r);if(a.kind==="error")return a.result;let l=a.value;return ar({gate:t,input:n,replacesFailed:l.replacesFailed,confirmation:()=>cf(l),run:()=>rl(e,l,o,r)})},{visibility:"trusted",sideEffects:"writes"}),modelInput:Uc(e.entityRegistry)}}function lf(e){let t=e.title?` "${e.title}"`:` ${e.entityType}`,r=e.from?.kind==="entity-attachment"?e.from:void 0,i=[`Entity type: ${e.entityType}`,...e.title?[`Title: ${e.title}`]:[],...e.prompt?[`Prompt: ${e.prompt}`]:[],...r?[`Source attachment: ${r.sourceEntityType}/${r.sourceEntityId} (${r.attachmentType})`]:[],...e.targetEntityType&&e.targetEntityId?[`Target: ${e.targetEntityType}/${e.targetEntityId}`]:[]];return{summary:`Generate${t}?`,preview:i.join(`
83
- `)}}async function Fi(e,t,r,i){let n=await H(e.entityService,t.entityType,t.entityId,e.logger,void 0,r);if(!n.ok)return T(n.error,i);return{kind:"ok",value:{...t,entityId:n.entity.id}}}async function df(e,t,r,i){let n=await Fi(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 uf(e,t,r,i,n){let{entityService:o,jobs:s}=e,a=Ni(Y(t.title??r),100);if(!a)return{success:!1,error:"Could not derive a slug from the provided title/prompt. Provide a 'title' with at least one URL-safe character."};let l=t.title??a,d=nl(e.entityRegistry,{entityType:t.entityType,id:a,title:l});if(!d)return{success:!1,error:`Entity type '${t.entityType}' does not support queued generation. Provide an exact source to system_create instead.`};let u;try{u=(await o.createEntity({entity:d,options:{deduplicateId:!0,...i?{eventContext:i}:{}}})).entityId}catch(g){return{success:!1,error:P(g,"Failed to persist generation stub")}}let p={entityId:u,prompt:r,...t.title&&{title:t.title},...t.sourceEntityType&&{sourceEntityType:t.sourceEntityType},...t.sourceEntityId&&{sourceEntityId:t.sourceEntityId},...t.sourceEntityIds&&{sourceEntityIds:t.sourceEntityIds},...t.targetEntityType&&{targetEntityType:t.targetEntityType},...t.targetEntityId&&{targetEntityId:t.targetEntityId}},m=e.entityRegistry.getGenerationEnqueuer(t.entityType);try{let g=m?await m(p,n):await s.enqueue({type:`${t.entityType}:generation`,data:p,toolContext:n});return{success:!0,data:{entityId:u,status:"generating",jobId:g}}}catch(g){return await o.deleteEntity({entityType:t.entityType,id:u}).catch((f)=>{e.logger.warn("Failed to remove unqueued generation stub",{entityType:t.entityType,entityId:u,error:f})}),{success:!1,error:P(g,"Failed to queue generation job")}}}async function pf(e,t,r){let i=ir(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 Fi(e,t.source,r,"source-not-found"):void 0;if(l?.kind==="error")return l;return{kind:"ok",value:{createInput:{entityType:t.entityType,...i?{title:i}:{},prompt:t.prompt,...l&&{sourceEntityType:l.value.entityType,sourceEntityId:l.value.entityId,sourceEntityIds:[l.value.entityId]}},sourceAttachment:void 0}}}if(t.kind==="standalone-image")return{kind:"ok",value:{createInput:{entityType:"image",...i?{title:i}:{},prompt:t.prompt},sourceAttachment:void 0}};if(t.kind==="cover-image"){let l=await Fi(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}}}let n=await df(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}}}async function mf(e,t,r){let i=t.operation,n=A(r.userPermissionLevel),o=await pf(e,i,n);if(o.kind==="error")return o;let{createInput:s,sourceAttachment:a}=o.value,l=sr(e,s.entityType,r);if(l.kind==="error")return l;let{interceptor:d}=l.value;if(!s.prompt&&!s.from)return T("Provide a generation source.");if(s.from&&!d)return T(`Entity type '${s.entityType}' does not support attachment-based generation. Use operation.kind prompt-from-source for AI-generated content based on referenced source material, or choose an entity type with an attachment provider.`,"unsupported-generation");let u=i.kind==="prompt"||i.kind==="prompt-from-source",p=d&&!u?void 0:await or(e,{entityType:s.entityType,candidateId:s.prompt?Ni(Y(s.title??s.prompt),100):s.title?Y(s.title):void 0,replace:s.replace===!0,copyHint:"generate a new copy intentionally"},r);if(p?.kind==="error")return p;return{kind:"ok",value:{createInput:s,operation:gf(i,s,a),interceptor:d,eventContext:je(r),...p?.value&&{replacesFailed:p.value}}}}function gf(e,t,r){if(e.kind==="attachment"){let i=r??{sourceEntityType:e.source.entityType,sourceEntityId:e.source.entityId,attachmentType:e.attachmentType};return{kind:"attachment",source:{entityType:i.sourceEntityType,entityId:i.sourceEntityId},attachmentType:i.attachmentType,...t.title&&{title:t.title},...t.replace&&{replace:t.replace}}}if(e.kind==="cover-image")return{kind:"cover-image",target:{entityType:t.targetEntityType??e.target.entityType,entityId:t.targetEntityId??e.target.entityId},...t.title&&{title:t.title},prompt:e.prompt};if(e.kind==="standalone-image")return{kind:"standalone-image",...t.title&&{title:t.title},prompt:e.prompt};if(e.kind==="prompt-from-source")return{kind:"prompt-from-source",entityType:t.entityType,...t.title&&{title:t.title},source:{entityType:t.sourceEntityType??e.source.entityType,entityId:t.sourceEntityId??e.source.entityId},prompt:e.prompt};return{kind:"prompt",entityType:t.entityType,...t.title&&{title:t.title},prompt:e.prompt}}function ol(e){let t=V({label:"generate",requestNoun:"generation"});return N("generate","Generate durable content or artifacts. Requires confirmation: calling this tool without confirmed is how you request it, so when the user asks to create, write, draft, or generate new durable content without supplying final exact content, call it instead of drafting the content in chat, asking for separate prose approval, or saying 'I can generate it if you want' or 'I need to queue it first'. Critical: broad or underspecified topical generation uses operation.kind prompt with no source field, also in the same turn after an optional search finds no source; preserve the user's wording as the prompt and do not stop to ask what details to highlight. Critical: to generate from an existing source such as 'my latest blog post', resolve it with read/search/list tools unless the user gives an exact entity id in quotes, then call operation.kind prompt-from-source right away, for example { kind: 'prompt-from-source', entityType: 'newsletter', source: { entityType: 'post', entityId: '...' }, prompt: '...' }. For the latest published/blog source, use system_list on that type (blog posts: entityType post) and choose the newest candidate by publishedAt, not updated/created or semantic search order; do not stop with prose like 'I found it and can generate it' or 'if that is the one you mean.' Never invent source IDs, use brain-character/profile, uploads, filenames, guessed ids, or placeholders as source refs. Turning an existing entity into another type ('turn my note X into a post') keeps its text and is not generation: call system_create with source.kind entity, also after a search resolves it. Use system_create as well for saving/importing existing text, URLs, uploads, prior assistant responses, or raw uploaded files. Critical: for a request to generate a post/social-post/newsletter/etc. with a cover image, call only the prompt generation first; call cover-image only once the target entity exists after confirmation, never guess its future id, and never use standalone-image as a substitute for a requested cover. When a cover-image request names the target's exact id in quotes or a search/get resolves a clear target, call cover-image in the same turn; do not stop after saying you found the entity. Use attachment for source-derived artifacts: attachmentType og-image for OG/social preview renders (the provider updates ogImageId), carousel for deck carousel PDFs, printable for post/project PDFs. Call it immediately for save/render requests, with replace:true for regenerate/replace/refresh, instead of saying you can queue it later. To attach a generated artifact to another entity, generate the artifact first in the same turn \u2014 do not ask whether they mean an existing artifact when the source entity is explicit or given as a quoted id such as deck `distributed-systems-primer` \u2014 and update the target only after the real artifact ID exists.",Ac,async(r,i)=>{let n=await mf(e,r,i);if(n.kind==="error")return n.result;let{createInput:o,operation:s,interceptor:a,eventContext:l,replacesFailed:d}=n.value;return ar({gate:t,input:r,replacesFailed:d,confirmation:()=>({toolName:"system_generate",...lf(o),args:{operation:s}}),run:()=>Ye(e,i,{createInput:o,interceptor:a,replacesFailed:d,persist:async(u)=>{if(!u.prompt)return{success:!1,error:"Attachment generation is supported only for entity types that explicitly handle source-derived artifacts."};return uf(e,u,u.prompt,l,i)}})})},{visibility:"trusted",sideEffects:"writes"})}function sl(e){let{entityService:t,entityRegistry:r,logger:i}=e,n=V({label:"delete",requestNoun:"deletion"});return N("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.",kc,async(o,s)=>{if((s.userPermissionLevel??"public")==="public")return{success:!1,error:"Changing content requires higher permission; current permission is Public."};let a=K(e,o.entityType,"delete",s);if(a)return a;let l=De(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 H(t,o.entityType,o.id,i,void 0,d,{binaryContent:"reference"});if(!u.ok)return{success:!1,error:u.error};let{entity:p}=u;if(o.confirmed){let f=n.validateConfirmed(o.confirmationToken,o);if(f)return f;try{await t.deleteEntity({entityType:o.entityType,id:p.id})}catch(h){return{success:!1,error:P(h,"Failed to delete entity")}}return{success:!0,data:{deleted:p.id}}}let m=nr(p),g=n.buildArgs((f)=>({...o,id:p.id,confirmed:!0,confirmationToken:f}));return{needsConfirmation:!0,toolName:"system_delete",summary:`Delete "${m}"?`,preview:p.content.slice(0,200),args:g}},{visibility:"admin",sideEffects:"writes"})}function al(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 nn}from"util";class mr{diff(e,t,r={}){let i;if(typeof r==="function")i=r,r={};else if("callback"in r)i=r.callback;let n=this.castInput(e,r),o=this.castInput(t,r),s=this.removeEmpty(this.tokenize(n,r)),a=this.removeEmpty(this.tokenize(o,r));return this.diffWithOptionsObj(s,a,r,i)}diffWithOptionsObj(e,t,r,i){var n;let o=(y)=>{if(y=this.postProcess(y,r),i){setTimeout(function(){i(y)},0);return}else return y},s=t.length,a=e.length,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}],g=this.extractCommon(m[0],t,e,0,r);if(m[0].oldPos+1>=a&&g+1>=s)return o(this.buildValues(m[0].lastComponent,t,e));let f=-1/0,h=1/0,v=()=>{for(let y=Math.max(f,-l);y<=Math.min(h,l);y+=2){let S,R=m[y-1],w=m[y+1];if(R)m[y-1]=void 0;let C=!1;if(w){let B=w.oldPos-y;C=w&&0<=B&&B<s}let E=R&&R.oldPos+1<a;if(!C&&!E){m[y]=void 0;continue}if(!E||C&&R.oldPos<w.oldPos)S=this.addToPath(w,!0,!1,0,r);else S=this.addToPath(R,!1,!0,1,r);if(g=this.extractCommon(S,t,e,y,r),S.oldPos+1>=a&&g+1>=s)return o(this.buildValues(S.lastComponent,t,e))||!0;else{if(m[y]=S,S.oldPos+1>=a)h=Math.min(h,y-1);if(g+1>=s)f=Math.max(f,y+1)}}l++};if(i)(function y(){setTimeout(function(){if(l>d||Date.now()>p)return i(void 0);if(!v())y()},0)})();else while(l<=d&&Date.now()<=p){let y=v();if(y)return y}}addToPath(e,t,r,i,n){let o=e.lastComponent;if(o&&!n.oneChangePerToken&&o.added===t&&o.removed===r)return{oldPos:e.oldPos+i,lastComponent:{count:o.count+1,added:t,removed:r,previousComponent:o.previousComponent}};else return{oldPos:e.oldPos+i,lastComponent:{count:1,added:t,removed:r,previousComponent:o}}}extractCommon(e,t,r,i,n){let o=t.length,s=r.length,a=e.oldPos,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 g=r[l+m];return g.length>p.length?g:p}),d.value=this.join(u)}else d.value=this.join(t.slice(a,a+d.count));if(a+=d.count,!d.added)l+=d.count}else d.value=this.join(r.slice(l,l+d.count)),l+=d.count}return i}}class cl extends mr{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}}var ll=new cl;function gr(e,t,r){return ll.diff(e,t,r)}var ve=c.enum(["png","jpg","jpeg","webp","gif","svg"]),ul=c.enum(["pending","draft","failed"]),pl=c.object({title:c.string().optional(),alt:c.string().optional(),format:ve.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:ul.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",ve],["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]})}}),ml=dl.extend({entityType:c.literal("image"),metadata:pl}),ff=c.object({url:c.string(),alt:c.string(),title:c.string(),width:c.number(),height:c.number()});function gl(e){return/^https?:\/\//i.test(e)}async function fl(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 et(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 tt(e){let t=et(e);if(!t)throw Error("Invalid image data URL");return t}function fr(e){let t=e.toLowerCase(),r=t==="svg+xml"?"svg":t,i=ve.safeParse(r);return i.success?i.data:null}async function hf(e){return fl(e,"image/")}function hl(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 be(e){switch(e){case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";default:return`image/${e}`}}var yf=64;async function Hi(e){let t=await e(0,yf),r=hl(t);if(!r)return;let i=r==="jpg"||r==="jpeg"?await bf(e):Gi(t);return{format:r,mediaType:be(r),width:i?.width??0,height:i?.height??0}}function Wi(e){return async(t,r)=>e.subarray(t,r)}function qi(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 vf(e){return(t,r)=>Bun.file(e).slice(t,r).bytes()}async function bf(e){let t=Xe(2),r=async(i)=>i.done?i.value:r(t.next(await e(...i.value)));return r(t.next(new Uint8Array))}function*Xe(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*Xe(e+1);if(r===1||r>=208&&r<=215)return yield*Xe(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*Xe(e+2+i)}function Ji(e){return Gi(Buffer.from(e,"base64"))}function Gi(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=Xe(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 Rf(e){let t=fr(e);if(!t)throw Error(`Unsupported image format: ${e}`);return t}function yl(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 wf(e){if(e===""||rt.safeParse(e).success)return{};let{format:t,base64:r}=tt(e),i=Ji(r);return{format:Rf(t),width:i?.width??0,height:i?.height??0}}function Qi(e){let{title:t,alt:r,...i}=yl(e);return{entityType:"image",content:e.asset.ref,metadata:{title:t,alt:r,...e.description,sizeBytes:e.asset.sizeBytes,...i}}}function If(e){return{entityType:"image",content:"",metadata:yl(e)}}function fT(e){return bl(e,{skipInvalid:!0,noRefs:!0,sortKeys:!0})}function Sl(e){return vl(e)}async function wl(e,t){let r=rt.safeParse(t.content);if(!r.success){let i=et(t.content);if(!i)return;let n=fr(i.format);return{bytes:Buffer.from(i.base64,"base64"),mediaType:n?be(n):`image/${i.format}`}}return{bytes:await Rl(e,r.data),mediaType:Pf(t)}}async function Il(e,t){if(!rt.safeParse(t.content).success)return et(t.content)?t.content:void 0;let r=await wl(e,t);return r&&`data:${r.mediaType};base64,${r.bytes.toString("base64")}`}function Pf(e){let t=e.metadata.mediaType;if(typeof t==="string")return t;let r=ve.safeParse(e.metadata.format);return r.success?be(r.data):"image/png"}var Cf=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,xf=c.record(c.string(),c.unknown());function Pl(e,t){let r=Cf.exec(e.content);if(!r?.[1])return;try{let i=xf.safeParse(Sl(r[1]));if(i.success){let n=i.data[t];return typeof n==="string"?n:void 0}}catch{return}return}function Tf(e){return Pl(e,"coverImageId")}function Ef(e){return Pl(e,"ogImageId")}function Ki(e,t){return{...e,content:it(e.content,"coverImageId",t)}}function Vi(e,t){return{...e,content:it(e.content,"ogImageId",t)}}var Yi=Cl();function Af(e,t){let r=Yi.parse(e),i=new Map;hr(r,"definition",(o)=>{if(!i.has(o.identifier))i.set(o.identifier,o)});let n=new Set;return hr(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?Yi.stringify(r):e}function kf(e){let t=[],r=Yi.parse(e);return hr(r,"image",(i)=>{t.push({url:i.url,alt:i.alt??"",title:i.title??void 0})}),t}var en=26214400,Df=["png","jpg","gif","webp"].map(be);async function jf(e,t,r){let{read:i,bytes:n}=zf(t),o=await Hi(i);if(!o)throw Error("Unsupported image format: not a PNG, JPEG, GIF or WebP");let s=await e.stageAsset(n,{maxBytes:en});return{stagedAsset:s,entity:Qi({...r,asset:s,description:o})}}function zf(e){if("bytes"in e)return{read:Wi(e.bytes),bytes:e.bytes};let{base64:t}=tt(e.dataUrl);return{read:qi(t),bytes:Xi(t)}}var nt=/^---\r?\n(?:[\s\S]*?\r?\n)?---[ \t]*(?:\r?\n|$)/;function tn(e){return e.replace(nt,"")}var xl=400;function yr(e,t,r){if(r===null)return!Object.hasOwn(e,t);return Object.hasOwn(e,t)&&nn(e[t],r)}function ze(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 Mf(e,t,r){if(r.has(t))return vr(e.content).frontmatter[t];return t==="visibility"?e.visibility:e.metadata[t]}function jl(e,t,r){let i=ze(e.entityType,r),n=new Set(Object.keys(r.getAdapter(e.entityType).frontmatterSchema?.shape??{}).filter((s)=>!i.has(s))),o=Object.fromEntries(Object.entries(vr(t).frontmatter).filter(([s])=>!n.has(s)));return Object.keys(o).length>0?{...e,content:dr(o,e.content)}:e}function zl(e,t,r){let{visibility:i,coverImageId:n,ogImageId:o,...s}=t,a=i===void 0?e.visibility:kl.parse(i),l=Object.hasOwn(t,"coverImageId")?Ki(e,typeof n==="string"?n:null):e,d=Object.hasOwn(t,"ogImageId")?Vi(l,typeof o==="string"?o:null):l,u={...e.metadata};for(let[f,h]of Object.entries(s))if(h===null)delete u[f];else u[f]=h;let p={...d,visibility:a,metadata:u};for(let[f,h]of Object.entries(s))if(h===null)delete p[f];else p[f]=h;let m=ze(e.entityType,r),g=!1;for(let[f,h]of Object.entries(t)){if(!m.has(f))continue;p.content=it(p.content,f,h),g=!0}if(g)p.metadata=r.projectMetadata(e.entityType,p.content,u);if(r.getAdapter(e.entityType).metadataFromFrontmatter===!0){let f={...p.metadata};for(let h of["coverImageId","ogImageId"]){if(!Object.hasOwn(t,h))continue;let v=t[h];if(typeof v==="string")f[h]=v;else delete f[h]}p.metadata=f}return p}function Lf(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(nn(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:pr(t)??e.visibility}}var Uf=new Set(["visibility","coverImageId","ogImageId"]),Bf=c.record(c.string(),c.unknown());function $f(e,t,r,i){if(t.kind!=="fields")return;let n=t.fields,o=r.getEffectiveFrontmatterSchema(e.entityType);if(!o)return;let s=ze(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),v=i.serializeEntity(h),y=vr(v).frontmatter,S=i.deserializeEntity(v,e.entityType).metadata??{};for(let R of a){let w=n[R];if(!yr(y,R,w)||!yr(S,R,w))return{success:!1,error:`The requested ${R} 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)&&(!Uf.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 g=[],f=[];for(let h of u){let v=n[h];if(Object.hasOwn(m,h)){if(!yr(m,h,v))g.push(h)}else if(v!==null||!Object.hasOwn(e.metadata,h))f.push(h)}if(f.length>0){let h;try{h=p.parseFrontMatter(p.toMarkdown(l),Bf)}catch{if(g.length===0)return}if(h){for(let v of f)if(!yr(h,v,n[v]))g.push(v)}}if(g.length===0)return;return{success:!1,error:`${e.entityType} does not persist ${g.join(", ")} through 'fields'. The update would report success without changing anything. Provide full markdown with frontmatter via 'content' instead.`}}function Ol(e,t,r){let i=nt.exec(e.content)?.[0];if(i===void 0||!t.trim()||nt.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 _f(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&&!nt.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 Zf(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 Ff(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 Ml(e,t,r){let i=ze(e.entityType,r);if(t.kind==="fields")return Object.entries(t.fields).map(([a,l])=>{let d=Mf(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)"}`,g=l===null?"(removed)":JSON.stringify(l);return`${a}: ${m} \u2192 ${g}`}).join(`
80
+ `)}}async function Bg(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,...K(n.data)?n.data:{}});else r.push(`${i.filename}: ${Qc(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 Kc(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}): ${Qc(d.result)}`};i.push(d.value)}let n=Lg(i);if(n)return{success:!1,error:n};if(t.confirmed){let a=r.validateConfirmed(t.confirmationToken,t);if(a)return a;return Bg(i)}let o=Ug(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 $g(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
+ `)}}function _g(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 Zg(e){let t=e.title?` "${e.title}"`:"";return`Saved ${e.entityType}${t}.`}function Fg(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 Ng(e,t,r){let i=await H(e.entityService,t.entityType,t.entityId,e.logger,"Source entity",A(r.userPermissionLevel));if(!i.ok)return T(i.error);let{entity:n}=i,o=Vc(n.content);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 Hg(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 lr(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 Wg(e,t){let r=rr(t);return e.handler({upload:e.upload,...e.title&&{title:e.title},...e.visibility!==void 0?{visibility:e.visibility}:{}},r)}async function qg(e,t,r){let{entityService:i,entityRegistry:n}=e,o=X(t.title??`${t.entityType}-${Date.now()}`),s=n.getEffectiveFrontmatterSchema(t.entityType),a=t.content!==void 0&&Zc(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:t.fields?dr(t.fields,t.content):t.content,...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 Jg(e,t,r){let{content:i,url:n,from:o,uploadRef:s,conversationMessageRef:a,entityRef:l,transform:d}=Fg(t.source),u=l?await Ng(e,l,r):void 0;if(u?.kind==="error")return u;let p=a?await cr(e,a,r,{confirmed:t.confirmed===!0}):void 0;if(p&&!p.success)return ye(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 Gg(e,t){if(!Zi(t.mediaType))return;let{content:r}=await e.runtimeUploads.scoped(xe).read(t.id);return ki(r).toString("utf8")}async function Qg(e,t,r){if(!await Fc(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(xe).readRecord(t.uploadRef.id),o=t.transform==="extract-markdown"?await Gg(e,{id:t.uploadRef.id,mediaType:n.mediaType}):void 0}catch{return T("Upload ref not found")}let s=Xc({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=Zi(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 Kg(e,t,r){let i=t?pr(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(!ur(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 Vg(e,t,r){return or(e,{entityType:t.entityType,candidateId:t.title?X(t.title):void 0,replace:t.replace===!0,copyHint:"create a new copy intentionally"},r)}function Yg(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 Xg(e,t,r){let i=e.entityRegistry.getCreateCheck(t.entityType);if(!i)return{kind:"ready"};try{return await i(t,rr(r))}catch(n){return{kind:"error",error:P(n,`Could not check the ${t.entityType}`)}}}function ef(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(Gc(t))}.`,e.answerWith].join(" ")}function tf(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 el='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 rf(e,t,r,i,n){let o=await Jg(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 nf(e,t,{source:r,retry:i},n){let o=r.uploadRef?await Qg(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=Yg(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 of(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=Kg(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=ir(e.title),g=(a&&Yc(m,a.filename)?void 0:m)??r?.title??a?.title,f=e.replace===!0;return{kind:"ok",value:{entityType:i,...g&&{title:g},...u.value!==void 0?{visibility:u.value}:{},...n&&{content:n},...t&&{url:t},...o&&{from:o},...s&&{transform:s},...p&&{fields:p},...f&&{replace:f}}}}async function sf(e,t,r,i){let n=await Xg(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(ef(n,i.source,i.several))}return{kind:"ok",value:tf(t,n)}}async function tl(e,t,r,i,n){if(!(t.source.kind==="upload"&&t.source.transform==="preserve")){let C=De(e,t.entityType);if(C)return ye(C)}let s=$i(r.conversationId??r.channelId,t.entityType),a=await rf(e,t,r,i,s);if(a.kind==="error")return a;let{source:l}=a.value,d=await nf(e,t,a.value,r);if(d.kind==="error")return d;let{content:u,upload:p}=d.value,m=p?.uploadPreserve,g=of(t,l,d.value,r);if(g.kind==="error")return g;let f=g.value,h=sr(e,f.entityType,r);if(h.kind==="error")return h;let{interceptor:v}=h.value;if(!f.content&&!v&&!m)return T(el);let y=Hg(t.source,a.value,u),S=t.confirmed||m?{kind:"ok",value:f}:await sf(e,f,r,{source:y,several:n,pinnable:l.uploadRef?void 0:u,pending:i,pendingKey:s});if(S.kind==="error")return S;let R=S.value,w=await Vg(e,R,r);if(w.kind==="error")return w;return{kind:"ok",value:{createInput:R,confirmationSource:y,interceptor:v,eventContext:je(r),...p&&{uploadFilename:p.filename},...l.uploadRef&&{uploadId:l.uploadRef.id},...w.value&&{replacesFailed:w.value},...m&&{uploadPreserve:m}}}}async function rl(e,t,r,i){let n=await af(e,t,r,i),{uploadId:o}=t;if(o===void 0||!("success"in n)||!n.success)return n;if(!K(n.data))return n;return{...n,data:{entityType:t.createInput.entityType,...n.data,uploadId:o}}}async function af(e,t,r,i){let{createInput:n,eventContext:o,uploadPreserve:s,replacesFailed:a}=t;if(s)return Ye(e,r,{createInput:n,interceptor:void 0,replacesFailed:a,persist:()=>Wg({upload:s.upload,...n.title&&{title:n.title},...n.visibility!==void 0?{visibility:n.visibility}:{},handler:s.handler},r)});let l=await Ye(e,r,{createInput:n,interceptor:t.interceptor,replacesFailed:a,persist:async(u)=>u.content?qg(e,u,o):{success:!1,error:el}}),d=$i(r.conversationId??r.channelId,n.entityType);if(d&&"success"in l&&l.success)i.clear(d);return l}async function cf(e,t,r,i,n){let o={...t.fields,...r.fields},s=await tl(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:()=>rl(e,a,i,n)}}}function lf(e){let{createInput:t,uploadPreserve:r}=e,{summary:i,preview:n}=r?$g({...t.title&&{title:t.title},filename:r.filename,mediaType:r.mediaType,entityType:t.entityType,visibility:t.visibility}):_g(t);return{toolName:"system_create",summary:i,completionSummary:Zg(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 il(e){let t=Y({label:"create",requestNoun:"creation"}),r=new Bi;return{...N("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.",Yt,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)=>er(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 Kc({input:{...n,source:n.source},gate:t,prepare:(d)=>cf(e,n,d,o,r)});let a=await tl(e,n,o,r);if(a.kind==="error")return a.result;let l=a.value;return ar({gate:t,input:n,replacesFailed:l.replacesFailed,confirmation:()=>lf(l),run:()=>rl(e,l,o,r)})},{visibility:"trusted",sideEffects:"writes"}),modelInput:Uc(e.entityRegistry)}}function df(e){let t=e.title?` "${e.title}"`:` ${e.entityType}`,r=e.from?.kind==="entity-attachment"?e.from:void 0,i=[`Entity type: ${e.entityType}`,...e.title?[`Title: ${e.title}`]:[],...e.prompt?[`Prompt: ${e.prompt}`]:[],...r?[`Source attachment: ${r.sourceEntityType}/${r.sourceEntityId} (${r.attachmentType})`]:[],...e.targetEntityType&&e.targetEntityId?[`Target: ${e.targetEntityType}/${e.targetEntityId}`]:[]];return{summary:`Generate${t}?`,preview:i.join(`
83
+ `)}}async function Fi(e,t,r,i){let n=await H(e.entityService,t.entityType,t.entityId,e.logger,void 0,r);if(!n.ok)return T(n.error,i);return{kind:"ok",value:{...t,entityId:n.entity.id}}}async function uf(e,t,r,i){let n=await Fi(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 pf(e,t,r,i,n){let{entityService:o,jobs:s}=e,a=Ni(X(t.title??r),100);if(!a)return{success:!1,error:"Could not derive a slug from the provided title/prompt. Provide a 'title' with at least one URL-safe character."};let l=t.title??a,d=nl(e.entityRegistry,{entityType:t.entityType,id:a,title:l});if(!d)return{success:!1,error:`Entity type '${t.entityType}' does not support queued generation. Provide an exact source to system_create instead.`};let u;try{u=(await o.createEntity({entity:d,options:{deduplicateId:!0,...i?{eventContext:i}:{}}})).entityId}catch(g){return{success:!1,error:P(g,"Failed to persist generation stub")}}let p={entityId:u,prompt:r,...t.title&&{title:t.title},...t.sourceEntityType&&{sourceEntityType:t.sourceEntityType},...t.sourceEntityId&&{sourceEntityId:t.sourceEntityId},...t.sourceEntityIds&&{sourceEntityIds:t.sourceEntityIds},...t.targetEntityType&&{targetEntityType:t.targetEntityType},...t.targetEntityId&&{targetEntityId:t.targetEntityId}},m=e.entityRegistry.getGenerationEnqueuer(t.entityType);try{let g=m?await m(p,n):await s.enqueue({type:`${t.entityType}:generation`,data:p,toolContext:n});return{success:!0,data:{entityId:u,status:"generating",jobId:g}}}catch(g){return await o.deleteEntity({entityType:t.entityType,id:u}).catch((f)=>{e.logger.warn("Failed to remove unqueued generation stub",{entityType:t.entityType,entityId:u,error:f})}),{success:!1,error:P(g,"Failed to queue generation job")}}}async function mf(e,t,r){let i=ir(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 Fi(e,t.source,r,"source-not-found"):void 0;if(l?.kind==="error")return l;return{kind:"ok",value:{createInput:{entityType:t.entityType,...i?{title:i}:{},prompt:t.prompt,...l&&{sourceEntityType:l.value.entityType,sourceEntityId:l.value.entityId,sourceEntityIds:[l.value.entityId]}},sourceAttachment:void 0}}}if(t.kind==="standalone-image")return{kind:"ok",value:{createInput:{entityType:"image",...i?{title:i}:{},prompt:t.prompt},sourceAttachment:void 0}};if(t.kind==="cover-image"){let l=await Fi(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}}}let n=await uf(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}}}async function gf(e,t,r){let i=t.operation,n=A(r.userPermissionLevel),o=await mf(e,i,n);if(o.kind==="error")return o;let{createInput:s,sourceAttachment:a}=o.value,l=sr(e,s.entityType,r);if(l.kind==="error")return l;let{interceptor:d}=l.value;if(!s.prompt&&!s.from)return T("Provide a generation source.");if(s.from&&!d)return T(`Entity type '${s.entityType}' does not support attachment-based generation. Use operation.kind prompt-from-source for AI-generated content based on referenced source material, or choose an entity type with an attachment provider.`,"unsupported-generation");let u=i.kind==="prompt"||i.kind==="prompt-from-source",p=d&&!u?void 0:await or(e,{entityType:s.entityType,candidateId:s.prompt?Ni(X(s.title??s.prompt),100):s.title?X(s.title):void 0,replace:s.replace===!0,copyHint:"generate a new copy intentionally"},r);if(p?.kind==="error")return p;return{kind:"ok",value:{createInput:s,operation:ff(i,s,a),interceptor:d,eventContext:je(r),...p?.value&&{replacesFailed:p.value}}}}function ff(e,t,r){if(e.kind==="attachment"){let i=r??{sourceEntityType:e.source.entityType,sourceEntityId:e.source.entityId,attachmentType:e.attachmentType};return{kind:"attachment",source:{entityType:i.sourceEntityType,entityId:i.sourceEntityId},attachmentType:i.attachmentType,...t.title&&{title:t.title},...t.replace&&{replace:t.replace}}}if(e.kind==="cover-image")return{kind:"cover-image",target:{entityType:t.targetEntityType??e.target.entityType,entityId:t.targetEntityId??e.target.entityId},...t.title&&{title:t.title},prompt:e.prompt};if(e.kind==="standalone-image")return{kind:"standalone-image",...t.title&&{title:t.title},prompt:e.prompt};if(e.kind==="prompt-from-source")return{kind:"prompt-from-source",entityType:t.entityType,...t.title&&{title:t.title},source:{entityType:t.sourceEntityType??e.source.entityType,entityId:t.sourceEntityId??e.source.entityId},prompt:e.prompt};return{kind:"prompt",entityType:t.entityType,...t.title&&{title:t.title},prompt:e.prompt}}function ol(e){let t=Y({label:"generate",requestNoun:"generation"});return N("generate","Generate durable content or artifacts. Requires confirmation: calling this tool without confirmed is how you request it, so when the user asks to create, write, draft, or generate new durable content without supplying final exact content, call it instead of drafting the content in chat, asking for separate prose approval, or saying 'I can generate it if you want' or 'I need to queue it first'. Critical: broad or underspecified topical generation uses operation.kind prompt with no source field, also in the same turn after an optional search finds no source; preserve the user's wording as the prompt and do not stop to ask what details to highlight. Critical: to generate from an existing source such as 'my latest blog post', resolve it with read/search/list tools unless the user gives an exact entity id in quotes, then call operation.kind prompt-from-source right away, for example { kind: 'prompt-from-source', entityType: 'newsletter', source: { entityType: 'post', entityId: '...' }, prompt: '...' }. For the latest published/blog source, use system_list on that type (blog posts: entityType post) and choose the newest candidate by publishedAt, not updated/created or semantic search order; do not stop with prose like 'I found it and can generate it' or 'if that is the one you mean.' Never invent source IDs, use brain-character/profile, uploads, filenames, guessed ids, or placeholders as source refs. Turning an existing entity into another type ('turn my note X into a post') keeps its text and is not generation: call system_create with source.kind entity, also after a search resolves it. Use system_create as well for saving/importing existing text, URLs, uploads, prior assistant responses, or raw uploaded files. Critical: for a request to generate a post/social-post/newsletter/etc. with a cover image, call only the prompt generation first; call cover-image only once the target entity exists after confirmation, never guess its future id, and never use standalone-image as a substitute for a requested cover. When a cover-image request names the target's exact id in quotes or a search/get resolves a clear target, call cover-image in the same turn; do not stop after saying you found the entity. Use attachment for source-derived artifacts: attachmentType og-image for OG/social preview renders (the provider updates ogImageId), carousel for deck carousel PDFs, printable for post/project PDFs. Call it immediately for save/render requests, with replace:true for regenerate/replace/refresh, instead of saying you can queue it later. To attach a generated artifact to another entity, generate the artifact first in the same turn \u2014 do not ask whether they mean an existing artifact when the source entity is explicit or given as a quoted id such as deck `distributed-systems-primer` \u2014 and update the target only after the real artifact ID exists.",Ac,async(r,i)=>{let n=await gf(e,r,i);if(n.kind==="error")return n.result;let{createInput:o,operation:s,interceptor:a,eventContext:l,replacesFailed:d}=n.value;return ar({gate:t,input:r,replacesFailed:d,confirmation:()=>({toolName:"system_generate",...df(o),args:{operation:s}}),run:()=>Ye(e,i,{createInput:o,interceptor:a,replacesFailed:d,persist:async(u)=>{if(!u.prompt)return{success:!1,error:"Attachment generation is supported only for entity types that explicitly handle source-derived artifacts."};return pf(e,u,u.prompt,l,i)}})})},{visibility:"trusted",sideEffects:"writes"})}function sl(e){let{entityService:t,entityRegistry:r,logger:i}=e,n=Y({label:"delete",requestNoun:"deletion"});return N("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.",kc,async(o,s)=>{if((s.userPermissionLevel??"public")==="public")return{success:!1,error:"Changing content requires higher permission; current permission is Public."};let a=V(e,o.entityType,"delete",s);if(a)return a;let l=De(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 H(t,o.entityType,o.id,i,void 0,d,{binaryContent:"reference"});if(!u.ok)return{success:!1,error:u.error};let{entity:p}=u;if(o.confirmed){let f=n.validateConfirmed(o.confirmationToken,o);if(f)return f;try{await t.deleteEntity({entityType:o.entityType,id:p.id})}catch(h){return{success:!1,error:P(h,"Failed to delete entity")}}return{success:!0,data:{deleted:p.id}}}let m=nr(p),g=n.buildArgs((f)=>({...o,id:p.id,confirmed:!0,confirmationToken:f}));return{needsConfirmation:!0,toolName:"system_delete",summary:`Delete "${m}"?`,preview:p.content.slice(0,200),args:g}},{visibility:"admin",sideEffects:"writes"})}function al(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 nn}from"util";class mr{diff(e,t,r={}){let i;if(typeof r==="function")i=r,r={};else if("callback"in r)i=r.callback;let n=this.castInput(e,r),o=this.castInput(t,r),s=this.removeEmpty(this.tokenize(n,r)),a=this.removeEmpty(this.tokenize(o,r));return this.diffWithOptionsObj(s,a,r,i)}diffWithOptionsObj(e,t,r,i){var n;let o=(y)=>{if(y=this.postProcess(y,r),i){setTimeout(function(){i(y)},0);return}else return y},s=t.length,a=e.length,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}],g=this.extractCommon(m[0],t,e,0,r);if(m[0].oldPos+1>=a&&g+1>=s)return o(this.buildValues(m[0].lastComponent,t,e));let f=-1/0,h=1/0,v=()=>{for(let y=Math.max(f,-l);y<=Math.min(h,l);y+=2){let S,R=m[y-1],w=m[y+1];if(R)m[y-1]=void 0;let C=!1;if(w){let B=w.oldPos-y;C=w&&0<=B&&B<s}let E=R&&R.oldPos+1<a;if(!C&&!E){m[y]=void 0;continue}if(!E||C&&R.oldPos<w.oldPos)S=this.addToPath(w,!0,!1,0,r);else S=this.addToPath(R,!1,!0,1,r);if(g=this.extractCommon(S,t,e,y,r),S.oldPos+1>=a&&g+1>=s)return o(this.buildValues(S.lastComponent,t,e))||!0;else{if(m[y]=S,S.oldPos+1>=a)h=Math.min(h,y-1);if(g+1>=s)f=Math.max(f,y+1)}}l++};if(i)(function y(){setTimeout(function(){if(l>d||Date.now()>p)return i(void 0);if(!v())y()},0)})();else while(l<=d&&Date.now()<=p){let y=v();if(y)return y}}addToPath(e,t,r,i,n){let o=e.lastComponent;if(o&&!n.oneChangePerToken&&o.added===t&&o.removed===r)return{oldPos:e.oldPos+i,lastComponent:{count:o.count+1,added:t,removed:r,previousComponent:o.previousComponent}};else return{oldPos:e.oldPos+i,lastComponent:{count:1,added:t,removed:r,previousComponent:o}}}extractCommon(e,t,r,i,n){let o=t.length,s=r.length,a=e.oldPos,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 g=r[l+m];return g.length>p.length?g:p}),d.value=this.join(u)}else d.value=this.join(t.slice(a,a+d.count));if(a+=d.count,!d.added)l+=d.count}else d.value=this.join(r.slice(l,l+d.count)),l+=d.count}return i}}class cl extends mr{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}}var ll=new cl;function gr(e,t,r){return ll.diff(e,t,r)}var ve=c.enum(["png","jpg","jpeg","webp","gif","svg"]),ul=c.enum(["pending","draft","failed"]),pl=c.object({title:c.string().optional(),alt:c.string().optional(),format:ve.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:ul.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",ve],["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]})}}),ml=dl.extend({entityType:c.literal("image"),metadata:pl}),hf=c.object({url:c.string(),alt:c.string(),title:c.string(),width:c.number(),height:c.number()});function gl(e){return/^https?:\/\//i.test(e)}async function fl(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 et(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 tt(e){let t=et(e);if(!t)throw Error("Invalid image data URL");return t}function fr(e){let t=e.toLowerCase(),r=t==="svg+xml"?"svg":t,i=ve.safeParse(r);return i.success?i.data:null}async function yf(e){return fl(e,"image/")}function hl(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 be(e){switch(e){case"jpg":case"jpeg":return"image/jpeg";case"svg":return"image/svg+xml";default:return`image/${e}`}}var vf=64;async function Hi(e){let t=await e(0,vf),r=hl(t);if(!r)return;let i=r==="jpg"||r==="jpeg"?await Sf(e):Gi(t);return{format:r,mediaType:be(r),width:i?.width??0,height:i?.height??0}}function Wi(e){return async(t,r)=>e.subarray(t,r)}function qi(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 bf(e){return(t,r)=>Bun.file(e).slice(t,r).bytes()}async function Sf(e){let t=Xe(2),r=async(i)=>i.done?i.value:r(t.next(await e(...i.value)));return r(t.next(new Uint8Array))}function*Xe(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*Xe(e+1);if(r===1||r>=208&&r<=215)return yield*Xe(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*Xe(e+2+i)}function Ji(e){return Gi(Buffer.from(e,"base64"))}function Gi(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=Xe(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 wf(e){let t=fr(e);if(!t)throw Error(`Unsupported image format: ${e}`);return t}function yl(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 If(e){if(e===""||rt.safeParse(e).success)return{};let{format:t,base64:r}=tt(e),i=Ji(r);return{format:wf(t),width:i?.width??0,height:i?.height??0}}function Qi(e){let{title:t,alt:r,...i}=yl(e);return{entityType:"image",content:e.asset.ref,metadata:{title:t,alt:r,...e.description,sizeBytes:e.asset.sizeBytes,...i}}}function Pf(e){return{entityType:"image",content:"",metadata:yl(e)}}function hT(e){return bl(e,{skipInvalid:!0,noRefs:!0,sortKeys:!0})}function Sl(e){return vl(e)}async function wl(e,t){let r=rt.safeParse(t.content);if(!r.success){let i=et(t.content);if(!i)return;let n=fr(i.format);return{bytes:Buffer.from(i.base64,"base64"),mediaType:n?be(n):`image/${i.format}`}}return{bytes:await Rl(e,r.data),mediaType:Cf(t)}}async function Il(e,t){if(!rt.safeParse(t.content).success)return et(t.content)?t.content:void 0;let r=await wl(e,t);return r&&`data:${r.mediaType};base64,${r.bytes.toString("base64")}`}function Cf(e){let t=e.metadata.mediaType;if(typeof t==="string")return t;let r=ve.safeParse(e.metadata.format);return r.success?be(r.data):"image/png"}var xf=/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/,Tf=c.record(c.string(),c.unknown());function Pl(e,t){let r=xf.exec(e.content);if(!r?.[1])return;try{let i=Tf.safeParse(Sl(r[1]));if(i.success){let n=i.data[t];return typeof n==="string"?n:void 0}}catch{return}return}function Ef(e){return Pl(e,"coverImageId")}function Af(e){return Pl(e,"ogImageId")}function Ki(e,t){return{...e,content:it(e.content,"coverImageId",t)}}function Vi(e,t){return{...e,content:it(e.content,"ogImageId",t)}}var Yi=Cl();function kf(e,t){let r=Yi.parse(e),i=new Map;hr(r,"definition",(o)=>{if(!i.has(o.identifier))i.set(o.identifier,o)});let n=new Set;return hr(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?Yi.stringify(r):e}function Df(e){let t=[],r=Yi.parse(e);return hr(r,"image",(i)=>{t.push({url:i.url,alt:i.alt??"",title:i.title??void 0})}),t}var en=26214400,jf=["png","jpg","gif","webp"].map(be);async function zf(e,t,r){let{read:i,bytes:n}=Of(t),o=await Hi(i);if(!o)throw Error("Unsupported image format: not a PNG, JPEG, GIF or WebP");let s=await e.stageAsset(n,{maxBytes:en});return{stagedAsset:s,entity:Qi({...r,asset:s,description:o})}}function Of(e){if("bytes"in e)return{read:Wi(e.bytes),bytes:e.bytes};let{base64:t}=tt(e.dataUrl);return{read:qi(t),bytes:Xi(t)}}var nt=/^---\r?\n(?:[\s\S]*?\r?\n)?---[ \t]*(?:\r?\n|$)/;function tn(e){return e.replace(nt,"")}var xl=400;function yr(e,t,r){if(r===null)return!Object.hasOwn(e,t);return Object.hasOwn(e,t)&&nn(e[t],r)}function ze(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 Lf(e,t,r){if(r.has(t))return vr(e.content).frontmatter[t];return t==="visibility"?e.visibility:e.metadata[t]}function jl(e,t,r){let i=ze(e.entityType,r),n=new Set(Object.keys(r.getAdapter(e.entityType).frontmatterSchema?.shape??{}).filter((s)=>!i.has(s))),o=Object.fromEntries(Object.entries(vr(t).frontmatter).filter(([s])=>!n.has(s)));return Object.keys(o).length>0?{...e,content:dr(o,e.content)}:e}function zl(e,t,r){let{visibility:i,coverImageId:n,ogImageId:o,...s}=t,a=i===void 0?e.visibility:kl.parse(i),l=Object.hasOwn(t,"coverImageId")?Ki(e,typeof n==="string"?n:null):e,d=Object.hasOwn(t,"ogImageId")?Vi(l,typeof o==="string"?o:null):l,u={...e.metadata};for(let[f,h]of Object.entries(s))if(h===null)delete u[f];else u[f]=h;let p={...d,visibility:a,metadata:u};for(let[f,h]of Object.entries(s))if(h===null)delete p[f];else p[f]=h;let m=ze(e.entityType,r),g=!1;for(let[f,h]of Object.entries(t)){if(!m.has(f))continue;p.content=it(p.content,f,h),g=!0}if(g)p.metadata=r.projectMetadata(e.entityType,p.content,u);if(r.getAdapter(e.entityType).metadataFromFrontmatter===!0){let f={...p.metadata};for(let h of["coverImageId","ogImageId"]){if(!Object.hasOwn(t,h))continue;let v=t[h];if(typeof v==="string")f[h]=v;else delete f[h]}p.metadata=f}return p}function Uf(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(nn(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:pr(t)??e.visibility}}var Bf=new Set(["visibility","coverImageId","ogImageId"]),$f=c.record(c.string(),c.unknown());function _f(e,t,r,i){if(t.kind!=="fields")return;let n=t.fields,o=r.getEffectiveFrontmatterSchema(e.entityType);if(!o)return;let s=ze(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),v=i.serializeEntity(h),y=vr(v).frontmatter,S=i.deserializeEntity(v,e.entityType).metadata??{};for(let R of a){let w=n[R];if(!yr(y,R,w)||!yr(S,R,w))return{success:!1,error:`The requested ${R} 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)&&(!Bf.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 g=[],f=[];for(let h of u){let v=n[h];if(Object.hasOwn(m,h)){if(!yr(m,h,v))g.push(h)}else if(v!==null||!Object.hasOwn(e.metadata,h))f.push(h)}if(f.length>0){let h;try{h=p.parseFrontMatter(p.toMarkdown(l),$f)}catch{if(g.length===0)return}if(h){for(let v of f)if(!yr(h,v,n[v]))g.push(v)}}if(g.length===0)return;return{success:!1,error:`${e.entityType} does not persist ${g.join(", ")} through 'fields'. The update would report success without changing anything. Provide full markdown with frontmatter via 'content' instead.`}}function Ol(e,t,r){let i=nt.exec(e.content)?.[0];if(i===void 0||!t.trim()||nt.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 Zf(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&&!nt.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 Ff(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 Nf(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 Ml(e,t,r){let i=ze(e.entityType,r);if(t.kind==="fields")return Object.entries(t.fields).map(([a,l])=>{let d=Lf(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)"}`,g=l===null?"(removed)":JSON.stringify(l);return`${a}: ${m} \u2192 ${g}`}).join(`
84
84
  `);let n=e.content.split(`
85
85
  `),o=t.content.split(`
86
86
  `),s=gr(n,o,{maxEditLength:xl});if(!s)return`Full content replacement (line diff omitted: more than ${xl} changed lines).`;return s.filter((a)=>a.added||a.removed).flatMap((a)=>a.value.map((l)=>`${a.added?"+":"-"} ${l}`)).join(`
87
- `)}function Ll(e,t,r,i){return $f(e,t,r,i)??_f(e.entityType,t,r)??Zf(e.entityType,t,r)}function Ul(e,t,r){return Dl(e.entityType,e.metadata.status,Ff(e,t,r),r)==="non-publish"?"update":"publish"}function Bl(e,t,r){return t.kind==="content"?Lf(e,t.content,r):zl(e,t.fields,r)}var Tl=5,El=160;function Nf(e){return e.length>El?`${e.slice(0,El)}\u2026`:e}function Hf(e){if(e===void 0)return"(removed)";return typeof e==="string"?e:JSON.stringify(e)}function Al(e){return e.trim().length>0}function rn(e,t){if(t.length===0)return;let r=t.length-Tl;return[e,...t.slice(0,Tl).map((i)=>`> ${Nf(i)}`),...r>0?[`\u2026 and ${r} more changed lines`]:[]].join(`
88
- `)}function Wf(e,t){return[...new Set([...Object.keys(e.metadata),...Object.keys(t.metadata)])].filter((r)=>!nn(e.metadata[r],t.metadata[r])).map((r)=>`${r}: ${Hf(t.metadata[r])}`)}function $l(e,t){if(t.content===e.content)return rn("Stored now:",Wf(e,t));let r=gr(e.content.split(`
87
+ `)}function Ll(e,t,r,i){return _f(e,t,r,i)??Zf(e.entityType,t,r)??Ff(e.entityType,t,r)}function Ul(e,t,r){return Dl(e.entityType,e.metadata.status,Nf(e,t,r),r)==="non-publish"?"update":"publish"}function Bl(e,t,r){return t.kind==="content"?Uf(e,t.content,r):zl(e,t.fields,r)}var Tl=5,El=160;function Hf(e){return e.length>El?`${e.slice(0,El)}\u2026`:e}function Wf(e){if(e===void 0)return"(removed)";return typeof e==="string"?e:JSON.stringify(e)}function Al(e){return e.trim().length>0}function rn(e,t){if(t.length===0)return;let r=t.length-Tl;return[e,...t.slice(0,Tl).map((i)=>`> ${Hf(i)}`),...r>0?[`\u2026 and ${r} more changed lines`]:[]].join(`
88
+ `)}function qf(e,t){return[...new Set([...Object.keys(e.metadata),...Object.keys(t.metadata)])].filter((r)=>!nn(e.metadata[r],t.metadata[r])).map((r)=>`${r}: ${Wf(t.metadata[r])}`)}function $l(e,t){if(t.content===e.content)return rn("Stored now:",qf(e,t));let r=gr(e.content.split(`
89
89
  `),t.content.split(`
90
- `)),i=r.filter((n)=>n.added).flatMap((n)=>n.value).filter(Al);if(i.length>0)return rn("Stored now:",i);return rn("No longer stored:",r.filter((n)=>n.removed).flatMap((n)=>n.value).filter(Al))}function Se(e){return{success:!1,error:e}}async function qf(e,t,r,i){if(t.confirmed&&t.contentHash&&r.contentHash!==t.contentHash)return Se("Entity was modified since you reviewed the changes. Please try again.");let n=t.operation;if(n.fields!==void 0)return{operation:{kind:"fields",fields:n.fields}};if(n.edits!==void 0)return{operation:{kind:"content",content:al(r.content,n.edits)}};if(n.content!==void 0)return _l(e,r,n.content);if(n.source===void 0)return Se(Ke);let o=await cr(e,n.source,i,{confirmed:t.confirmed===!0});if(!o.success)return o;return _l(e,r,o.content,lr(n.source,o))}function _l(e,t,r,i){let n=Ol(t,r,e.entityRegistry);if(typeof n!=="string")return n;return{operation:{kind:"content",content:n},...i?{source:i}:{}}}function Zl(e){let{entityService:t,logger:r,entityRegistry:i}=e,n=V({label:"update",requestNoun:"the update"}),o=async(d,u,p,m)=>{let g=n.validateConfirmed(d.confirmationToken,d);if(g)return g;let f=Bl(u,p,i);if(f.visibility!==u.visibility&&!ur(m.userPermissionLevel,f.visibility))return Se(`Cannot set entity visibility to "${f.visibility}" \u2014 caller permission "${m.userPermissionLevel??"public"}" is not allowed to write at that level.`);try{let y=je(m);if((await t.updateEntity({entity:f,options:{expectedContentHash:u.contentHash,...y?{eventContext:y}:{}}})).skipReason==="content-conflict")return Se("Entity was modified before the update could be saved. Please request and confirm the update again.")}catch(y){return Se(P(y,"Failed to update entity"))}let h=await t.getEntity({entityType:u.entityType,id:u.id,visibilityScope:A(m.userPermissionLevel)}),v=h?$l(u,h):void 0;return{success:!0,data:{updated:u.id},...v!==void 0&&{completionDetail:v}}},s=async(d,u,p)=>{if(u.kind!=="fields")return d;if(i.getAdapter(d.entityType).metadataFromFrontmatter!==!0)return d;let m=ze(d.entityType,i);if(!Object.keys(u.fields).some((f)=>m.has(f)))return d;let g=await t.getEntity({entityType:d.entityType,id:d.id,visibilityScope:p,source:!0});return g?jl(d,g.content,i):d},a=(d,u,{operation:p,source:m})=>({needsConfirmation:!0,toolName:"system_update",summary:`Update "${nr(u)}"?`,completionSummary:`Updated ${_c(u.entityType)}.`,preview:Ml(u,p,i),args:n.buildArgs((g)=>({...d,...m?{operation:{source:m}}:{},id:u.id,confirmed:!0,confirmationToken:g,contentHash:u.contentHash}))});return{...N("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.",Xt,async(d,u)=>{await i.ensureGroupingsCurrent(d.entityType);let p=er(i,d.entityType,d.operation.fields,{on:"update",allow:["visibility","coverImageId","ogImageId"]});if(p)return Se(p);let m=await H(t,d.entityType,d.id,r,void 0,A(u.userPermissionLevel),{binaryContent:"reference"});if(!m.ok)return Se(m.error);let g=await qf(e,d,m.entity,u);if("success"in g)return g;let{operation:f}=g,h=await s(m.entity,f,A(u.userPermissionLevel)),v=Ll(h,f,i,t);if(v)return v;let y=K(e,d.entityType,Ul(h,f,i),u);if(y)return y;return d.confirmed?o(d,h,f,u):a(d,h,g)},{visibility:"trusted",sideEffects:"writes"}),modelInput:Bc(e.entityRegistry)}}function Fl(e){return[il(e),ol(e),sl(e),Zl(e)]}function br(e){if(e.interfaceType!==Nl)return;if(e.userPermissionLevel!=="public"||e.isAnchor)throw Error("Guest execution denied")}var Jl=3000,Jf={limit:10,excerptChars:Jl},Gf={limit:5,maxLimit:5,excerptChars:800};function Gl(e){return e!==void 0&&me(e)==="local"?Gf:Jf}var Hl=`
90
+ `)),i=r.filter((n)=>n.added).flatMap((n)=>n.value).filter(Al);if(i.length>0)return rn("Stored now:",i);return rn("No longer stored:",r.filter((n)=>n.removed).flatMap((n)=>n.value).filter(Al))}function Se(e){return{success:!1,error:e}}async function Jf(e,t,r,i){if(t.confirmed&&t.contentHash&&r.contentHash!==t.contentHash)return Se("Entity was modified since you reviewed the changes. Please try again.");let n=t.operation;if(n.fields!==void 0)return{operation:{kind:"fields",fields:n.fields}};if(n.edits!==void 0)return{operation:{kind:"content",content:al(r.content,n.edits)}};if(n.content!==void 0)return _l(e,r,n.content);if(n.source===void 0)return Se(Ke);let o=await cr(e,n.source,i,{confirmed:t.confirmed===!0});if(!o.success)return o;return _l(e,r,o.content,lr(n.source,o))}function _l(e,t,r,i){let n=Ol(t,r,e.entityRegistry);if(typeof n!=="string")return n;return{operation:{kind:"content",content:n},...i?{source:i}:{}}}function Zl(e){let{entityService:t,logger:r,entityRegistry:i}=e,n=Y({label:"update",requestNoun:"the update"}),o=async(d,u,p,m)=>{let g=n.validateConfirmed(d.confirmationToken,d);if(g)return g;let f=Bl(u,p,i);if(f.visibility!==u.visibility&&!ur(m.userPermissionLevel,f.visibility))return Se(`Cannot set entity visibility to "${f.visibility}" \u2014 caller permission "${m.userPermissionLevel??"public"}" is not allowed to write at that level.`);try{let y=je(m);if((await t.updateEntity({entity:f,options:{expectedContentHash:u.contentHash,...y?{eventContext:y}:{}}})).skipReason==="content-conflict")return Se("Entity was modified before the update could be saved. Please request and confirm the update again.")}catch(y){return Se(P(y,"Failed to update entity"))}let h=await t.getEntity({entityType:u.entityType,id:u.id,visibilityScope:A(m.userPermissionLevel)}),v=h?$l(u,h):void 0;return{success:!0,data:{updated:u.id},...v!==void 0&&{completionDetail:v}}},s=async(d,u,p)=>{if(u.kind!=="fields")return d;if(i.getAdapter(d.entityType).metadataFromFrontmatter!==!0)return d;let m=ze(d.entityType,i);if(!Object.keys(u.fields).some((f)=>m.has(f)))return d;let g=await t.getEntity({entityType:d.entityType,id:d.id,visibilityScope:p,source:!0});return g?jl(d,g.content,i):d},a=(d,u,{operation:p,source:m})=>({needsConfirmation:!0,toolName:"system_update",summary:`Update "${nr(u)}"?`,completionSummary:`Updated ${_c(u.entityType)}.`,preview:Ml(u,p,i),args:n.buildArgs((g)=>({...d,...m?{operation:{source:m}}:{},id:u.id,confirmed:!0,confirmationToken:g,contentHash:u.contentHash}))});return{...N("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.",Xt,async(d,u)=>{await i.ensureGroupingsCurrent(d.entityType);let p=er(i,d.entityType,d.operation.fields,{on:"update",allow:["visibility","coverImageId","ogImageId"]});if(p)return Se(p);let m=await H(t,d.entityType,d.id,r,void 0,A(u.userPermissionLevel),{binaryContent:"reference"});if(!m.ok)return Se(m.error);let g=await Jf(e,d,m.entity,u);if("success"in g)return g;let{operation:f}=g,h=await s(m.entity,f,A(u.userPermissionLevel)),v=Ll(h,f,i,t);if(v)return v;let y=V(e,d.entityType,Ul(h,f,i),u);if(y)return y;return d.confirmed?o(d,h,f,u):a(d,h,g)},{visibility:"trusted",sideEffects:"writes"}),modelInput:Bc(e.entityRegistry)}}function Fl(e){return[il(e),ol(e),sl(e),Zl(e)]}function br(e){if(e.interfaceType!==Nl)return;if(e.userPermissionLevel!=="public"||e.isAnchor)throw Error("Guest execution denied")}var Jl=3000,Gf={limit:10,excerptChars:Jl},Qf={limit:5,maxLimit:5,excerptChars:800};function Gl(e){return e!==void 0&&me(e)==="local"?Qf:Gf}var Hl=`
91
91
 
92
92
  \u2026
93
93
 
94
- `,Qf=new Set(["about","and","are","can","does","for","from","how","into","the","this","what","when","where","which","who","why","with","you","your"]);function on(e){return new Set(e.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter((t)=>t.length>=3&&!Qf.has(t)).map((t)=>t.length>3&&t.endsWith("s")?t.slice(0,-1):t))}var Wl=/^#{1,6}\s/,Kf=/^\s*(```|~~~)/;function Vf(e){let t=e.split(`
95
- `),{starts:r}=t.reduce((n,o,s)=>{if(!n.inFence&&s>0&&Wl.test(o))n.starts.push(s);if(Kf.test(o))n.inFence=!n.inFence;return n},{inFence:!1,starts:[]}),i=[0,...r,t.length];return i.slice(0,-1).map((n,o)=>t.slice(n,i[o+1]).join(`
94
+ `,Kf=new Set(["about","and","are","can","does","for","from","how","into","the","this","what","when","where","which","who","why","with","you","your"]);function on(e){return new Set(e.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter((t)=>t.length>=3&&!Kf.has(t)).map((t)=>t.length>3&&t.endsWith("s")?t.slice(0,-1):t))}var Wl=/^#{1,6}\s/,Vf=/^\s*(```|~~~)/;function Yf(e){let t=e.split(`
95
+ `),{starts:r}=t.reduce((n,o,s)=>{if(!n.inFence&&s>0&&Wl.test(o))n.starts.push(s);if(Vf.test(o))n.inFence=!n.inFence;return n},{inFence:!1,starts:[]}),i=[0,...r,t.length];return i.slice(0,-1).map((n,o)=>t.slice(n,i[o+1]).join(`
96
96
  `).trim()).filter((n)=>n.length>0).map((n,o)=>({index:o,heading:Wl.test(n)?n.split(`
97
- `)[0]??"":"",text:n}))}function Yf(e,t){let r=on(t.heading),i=on(t.text);return Array.from(e).reduce((n,o)=>n+(i.has(o)?1:0)+(r.has(o)?1:0),0)}function ql(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 Ql(e,t,r=Jl){if(e.length<=r)return e;let i=on(t),n=Vf(e).map((a)=>({section:a,score:Yf(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 ql(e.trim(),r);if(o.text.length>r)return ql(o.text,r);let{kept:s}=n.reduce((a,l)=>{let d=l.text.length+(a.kept.length>0?Hl.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?`
97
+ `)[0]??"":"",text:n}))}function Xf(e,t){let r=on(t.heading),i=on(t.text);return Array.from(e).reduce((n,o)=>n+(i.has(o)?1:0)+(r.has(o)?1:0),0)}function ql(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 Ql(e,t,r=Jl){if(e.length<=r)return e;let i=on(t),n=Yf(e).map((a)=>({section:a,score:Xf(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 ql(e.trim(),r);if(o.text.length>r)return ql(o.text,r);let{kept:s}=n.reduce((a,l)=>{let d=l.text.length+(a.kept.length>0?Hl.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?`
98
98
 
99
- `:Hl}${a.text}`}).join("")}var Xf=0.5;function Kl(e,t){let r=e??t.limit;return t.maxLimit===void 0?r:Math.min(r,t.maxLimit)}function Vl(e,t,r,i){let n=Mi(e.entity,r);if(n!==e.entity)return{...e,entity:n,excerpt:n.content};let o=tn(n.content);if(o.length<=i)return{...e,entity:n};let{content:s,...a}=n;return{...e,entity:a,excerpt:Ql(o,t,i),excerpted:!0}}var Sr=(e)=>e==="public"?{publishedOnly:!0}:{};function eh(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 Yl(e){let{entityService:t,logger:r}=e;return[ce("system","search","Search entities using semantic search. For broad search, make one system_search call with scope.kind all. Use scope.kind type only when the user asks for a specific entity type. When the user names entity types, search each with scope.kind type in the same step, without a broad search first. Applies a default minScore of 0.5 to reduce weak matches; lower minScore only for exploratory or loose recall. An empty result with belowThreshold means weaker matches exist: search again with a lower minScore before concluding that nothing relevant exists. When the question is in a different language from the saved content, also search with the query translated into the content's language before concluding that little exists; the content's language is the language of the search results and of the brain's profile, and matches across languages score lower. Search results include each matched entity's content; a long one's is excerpted to its best-matching sections, which system_get reads whole. When relevant results already contain the complete evidence needed, answer from those results instead of redundantly listing or getting the same entities. Search results are candidates; do not present weak or unrelated candidates as exact matches. For each new user question about what they have written, mentioned, discussed, or saved, run a fresh search for that turn instead of answering from prior-turn results or memory, including analysis phrasing such as 'How do I discuss X in my writing?'.",Ic,async(i,n)=>{br(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:Kl(i.limit,e.searchBudget),filter:{visibilityScope:o},...Sr(o)}})).map((m)=>Vl({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??Xf,a=await t.search({query:i.query,options:{limit:Kl(i.limit,e.searchBudget),...i.scope.kind==="type"&&{types:[i.scope.entityType]},...i.includeUngenerated!==void 0&&{includeUngenerated:i.includeUngenerated},visibilityScope:o,...Sr(o)}}),l=a.filter((u)=>u.score>=s),d=l.length===0?eh(a,s):void 0;return{success:!0,data:{results:l.map((u)=>Vl(u,i.query,e.entityRegistry,e.searchBudget.excerptChars)),...d&&{belowThreshold:d}}}},{visibility:"public",sideEffects:"none",cli:{name:"search"}}),ce("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.",Pc,async(i,n)=>{if(br(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 H(t,i.entityType,i.id,r,void 0,o,{...Sr(o),source:!0,binaryContent:"reference"});if(!s.ok)return{success:!1,error:s.error};let a=Mi(s.entity,e.entityRegistry);return{success:!0,data:{entity:i.part==="body"?{...a,content:tn(a.content)}:a}}},{visibility:"public",sideEffects:"none",cli:{name:"get"}}),ce("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.",Cc,async(i,n)=>{if(br(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,binaryContent:"reference",...Sr(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 th(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 rh(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(th),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 Xl(e){let{entityService:t,analytics:r}=e,i=r.getDefinitions(),n=i.map((o)=>`${o.type} (${o.description})`).join("; ");return[ce("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}.`,rh(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 ed(e){let{jobs:t}=e;return[N("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.",Dc,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 ih(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 td(e){return[ce("system","status","Get system status including version, background work, and the web surfaces (such as the dashboard and Studio) the caller can open, with their paths; trusted callers also get the model and entity totals",c.object({}),async(t,r)=>({success:!0,data:ih(await e.getAppInfo(),(i)=>e.permissionService.hasPermission(r.userPermissionLevel??"public",i))}),{visibility:"public",sideEffects:"none",cli:{name:"status"}})]}function rd(e){return[...Yl(e),...ed(e),...td(e),...Fl(e),...Xl(e)]}function id(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(`
99
+ `:Hl}${a.text}`}).join("")}var eh=0.5;function Kl(e,t){let r=e??t.limit;return t.maxLimit===void 0?r:Math.min(r,t.maxLimit)}function Vl(e,t,r,i){let n=Mi(e.entity,r);if(n!==e.entity)return{...e,entity:n,excerpt:n.content};let o=tn(n.content);if(o.length<=i)return{...e,entity:n};let{content:s,...a}=n;return{...e,entity:a,excerpt:Ql(o,t,i),excerpted:!0}}var Sr=(e)=>e==="public"?{publishedOnly:!0}:{};function th(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 Yl(e){let{entityService:t,logger:r}=e;return[ce("system","search","Search entities using semantic search. For broad search, make one system_search call with scope.kind all. Use scope.kind type only when the user asks for a specific entity type. When the user names entity types, search each with scope.kind type in the same step, without a broad search first. Applies a default minScore of 0.5 to reduce weak matches; lower minScore only for exploratory or loose recall. An empty result with belowThreshold means weaker matches exist: search again with a lower minScore before concluding that nothing relevant exists. When the question is in a different language from the saved content, also search with the query translated into the content's language before concluding that little exists; the content's language is the language of the search results and of the brain's profile, and matches across languages score lower. Search results include each matched entity's content; a long one's is excerpted to its best-matching sections, which system_get reads whole. When relevant results already contain the complete evidence needed, answer from those results instead of redundantly listing or getting the same entities. Search results are candidates; do not present weak or unrelated candidates as exact matches. For each new user question about what they have written, mentioned, discussed, or saved, run a fresh search for that turn instead of answering from prior-turn results or memory, including analysis phrasing such as 'How do I discuss X in my writing?'.",Ic,async(i,n)=>{br(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:Kl(i.limit,e.searchBudget),filter:{visibilityScope:o},...Sr(o)}})).map((m)=>Vl({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??eh,a=await t.search({query:i.query,options:{limit:Kl(i.limit,e.searchBudget),...i.scope.kind==="type"&&{types:[i.scope.entityType]},...i.includeUngenerated!==void 0&&{includeUngenerated:i.includeUngenerated},visibilityScope:o,...Sr(o)}}),l=a.filter((u)=>u.score>=s),d=l.length===0?th(a,s):void 0;return{success:!0,data:{results:l.map((u)=>Vl(u,i.query,e.entityRegistry,e.searchBudget.excerptChars)),...d&&{belowThreshold:d}}}},{visibility:"public",sideEffects:"none",cli:{name:"search"}}),ce("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.",Pc,async(i,n)=>{if(br(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 H(t,i.entityType,i.id,r,void 0,o,{...Sr(o),source:!0,binaryContent:"reference"});if(!s.ok)return{success:!1,error:s.error};let a=Mi(s.entity,e.entityRegistry);return{success:!0,data:{entity:i.part==="body"?{...a,content:tn(a.content)}:a}}},{visibility:"public",sideEffects:"none",cli:{name:"get"}}),ce("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.",Cc,async(i,n)=>{if(br(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,binaryContent:"reference",...Sr(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 rh(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 ih(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(rh),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 Xl(e){let{entityService:t,analytics:r}=e,i=r.getDefinitions(),n=i.map((o)=>`${o.type} (${o.description})`).join("; ");return[ce("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}.`,ih(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 ed(e){let{jobs:t}=e;return[N("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.",Dc,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 nh(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 td(e){return[ce("system","status","Get system status including version, background work, and the web surfaces (such as the dashboard and Studio) the caller can open, with their paths; trusted callers also get the model and entity totals",c.object({}),async(t,r)=>({success:!0,data:nh(await e.getAppInfo(),(i)=>e.permissionService.hasPermission(r.userPermissionLevel??"public",i))}),{visibility:"public",sideEffects:"none",cli:{name:"status"}})]}function rd(e){return[...Yl(e),...ed(e),...td(e),...Fl(e),...Xl(e)]}function id(e){return[{uri:"entity://types",name:"Entity Types",description:"List of registered entity types",mimeType:"text/plain",handler:async()=>({contents:[{uri:"entity://types",mimeType:"text/plain",text:e.entityService.getEntityTypes().join(`
100
100
  `)}]})},{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 nd(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,options:{binaryContent:"reference"}})).map((s)=>({id:s.id,entityType:s.entityType,...s.metadata,updated:s.updated}));return{contents:[{uri:`entity://${r}`,mimeType:"application/json",text:JSON.stringify(o,null,2)}]}}},{name:"entity-detail",uriTemplate:"entity://{type}/{id}",description:"Read a single entity by type and ID",mimeType:"text/markdown",complete:{type:async(r)=>{let i=t.getEntityTypes();return r?i.filter((n)=>n.startsWith(r)):i},id:async()=>[]},handler:async({type:r,id:i})=>{let n=await t.getEntity({entityType:r,id:i});if(!n)throw Error(`Entity not found: ${r}/${i}`);return{contents:[{uri:`entity://${r}/${i}`,mimeType:"text/markdown",text:n.content}]}}}]}function od(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 sd(e){return["## Entity CRUD","","Use the system tools for ALL entity operations; each tool's description is its contract.","","Treat explicit verbs such as save, create, capture, remember, import, add/connect an agent, approve/archive an agent, update, delete, generate, publish, or sync as mutation requests. Entity-specific instructions may require proactively recording the user's request itself for demand or workflow tracking; follow those instructions even when the user did not use a separate save/create verb. Ordinary status questions like 'what is the status', 'is it ready', 'did that finish', or 'what happened' are not capture requests; answer them by using the relevant status/read tool for the prior operation. Never call system_create for a status follow-up.","","Do not ask for prose confirmation instead of calling the applicable mutating tool; for create, update, delete, generate, publish, sync, and similar state-changing requests, the initial tool call without `confirmed` is how you create the pending confirmation. Never pass `confirmed: true` on the initial user request. Deletion is Admin-only: if system_delete is not available in the current tool surface, say deletion requires Admin access; do not imply a confirmation flow is available. Never claim a durable create/update/delete change was saved, created, done, or completed unless the relevant tool call succeeded or returned a pending confirmation. If a create/update/delete tool is unavailable, unauthorized, or intentionally not called, say you can't make that durable change from the current context; never say saved/created/done. For an explicit write request from an unauthorized/currently unwritable context, refuse directly; do not call system_status or system_search to check permission or look up related content. Entity type descriptions may mark projection-owned or system-maintained types read-only; refuse mutation requests for those types directly without calling read or write tools, searching for a target, or asking which record to mutate.","","Entity types \u2014 select `entityType` by what the type is for:",...e.entityService.getEntityTypes().map((i)=>`- ${i}: ${e.entityRegistry.getAdapter(i).purpose}`)].join(`
101
- `)}var Oe="system",nh=c.object({toolName:c.string(),args:c.unknown(),...ad.partial().shape});function Rr(e,t,r,i,n){for(let o of e)try{t(o)}catch{n.debug(`System ${i} ${r(o)} already registered, skipping`)}}function cd(e,t,r,i){let n=rd(e);Rr(n,(u)=>t.registerTool(Oe,u),(u)=>u.name,"tool",i);let o=r.subscribe(Gt.toolExecute(Oe),async(u)=>{let p=nh.safeParse(u.payload);if(!p.success)return{success:!1,error:"Invalid system tool execute payload"};let{toolName:m,args:g,interfaceType:f,actor:h,conversationId:v,channelId:y,userPermissionLevel:S}=p.data,R=n.find((E)=>E.name===m);if(!R)return{success:!1,error:`System tool not found: ${m}`};let w={interfaceType:f??"system",actor:h??{kind:"service",serviceId:"system"}};if(v)w.conversationId=v;if(y)w.channelId=y;if(S)w.userPermissionLevel=S;return{success:!0,data:await R.handler(g,w)}});i.debug(`Registered ${n.length} system tools`);let s=id(e);Rr(s,(u)=>t.registerResource(Oe,u),(u)=>u.uri,"resource",i),i.debug(`Registered ${s.length} system resources`);let a=nd(e);Rr(a,(u)=>t.registerResourceTemplate(Oe,u),(u)=>u.uriTemplate,"resource template",i),i.debug(`Registered ${a.length} system resource templates`);let l=od(e);Rr(l,(u)=>t.registerPrompt(Oe,u),(u)=>u.name,"prompt",i),i.debug(`Registered ${l.length} system prompts`);let d=sd(e);try{t.registerInstructions(Oe,d)}catch{i.debug("System instructions already registered, skipping")}return i.debug("Registered system instructions"),o}function md(e){let{services:t,jobs:r,analytics:i,query:n,getAppInfo:o}=e,s=t.jobQueueService,a=t.logger.child("system"),l=cd({entityService:t.entityService,entityRegistry:t.entityRegistry,jobs:{...r,enqueue:ld(s,"system",!1),enqueueBatch:ud(r,"system"),registerHandler:pd(s,"system"),has:dd(s)},conversationService:t.conversationService,runtimeUploads:t.runtimeUploadRegistry,attachments:wr(t.attachmentRegistry),logger:a,query:n,getIdentity:()=>t.identityService.getCharacter(),getProfile:()=>t.profileService.getProfile(),getAppInfo:o,searchBudget:Gl(t.aiService.getConfig().model),analytics:i,permissionService:t.permissionService},t.mcpService,t.messageBus,a);t.disposables.push(l)}class sn{scope;closePromise=null;closed=!1;constructor(){this.scope=b.runSync(j.make())}buildLayer(e){this.assertOpen();let t=b.runSyncExit(J.buildWithScope(e,this.scope));if(D.isFailure(t))throw ne.squash(t.cause);return t.value}addFinalizer(e){this.assertOpen(),b.runSync(j.addFinalizer(this.scope,b.promise(async()=>{await e()})))}addSyncFinalizer(e){this.assertOpen(),b.runSync(j.addFinalizer(this.scope,b.sync(()=>{e()})))}async fork(e){if(this.closed)throw Error("Cannot start background work after shell shutdown");await b.runPromise(b.forkIn(e,this.scope))}close(e=D.void){if(this.closePromise)return this.closePromise;if(this.closed)return Promise.resolve();return this.closed=!0,this.closePromise=b.runPromise(j.close(this.scope,e)),this.closePromise}closeSync(e){if(this.closed)return;this.closed=!0,b.runSync(j.close(this.scope,e))}assertOpen(){if(this.closed)throw Error("Cannot register cleanup after shell shutdown")}}class an{config;services;lifecycle;bootloader;initialized=!1;lifecycleState="constructed";bootMode;bootPromise=null;shutdownPromise=null;analyticsRegistry;bootTime=Date.now();endpointRegistry=new Ti;interactionRegistry=new Ei;httpRouteRegistry=Vt.createFresh();httpServed;jobs;static createFresh(e,t,r){return new an(ut(e),t,r)}constructor(e,t,r){this.config=e,this.httpServed=e.http.enabled&&Ce(r?.processRole).serves,this.lifecycle=new sn,Rd(this,()=>this.httpRouteRegistry.getSnapshot());let i=t?.logger??Pe.getInstance(),n=zt.createFresh(i,this.config,r?.processRole,r?.peerChannel);try{if(this.services=n.initializeServices(this.lifecycle,t),this.jobs=hc(this.services.batchJobManager,this.services.jobQueueService),this.analyticsRegistry=uc(this.services.entityRegistry),this.bootloader=new Ci(this.config,this.services,this.lifecycle,n,r?.processRole,{registerCoreDataSources:()=>An(this.services,this.config),finalizeHttpRoutes:()=>{this.httpRouteRegistry.finalize(vc(this.services.pluginManager))},registerSystemCapabilities:()=>md({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();Rc(this.lifecycle,this.services)}catch(o){try{this.lifecycle.closeSync(D.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)=>pt(this.services.entityService,e,t),appInfo:()=>this.getAppInfo(),identityInput:()=>{let e=this.getIdentity(),t=this.getProfile();return fd.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:yd(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 Te(this.services.messageBus,vd,{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(D.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"),kn(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 gd.parse(await this.generateContent({prompt:e,templateName:$e.KNOWLEDGE_QUERY,...n&&{conversationHistory:n},data:o,interfacePermissionGrant:"public"}))}registerPlugin(e){this.requireInitialized("Plugin registration"),this.services.pluginManager.registerPlugin(e)}isInitialized(){return this.initialized}requireInitialized(e){if(!this.initialized)throw Error(`${e} attempted before initialization`)}getEntityService(){return this.services.entityService}getConversationService(){return this.services.conversationService}getEntityRegistry(){return this.services.entityRegistry}async generateObject(e,t,r){this.requireInitialized("Shell generateObject");let{object:i}=await this.services.aiService.generateObject("You are a helpful assistant. Respond with the requested structured data.",e,t,r);return{object:i}}async judge(e){return this.requireInitialized("Shell judge"),this.services.aiService.judge(e)}getAIService(){return this.services.aiService}generateImage(e,t){return this.services.aiService.generateImage(e,t)}canGenerateImages(){return this.services.aiService.canGenerateImages()}getPluginManager(){return this.services.pluginManager}getContentService(){return this.services.contentService}getCallerAuthorizer(){return this.services.callerAuthorizer}getRenderService(){return this.services.renderService}getAttachmentRegistry(){return wr(this.services.attachmentRegistry)}getRuntimeUploadRegistry(){return bd(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(G,Xa({config:this.config.http,domain:this.config.siteBaseUrl,logger:t.child(F),messageBus:r,getRoutes:()=>this.httpRouteRegistry.getSnapshot(),getPlugins:()=>[...i.getAllPlugins().values()].map(({plugin:s})=>s),getOperationalInfo:async()=>Sd(hd(await this.getAppInfo())),getReadinessData:()=>this.getRuntimeReadiness()}),F),this.lifecycle.addSyncFinalizer(()=>e.abandon(G));let{endpoints:n,interactions:o}=ec(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 vn({config:this.config,services:this.services,bootTime:this.bootTime,endpoints:()=>this.listEndpoints(),interactions:()=>this.listInteractions()})}getRuntimeReadiness(){return Rn(this.services)}}async function jd(e,t){await le({label:"entity",config:e,schema:{assets:Id,entities:wd,entityMutationReceipts:Pd,projectionDirtyInputs:Cd,projectionWaves:xd,projectionIncidents:Td,projectionWaveInputs:Ed,projectionWaveRules:Ad,projectionRuleMemos:kd},migrationsFolder:de(import.meta.url,"entity-service"),authTokenEnv:"DATABASE_AUTH_TOKEN",logger:t,afterMigrate:Dd})}async function Md(e,t){await le({label:"job-queue",config:e,schema:{jobQueue:zd,jobWorkerSessions:Od},migrationsFolder:de(import.meta.url,"job-queue"),authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",logger:t})}async function $d(e,t){await le({label:"conversation",config:e,schema:{conversations:Ld,messages:Ud,summaryTracking:Bd},migrationsFolder:de(import.meta.url,"conversation-service"),authTokenEnv:"CONVERSATION_DATABASE_AUTH_TOKEN",logger:t})}async function _d(e,t){await le({label:"runtime-state",config:e,schema:{runtimeStateRecords:I},migrationsFolder:de(import.meta.url,"runtime-state"),authTokenEnv:"RUNTIME_STATE_DATABASE_AUTH_TOKEN",logger:t})}import{mkdir as ln}from"fs/promises";import{isAbsolute as oh}from"path";function Zd(e=process.env){return{dataDir:e.XDG_DATA_HOME??"./data",cacheDir:e.XDG_CACHE_HOME??"./cache",distDir:"./dist"}}function Fd(e=process.env){let t=e.BRAIN_GIT_BROKER_CHECKOUT;if(!t)return;if(!oh(t))throw Error(`Git broker checkout path must be absolute: ${t}`);return t}function Nd(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 Hd(e=process.env){return pe(Zd(e))}async function Wd(e=process.env){let t=Zd(e);try{await ln(t.dataDir,{recursive:!0}),await ln(t.cacheDir,{recursive:!0}),await ln(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 pe(t)}class sh{logger;migrations;constructor(e,t){this.logger=e,this.migrations=t??{getStandardConfigWithDirectories:()=>Wd(),migrateEntities:jd,migrateJobQueue:Md,migrateConversations:$d,migrateRuntimeState:_d}}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 dn={kind:"service",serviceId:"brain-cli"},un=`${dn.kind}:${dn.serviceId}`;function Lk(e="admin"){return{interfaceType:"cli",actor:dn,userPermissionLevel:e}}var $k=c.enum(["eval"]),_k=c.enum(["person","team","organization"]),pn=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 Jd=c.object({name:c.string().default("brain-app"),version:c.string().default("1.0.0"),database:c.string().optional(),aiProviderKeys:Be.optional(),aiModel:c.string().optional(),aiEmbeddingModel:c.string().optional(),aiModelRuntimeUrl:c.string().optional(),aiAnswerModel:c.string().optional(),aiVisionModel:c.string().optional(),aiImageModel:c.string().optional(),aiReasoningEffort:ee.optional(),logLevel:Ie.optional(),logFile:c.string().optional(),profileKind:c.string().trim().min(1).optional(),plugins:c.array(dt).default([]),spaces:c.array(c.string()).default([]),identity:qd.optional(),agentInstructions:c.array(c.string()).optional(),deployment:pn.prefault({}),http:Ue.prefault({})});var ah="NODE_ENV";function ch(){return process.env[ah]}function mn(){return ch()==="production"}function Gd(){return!mn()}var lh="startup-check";function dh(){return Object.fromEntries(cn.map((e)=>[e,lh]))}function iD(e){let r={...Jd.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 nD(e,t){let r={plugins:e.plugins??[],...e.shellConfig};return uh(r),ph(e,r),mh(e,r,t),gh(e,r),fh(e,r),hh(e,r),yh(e,r),vh(e,r),Sh(e,r),bh(e,r),r}function uh(e){let t=Hd();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??=Nd(),e.gitBrokerCheckout??=Fd()}function ph(e,t){if(e.database)t.database={url:e.database};if(e.profileKind)t.profileKind=e.profileKind;t.features={}}function mh(e,t,r){let i=r?.mode==="startup-check";if(!e.aiProviderKeys&&!e.aiModel&&!e.aiEmbeddingModel&&!e.aiModelRuntimeUrl&&!e.aiAnswerModel&&!e.aiVisionModel&&!e.aiImageModel&&!e.aiReasoningEffort&&!i)return;t.ai={...t.ai,providerKeys:{...i&&dh(),...t.ai?.providerKeys,...e.aiProviderKeys},...e.aiModel&&{model:e.aiModel},...e.aiEmbeddingModel&&{embeddingModel:e.aiEmbeddingModel},...e.aiModelRuntimeUrl&&{modelRuntimeUrl:e.aiModelRuntimeUrl},...e.aiAnswerModel&&{answerModel:e.aiAnswerModel},...e.aiVisionModel&&{visionModel:e.aiVisionModel},...e.aiImageModel&&{imageModel:e.aiImageModel},...e.aiReasoningEffort&&{reasoningEffort:e.aiReasoningEffort}}}function gh(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 fh(e,t){let r=e.permissions?.rules??[];t.permissions={...e.permissions,rules:r.some((i)=>i.pattern===un)?r:[{pattern:un,level:"admin"},...r]}}function hh(e,t){if(e.spaces)t.spaces=e.spaces}function yh(e,t){if(e.identity)t.identity=e.identity}function vh(e,t){if(e.agentInstructions)t.agentInstructions=e.agentInstructions}function bh(e,t){t.http??={...W(e.http),port:e.deployment.ports.production}}function Sh(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=Gd(),t.production=mn()}
102
- export{pe as R,Ue as S,Ie as T,ut as U,z as V,Nu as W,Hu as X,Wu as Y,Vu as Z,Vn as _,Xu as $,ep as aa,tp as ba,rp as ca,ip as da,np as ea,op as fa,Kr as ga,ra as ha,ia,na as ja,vi as ka,ki as la,eC as ma,pl as na,gl as oa,et as pa,hf as qa,Hi as ra,qi as sa,vf as ta,wf as ua,If as va,fT as wa,wl as xa,Il as ya,Tf as za,Ef as Aa,Af as Ba,kf as Ca,en as Da,Df as Ea,jf as Fa,an as Ga,jd as Ha,Md as Ia,$d as Ja,_d as Ka,sh as La,Lk as Ma,_k as Na,iD as Oa,nD as Pa};
101
+ `)}var Oe="system",oh=c.object({toolName:c.string(),args:c.unknown(),...ad.partial().shape});function Rr(e,t,r,i,n){for(let o of e)try{t(o)}catch{n.debug(`System ${i} ${r(o)} already registered, skipping`)}}function cd(e,t,r,i){let n=rd(e);Rr(n,(u)=>t.registerTool(Oe,u),(u)=>u.name,"tool",i);let o=r.subscribe(Gt.toolExecute(Oe),async(u)=>{let p=oh.safeParse(u.payload);if(!p.success)return{success:!1,error:"Invalid system tool execute payload"};let{toolName:m,args:g,interfaceType:f,actor:h,conversationId:v,channelId:y,userPermissionLevel:S}=p.data,R=n.find((E)=>E.name===m);if(!R)return{success:!1,error:`System tool not found: ${m}`};let w={interfaceType:f??"system",actor:h??{kind:"service",serviceId:"system"}};if(v)w.conversationId=v;if(y)w.channelId=y;if(S)w.userPermissionLevel=S;return{success:!0,data:await R.handler(g,w)}});i.debug(`Registered ${n.length} system tools`);let s=id(e);Rr(s,(u)=>t.registerResource(Oe,u),(u)=>u.uri,"resource",i),i.debug(`Registered ${s.length} system resources`);let a=nd(e);Rr(a,(u)=>t.registerResourceTemplate(Oe,u),(u)=>u.uriTemplate,"resource template",i),i.debug(`Registered ${a.length} system resource templates`);let l=od(e);Rr(l,(u)=>t.registerPrompt(Oe,u),(u)=>u.name,"prompt",i),i.debug(`Registered ${l.length} system prompts`);let d=sd(e);try{t.registerInstructions(Oe,d)}catch{i.debug("System instructions already registered, skipping")}return i.debug("Registered system instructions"),o}function md(e){let{services:t,jobs:r,analytics:i,query:n,getAppInfo:o}=e,s=t.jobQueueService,a=t.logger.child("system"),l=cd({entityService:t.entityService,entityRegistry:t.entityRegistry,jobs:{...r,enqueue:ld(s,"system",!1),enqueueBatch:ud(r,"system"),registerHandler:pd(s,"system"),has:dd(s)},conversationService:t.conversationService,runtimeUploads:t.runtimeUploadRegistry,attachments:wr(t.attachmentRegistry),logger:a,query:n,getIdentity:()=>t.identityService.getCharacter(),getProfile:()=>t.profileService.getProfile(),getAppInfo:o,searchBudget:Gl(t.aiService.getConfig().model),analytics:i,permissionService:t.permissionService},t.mcpService,t.messageBus,a);t.disposables.push(l)}class sn{scope;closePromise=null;closed=!1;constructor(){this.scope=b.runSync(j.make())}buildLayer(e){this.assertOpen();let t=b.runSyncExit(G.buildWithScope(e,this.scope));if(D.isFailure(t))throw ne.squash(t.cause);return t.value}addFinalizer(e){this.assertOpen(),b.runSync(j.addFinalizer(this.scope,b.promise(async()=>{await e()})))}addSyncFinalizer(e){this.assertOpen(),b.runSync(j.addFinalizer(this.scope,b.sync(()=>{e()})))}async fork(e){if(this.closed)throw Error("Cannot start background work after shell shutdown");await b.runPromise(b.forkIn(e,this.scope))}close(e=D.void){if(this.closePromise)return this.closePromise;if(this.closed)return Promise.resolve();return this.closed=!0,this.closePromise=b.runPromise(j.close(this.scope,e)),this.closePromise}closeSync(e){if(this.closed)return;this.closed=!0,b.runSync(j.close(this.scope,e))}assertOpen(){if(this.closed)throw Error("Cannot register cleanup after shell shutdown")}}class an{config;services;lifecycle;bootloader;initialized=!1;lifecycleState="constructed";bootMode;bootPromise=null;shutdownPromise=null;analyticsRegistry;bootTime=Date.now();endpointRegistry=new Ti;interactionRegistry=new Ei;httpRouteRegistry=Vt.createFresh();httpServed;jobs;static createFresh(e,t,r){return new an(ut(e),t,r)}constructor(e,t,r){this.config=e,this.httpServed=e.http.enabled&&Ce(r?.processRole).serves,this.lifecycle=new sn,Rd(this,()=>this.httpRouteRegistry.getSnapshot());let i=t?.logger??Pe.getInstance(),n=zt.createFresh(i,this.config,r?.processRole,r?.peerChannel);try{if(this.services=n.initializeServices(this.lifecycle,t),this.jobs=hc(this.services.batchJobManager,this.services.jobQueueService),this.analyticsRegistry=uc(this.services.entityRegistry),this.bootloader=new Ci(this.config,this.services,this.lifecycle,n,r?.processRole,{registerCoreDataSources:()=>An(this.services,this.config),finalizeHttpRoutes:()=>{this.httpRouteRegistry.finalize(vc(this.services.pluginManager))},registerSystemCapabilities:()=>md({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();Rc(this.lifecycle,this.services)}catch(o){try{this.lifecycle.closeSync(D.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)=>pt(this.services.entityService,e,t),appInfo:()=>this.getAppInfo(),identityInput:()=>{let e=this.getIdentity(),t=this.getProfile();return fd.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:yd(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 Te(this.services.messageBus,vd,{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(D.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"),kn(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 gd.parse(await this.generateContent({prompt:e,templateName:$e.KNOWLEDGE_QUERY,...n&&{conversationHistory:n},data:o,interfacePermissionGrant:"public"}))}registerPlugin(e){this.requireInitialized("Plugin registration"),this.services.pluginManager.registerPlugin(e)}isInitialized(){return this.initialized}requireInitialized(e){if(!this.initialized)throw Error(`${e} attempted before initialization`)}getEntityService(){return this.services.entityService}getConversationService(){return this.services.conversationService}getEntityRegistry(){return this.services.entityRegistry}async generateObject(e,t,r){this.requireInitialized("Shell generateObject");let{object:i}=await this.services.aiService.generateObject("You are a helpful assistant. Respond with the requested structured data.",e,t,r);return{object:i}}async judge(e){return this.requireInitialized("Shell judge"),this.services.aiService.judge(e)}getAIService(){return this.services.aiService}generateImage(e,t){return this.services.aiService.generateImage(e,t)}canGenerateImages(){return this.services.aiService.canGenerateImages()}getPluginManager(){return this.services.pluginManager}getContentService(){return this.services.contentService}getCallerAuthorizer(){return this.services.callerAuthorizer}getRenderService(){return this.services.renderService}getAttachmentRegistry(){return wr(this.services.attachmentRegistry)}getRuntimeUploadRegistry(){return bd(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(Q,Xa({config:this.config.http,domain:this.config.siteBaseUrl,logger:t.child(F),messageBus:r,getRoutes:()=>this.httpRouteRegistry.getSnapshot(),getPlugins:()=>[...i.getAllPlugins().values()].map(({plugin:s})=>s),getOperationalInfo:async()=>Sd(hd(await this.getAppInfo())),getReadinessData:()=>this.getRuntimeReadiness()}),F),this.lifecycle.addSyncFinalizer(()=>e.abandon(Q));let{endpoints:n,interactions:o}=ec(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 vn({config:this.config,services:this.services,bootTime:this.bootTime,endpoints:()=>this.listEndpoints(),interactions:()=>this.listInteractions()})}getRuntimeReadiness(){return Rn(this.services)}}async function jd(e,t){await le({label:"entity",config:e,schema:{assets:Id,entities:wd,entityMutationReceipts:Pd,projectionDirtyInputs:Cd,projectionWaves:xd,projectionIncidents:Td,projectionWaveInputs:Ed,projectionWaveRules:Ad,projectionRuleMemos:kd},migrationsFolder:de(import.meta.url,"entity-service"),authTokenEnv:"DATABASE_AUTH_TOKEN",logger:t,afterMigrate:Dd})}async function Md(e,t){await le({label:"job-queue",config:e,schema:{jobQueue:zd,jobWorkerSessions:Od},migrationsFolder:de(import.meta.url,"job-queue"),authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",logger:t})}async function $d(e,t){await le({label:"conversation",config:e,schema:{conversations:Ld,messages:Ud,summaryTracking:Bd},migrationsFolder:de(import.meta.url,"conversation-service"),authTokenEnv:"CONVERSATION_DATABASE_AUTH_TOKEN",logger:t})}async function _d(e,t){await le({label:"runtime-state",config:e,schema:{runtimeStateRecords:I},migrationsFolder:de(import.meta.url,"runtime-state"),authTokenEnv:"RUNTIME_STATE_DATABASE_AUTH_TOKEN",logger:t})}import{mkdir as ln}from"fs/promises";import{isAbsolute as sh}from"path";function Zd(e=process.env){return{dataDir:e.XDG_DATA_HOME??"./data",cacheDir:e.XDG_CACHE_HOME??"./cache",distDir:"./dist"}}function Fd(e=process.env){let t=e.BRAIN_GIT_BROKER_CHECKOUT;if(!t)return;if(!sh(t))throw Error(`Git broker checkout path must be absolute: ${t}`);return t}function Nd(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 Hd(e=process.env){return pe(Zd(e))}async function Wd(e=process.env){let t=Zd(e);try{await ln(t.dataDir,{recursive:!0}),await ln(t.cacheDir,{recursive:!0}),await ln(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 pe(t)}class ah{logger;migrations;constructor(e,t){this.logger=e,this.migrations=t??{getStandardConfigWithDirectories:()=>Wd(),migrateEntities:jd,migrateJobQueue:Md,migrateConversations:$d,migrateRuntimeState:_d}}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 dn={kind:"service",serviceId:"brain-cli"},un=`${dn.kind}:${dn.serviceId}`;function Uk(e="admin"){return{interfaceType:"cli",actor:dn,userPermissionLevel:e}}var _k=c.enum(["eval"]),Zk=c.enum(["person","team","organization"]),pn=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 Jd=c.object({name:c.string().default("brain-app"),version:c.string().default("1.0.0"),database:c.string().optional(),aiProviderKeys:Be.optional(),aiModel:c.string().optional(),aiEmbeddingModel:c.string().optional(),aiModelRuntimeUrl:c.string().optional(),aiAnswerModel:c.string().optional(),aiVisionModel:c.string().optional(),aiImageModel:c.string().optional(),aiReasoningEffort:te.optional(),logLevel:Ie.optional(),logFile:c.string().optional(),profileKind:c.string().trim().min(1).optional(),plugins:c.array(dt).default([]),spaces:c.array(c.string()).default([]),identity:qd.optional(),agentInstructions:c.array(c.string()).optional(),deployment:pn.prefault({}),http:Ue.prefault({})});var ch="NODE_ENV";function lh(){return process.env[ch]}function mn(){return lh()==="production"}function Gd(){return!mn()}var dh="startup-check";function uh(){return Object.fromEntries(cn.map((e)=>[e,dh]))}function nD(e){let r={...Jd.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 oD(e,t){let r={plugins:e.plugins??[],...e.shellConfig};return ph(r),mh(e,r),gh(e,r,t),fh(e,r),hh(e,r),yh(e,r),vh(e,r),bh(e,r),Rh(e,r),Sh(e,r),r}function ph(e){let t=Hd();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??=Nd(),e.gitBrokerCheckout??=Fd()}function mh(e,t){if(e.database)t.database={url:e.database};if(e.profileKind)t.profileKind=e.profileKind;t.features={}}function gh(e,t,r){let i=r?.mode==="startup-check";if(!e.aiProviderKeys&&!e.aiModel&&!e.aiEmbeddingModel&&!e.aiModelRuntimeUrl&&!e.aiAnswerModel&&!e.aiVisionModel&&!e.aiImageModel&&!e.aiReasoningEffort&&!i)return;t.ai={...t.ai,providerKeys:{...i&&uh(),...t.ai?.providerKeys,...e.aiProviderKeys},...e.aiModel&&{model:e.aiModel},...e.aiEmbeddingModel&&{embeddingModel:e.aiEmbeddingModel},...e.aiModelRuntimeUrl&&{modelRuntimeUrl:e.aiModelRuntimeUrl},...e.aiAnswerModel&&{answerModel:e.aiAnswerModel},...e.aiVisionModel&&{visionModel:e.aiVisionModel},...e.aiImageModel&&{imageModel:e.aiImageModel},...e.aiReasoningEffort&&{reasoningEffort:e.aiReasoningEffort}}}function fh(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 hh(e,t){let r=e.permissions?.rules??[];t.permissions={...e.permissions,rules:r.some((i)=>i.pattern===un)?r:[{pattern:un,level:"admin"},...r]}}function yh(e,t){if(e.spaces)t.spaces=e.spaces}function vh(e,t){if(e.identity)t.identity=e.identity}function bh(e,t){if(e.agentInstructions)t.agentInstructions=e.agentInstructions}function Sh(e,t){t.http??={...W(e.http),port:e.deployment.ports.production}}function Rh(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=Gd(),t.production=mn()}
102
+ export{pe as R,Ue as S,Ie as T,ut as U,z as V,Nu as W,Hu as X,Wu as Y,Vu as Z,Vn as _,Xu as $,ep as aa,tp as ba,rp as ca,ip as da,np as ea,op as fa,Kr as ga,ra as ha,ia,na as ja,vi as ka,ki as la,tC as ma,pl as na,gl as oa,et as pa,yf as qa,Hi as ra,qi as sa,bf as ta,If as ua,Pf as va,hT as wa,wl as xa,Il as ya,Ef as za,Af as Aa,kf as Ba,Df as Ca,en as Da,jf as Ea,zf as Fa,an as Ga,jd as Ha,Md as Ia,$d as Ja,_d as Ka,ah as La,Uk as Ma,Zk as Na,nD as Oa,oD as Pa};
103
103
 
104
- //# debugId=850218E4AD83331064756E2164756E21
105
- //# sourceMappingURL=index-04a9zd0g.js.map
104
+ //# debugId=F556B527579E772764756E2164756E21
105
+ //# sourceMappingURL=index-xjjn2y6e.js.map