@rizom/brain 0.2.0-alpha.745 → 0.2.0-alpha.746
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/brain.js +630 -630
- package/dist/chunks/{app-8ntw61p5.js → app-qg4tz2ss.js} +2 -2
- package/dist/chunks/{index-hrf7173w.js → index-q6xayd96.js} +2 -2
- package/dist/chunks/{index-h8gmxmtk.js → index-rkq6mgh1.js} +18 -18
- package/dist/chunks/{index-h8gmxmtk.js.map → index-rkq6mgh1.js.map} +3 -3
- package/dist/chunks/{index-eek4pwer.js → index-ypr42ee1.js} +3 -3
- package/dist/chunks/{index-eek4pwer.js.map → index-ypr42ee1.js.map} +1 -1
- package/dist/chunks/{package-3z5wzh16.js → package-q6mhrka6.js} +3 -3
- package/dist/chunks/{package-3z5wzh16.js.map → package-q6mhrka6.js.map} +1 -1
- package/dist/model.js +4 -4
- package/dist/model.js.map +1 -1
- package/dist/testing.js +1 -1
- package/package.json +1 -1
- /package/dist/chunks/{app-8ntw61p5.js.map → app-qg4tz2ss.js.map} +0 -0
- /package/dist/chunks/{index-hrf7173w.js.map → index-q6xayd96.js.map} +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Pa as js,Qa as Ds}from"./index-nmttkcq0.js";import{$a as ye,$d as Gs,$j as Bs,Ad as rl,Af as Hd,Ag as ic,Bb as ho,Bf as Wd,Bg as xd,Bi as Ao,Cb as Io,Cd as zl,Ce as to,Cg as Uo,Ci as $o,Dd as ls,De as ms,Di as _o,Eb as de,Ee as xn,Ei as Zo,Fb as ue,Fc as wd,Fd as ee,Fe as gs,Fg as wr,Fi as Fo,Gb as kd,Gc as Js,Gd as Fi,Gf as rr,Gg as Ss,Hb as jd,Hc as uo,He as qs,Hf as Hc,Hg as Ce,Ib as Dd,Ie as Vr,If as io,Jb as zd,Jf as Xd,Jg as Cd,Kb as Od,Kc as sd,Kg as Rs,Lb as Md,Lc as oo,Le as _d,Lg as gc,Mb as Ld,Me as Zd,Mg as Na,Nb as Ud,Ne as Go,Ng as wi,Ni as No,Nj as Ls,Ob as Bd,Oe as Qo,Oj as Ho,Pb as ao,Pe as Ko,Qb as co,Rb as lo,Re as Vo,Rj as Us,Se as hd,Sj as Wo,Tb as Dt,Te as yd,Tj as As,Ub as as,Uc as cs,Ue as vd,Ui as uc,Uj as qo,Va as Il,Vb as yt,Vd as Nc,Ve as bd,Vi as pc,Wa as ot,Wb as We,We as Id,Wf as Cn,Wi as dt,Xb as Te,Xe as Wl,Xf as pt,Yb as ud,Yf as ec,Yi as Td,Za as Yi,Zb as Sc,Zf as Pd,Zi as Es,_a as lt,_b as Dl,_d as _,ab as bo,ac as A,ai as Ze,ak as Ed,bb as O,bc as ur,bg as _i,bi as sn,cc as Yr,cg as Kc,ck as ks,db as se,dc as ul,dg as Vc,di as Rn,dk as sc,ec as Oo,eg as fs,ei as ge,ek as Kt,fb as So,fc as Mo,fg as hs,fi as wn,gc as Lo,gg as ys,gi as In,hi as jr,ic as Lr,ii as Is,jc as Ur,ji as Pn,nb as Ro,pc as pr,rd as hr,sb as Wr,tb as wt,tg as vs,ti as Ps,ub as mo,ui as xs,vb as go,vd as Tl,vg as bs,vi as jc,wg as qe,wi as Cs,xb as fo,xd as Os,xe as Ja,xg as tc,xi as Bo,yb as Ad,ye as ft,yg as rc,yi as Ts,zd as Ms,zf as Nd}from"./index-fvzp2k73.js";import{$n as us,Dm as Ws,Em as Gt,En as Za,Gn as Fa,Ll as Do,Ml as zo,Nm as Ya,Nn as re,On as V,Pl as Xn,Qm as qt,Vn as ds,am as we,ao as ps,bo as gd,cm as x,dm as He,gn as dd,hn as Rd,ho as ws,il as G,jo as $a,km as eo,ln as ts,mk as Sl,ml as Ha,mo as le,nk as Rl,nl as Z,ok as ie,qk as Me,qo as Y,rk as Oe,sk as vr,tk as dr,uk as st,wm as fe,ym as Tt}from"./index-cc0vpbw4.js";import{ro as Ge,to as Pe}from"./index-asvqgam1.js";import{$s as D,As as ss,Ms as j,_v as b,ht as Q,ow as ne,qw as Qt,rw as Xa,uq as C,uw as nc,ys as oe}from"./index-trypv2bs.js";import{Mx as c}from"./index-8phgkre1.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 $e(e,t){let r=e.workerSessions,i=r.active===0?"missing":r.stale>0?"stale":"active",n=e.duePending>0&&(e.oldestDuePendingAgeMs??0)>=120000&&e.totals.processing===0&&(e.latestClaimAgeMs===null||e.latestClaimAgeMs>=120000),o=[];if(i==="missing")o.push("No live worker session");else if(i==="stale")o.push(`${r.stale} stale worker session(s)`);if(n)o.push(`${e.duePending} due job(s) have remained unclaimed for at least 120000ms`);if(t){let s=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 hn(e){let{config:t,services:r,bootTime:i,endpoints:n,interactions:o}=e,[s,a,l,d]=await Promise.all([r.entityService.getEntityCounts(lt("runtime app info reports operator-facing aggregate status")),r.entityService.countEmbeddings(),r.daemonRegistry.getStatuses(),r.jobQueueService.getDiagnostics()]),u=s.reduce((p,m)=>p+m.count,0);return{model:t.name||"brain-app",version:t.version||"1.0.0",uptime:Math.floor((Date.now()-i)/1000),entities:u,entityCounts:s,embeddings:a,backgroundWork:$e(d,r.jobQueueService.getExecutionRegistrations()),ai:{model:t.ai.model,embeddingModel:r.embeddingService.identity.model},daemons:l,endpoints:n(),interactions:o()}}import{readdir as yn,readFile as bu}from"fs/promises";var Su=10;async function Ru(e="/proc"){let t=null;try{t=(await yn(`${e}/self/fd`)).length}catch{}try{let i=(await yn(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 bu(`${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 vn(e,t,r){return t.status==="fulfilled"?{name:e,status:"healthy",message:r}:{name:e,status:"unhealthy",message:x(t.reason)}}function wu(e){if(!e)return{name:"job-worker",status:"degraded",message:"Worker session state is unavailable"};let t=e.workerSessions,r=$e(e).worker;if(r.state==="missing")return{name:"job-worker",status:"degraded",message:"No live worker session",details:{sessions:t}};if(r.state==="stale")return{name:"job-worker",status:"degraded",message:`${t.stale} stale worker session(s)`,details:{sessions:t}};return{name:"job-worker",status:"healthy",message:`${t.active} live worker session(s)`,details:{sessions:t}}}function Iu(e){if(!e)return{name:"job-queue-progress",status:"degraded",message:"Queue progress state is unavailable"};let t=$e(e).queue;return t.stalled?{name:"job-queue-progress",status:"degraded",message:`${t.duePending} due job(s) are not being claimed`,details:{queue:t}}:{name:"job-queue-progress",status:"healthy",message:"Due jobs are being claimed",details:{queue:t}}}function Pu(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 xu(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 Cu(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 Tu(e){let t=e.entityService.getProjectionStore(),[r,i,n]=await Promise.all([t.getActiveWave(),t.getUnresolvedProjectionIncidentDiagnostics(Su),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 Eu(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 Au(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 bn(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(lt("runtime readiness database probe")),e.jobQueueService.getDiagnostics(t),Promise.resolve(e.jobQueueService.getExecutionRegistrations()),e.daemonRegistry.getStatuses(),(e.readProcessSignals??Ru)(),e.projectionRuntimeSupervisor.getDiagnostics(),Tu(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=[vn("entity-database",i,"Entity database is accessible"),vn("job-queue-database",n,"Job queue database is accessible"),wu(p),Iu(p),Pu(p,m),xu(p),l.status==="fulfilled"?Cu(h):{name:"projection-circuits",status:"degraded",message:x(l.reason)},d.status==="fulfilled"?Eu(d.value):{name:"projection-waves",status:"degraded",message:x(d.reason)},s.status==="fulfilled"?Au(g):{name:"daemons",status:"degraded",message:x(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 Sn(){return{dataDir:"./data",cacheDir:"./cache",distDir:"./dist"}}function me(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 _e=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")}),kr=_e.extend({enabled:c.boolean().default(!1),preview:c.boolean().default(!0),port:c.number().default(8080).describe("Port of the production listener")});var Dr=Sn(),ku=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 zr(){return me(Dr)}var Ie=c.enum(["debug","info","warn","error"]);var Or=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:Ze.default({}),model:c.string().refine(Rn,{error:(e)=>`Unsupported model "${String(e.input)}"`}),embeddingModel:c.string().refine((e)=>jr(e)!==void 0,{error:(e)=>Pn(String(e.input))}).default(In),modelRuntimeUrl:c.string().url().optional(),answerModel:c.string().optional(),visionModel:c.string().optional(),imageModel:c.string().optional(),temperature:c.number().min(0).max(2).default(0.7),webSearch:c.boolean().default(!0),reasoningEffort:re.optional()}).superRefine((e,t)=>{if(e.answerModel&&ge(e.answerModel)!=="local")t.addIssue({code:"custom",path:["answerModel"],message:`answerModel must be a local: model, not ${e.answerModel}`});if(e.visionModel&&ge(e.visionModel)!=="local")t.addIssue({code:"custom",path:["visionModel"],message:`visionModel must be a local: model, not ${e.visionModel}`});if(e.modelRuntimeUrl)return;let r=[...ge(e.model)==="local"?[e.model]:[],...[e.answerModel,e.visionModel].filter((i)=>i!==void 0&&ge(i)==="local"),...e.imageModel&&wn(e.imageModel).provider==="local"?[e.imageModel]:[],...jr(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(),ku).optional(),profileKind:c.string().trim().min(1).optional(),http:kr.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}=Or.parse({...zr(),...Z(p),ai:Z({...a}),logging:Z({...l}),embedding:Z({...d}),jobQueue:Z({...u}),plugins:[]});return{...g,plugins:t,permissions:r,...Z({entityDisplay:m,identity:i,profile:n,agentInstructions:o,evalHandlerRegistry:s})}}var M={NOTE:"note",BRAIN_CHARACTER:"brain-character",ANCHOR_PROFILE:"anchor-profile"},Fe={KNOWLEDGE_QUERY:"shell:knowledge-query",BASE_ENTITY_DISPLAY:"shell:base-entity-display",CONTENT_GENERATION:"shell:content-generation"},Mr={ENTITIES:"shell:entities"};var ju=xn.extend({templateName:c.string()}),Du=c.object({slug:c.string()}),zu="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.",Ou="Generate the content described in your instructions.";function Mu(e){return e instanceof c.ZodType}function Lu(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=Lu(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=ju.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 Cn((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(!Mu(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",zu,"");return i.push("# Instructions",e),i.join(`
|
|
2
|
+
import{Pa as js,Qa as Ds}from"./index-nmttkcq0.js";import{$a as ye,$d as Gs,$j as Bs,Ad as rl,Af as Hd,Ag as ic,Bb as ho,Bf as Wd,Bg as xd,Bi as Ao,Cb as Io,Cd as Ol,Ce as to,Cg as Uo,Ci as $o,Dd as ls,De as ms,Di as _o,Eb as de,Ee as xn,Ei as Zo,Fb as ue,Fc as wd,Fd as ee,Fe as gs,Fg as wr,Fi as Fo,Gb as kd,Gc as Js,Gd as Fi,Gf as ir,Gg as Ss,Hb as jd,Hc as uo,He as qs,Hf as Hc,Hg as Ce,Ib as Dd,Ie as Vr,If as io,Jb as Od,Jf as Xd,Jg as Cd,Kb as zd,Kc as sd,Kg as Rs,Lb as Md,Lc as oo,Le as _d,Lg as gc,Mb as Ld,Me as Zd,Mg as Na,Nb as Ud,Ne as Go,Ng as wi,Ni as No,Nj as Ls,Ob as Bd,Oe as Qo,Oj as Ho,Pb as ao,Pe as Ko,Qb as co,Rb as lo,Re as Vo,Rj as Us,Se as hd,Sj as Wo,Tb as Ot,Te as yd,Tj as As,Ub as as,Uc as cs,Ue as vd,Ui as uc,Uj as qo,Va as Il,Vb as vt,Vd as Nc,Ve as bd,Vi as pc,Wa as st,Wb as qe,We as Id,Wf as Cn,Wi as ut,Xb as Te,Xe as Wl,Xf as mt,Yb as ud,Yf as ec,Yi as Td,Za as Yi,Zb as Sc,Zf as Pd,Zi as Es,_a as dt,_b as Dl,_d as _,ab as bo,ac as A,ai as Fe,ak as Ed,bb as z,bc as pr,bg as _i,bi as sn,cc as Yr,cg as Kc,ck as ks,db as se,dc as ul,dg as Vc,di as Rn,dk as sc,ec as zo,eg as fs,ei as ge,ek as Vt,fb as So,fc as Mo,fg as hs,fi as wn,gc as Lo,gg as ys,gi as In,hi as jr,ic as Lr,ii as Is,jc as Ur,ji as Pn,nb as Ro,pc as mr,rd as yr,sb as Wr,tb as It,tg as vs,ti as Ps,ub as mo,ui as xs,vb as go,vd as Tl,vg as bs,vi as jc,wg as Je,wi as Cs,xb as fo,xd as zs,xe as Ja,xg as tc,xi as Bo,yb as Ad,ye as ht,yg as rc,yi as Ts,zd as Ms,zf as Nd}from"./index-fvzp2k73.js";import{$n as us,Dm as Ws,Em as Qt,En as Za,Gn as Fa,Ll as Do,Ml as Oo,Nm as Ya,Nn as re,On as V,Pl as Xn,Qm as Jt,Vn as ds,am as we,ao as ps,bo as gd,cm as x,dm as We,gn as dd,hn as Rd,ho as ws,il as G,jo as $a,km as eo,ln as ts,mk as Sl,ml as Ha,mo as le,nk as Rl,nl as Z,ok as ie,qk as Le,qo as Y,rk as ze,sk as Me,tk as ur,uk as at,wm as fe,ym as Et}from"./index-cc0vpbw4.js";import{ro as Qe,to as Pe}from"./index-asvqgam1.js";import{$s as D,As as ss,Ms as j,_v as b,ht as Q,ow as ne,qw as Kt,rw as Xa,uq as C,uw as nc,ys as oe}from"./index-trypv2bs.js";import{Mx as c}from"./index-8phgkre1.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 _e(e,t){let r=e.workerSessions,i=r.active===0?"missing":r.stale>0?"stale":"active",n=e.duePending>0&&(e.oldestDuePendingAgeMs??0)>=120000&&e.totals.processing===0&&(e.latestClaimAgeMs===null||e.latestClaimAgeMs>=120000),o=[];if(i==="missing")o.push("No live worker session");else if(i==="stale")o.push(`${r.stale} stale worker session(s)`);if(n)o.push(`${e.duePending} due job(s) have remained unclaimed for at least 120000ms`);if(t){let s=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 hn(e){let{config:t,services:r,bootTime:i,endpoints:n,interactions:o}=e,[s,a,l,d]=await Promise.all([r.entityService.getEntityCounts(dt("runtime app info reports operator-facing aggregate status")),r.entityService.countEmbeddings(),r.daemonRegistry.getStatuses(),r.jobQueueService.getDiagnostics()]),u=s.reduce((p,m)=>p+m.count,0);return{model:t.name||"brain-app",version:t.version||"1.0.0",uptime:Math.floor((Date.now()-i)/1000),entities:u,entityCounts:s,embeddings:a,backgroundWork:_e(d,r.jobQueueService.getExecutionRegistrations()),ai:{model:t.ai.model,embeddingModel:r.embeddingService.identity.model},daemons:l,endpoints:n(),interactions:o()}}import{readdir as yn,readFile as bu}from"fs/promises";var Su=10;async function Ru(e="/proc"){let t=null;try{t=(await yn(`${e}/self/fd`)).length}catch{}try{let i=(await yn(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 bu(`${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 vn(e,t,r){return t.status==="fulfilled"?{name:e,status:"healthy",message:r}:{name:e,status:"unhealthy",message:x(t.reason)}}function wu(e){if(!e)return{name:"job-worker",status:"degraded",message:"Worker session state is unavailable"};let t=e.workerSessions,r=_e(e).worker;if(r.state==="missing")return{name:"job-worker",status:"degraded",message:"No live worker session",details:{sessions:t}};if(r.state==="stale")return{name:"job-worker",status:"degraded",message:`${t.stale} stale worker session(s)`,details:{sessions:t}};return{name:"job-worker",status:"healthy",message:`${t.active} live worker session(s)`,details:{sessions:t}}}function Iu(e){if(!e)return{name:"job-queue-progress",status:"degraded",message:"Queue progress state is unavailable"};let t=_e(e).queue;return t.stalled?{name:"job-queue-progress",status:"degraded",message:`${t.duePending} due job(s) are not being claimed`,details:{queue:t}}:{name:"job-queue-progress",status:"healthy",message:"Due jobs are being claimed",details:{queue:t}}}function Pu(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 xu(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 Cu(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 Tu(e){let t=e.entityService.getProjectionStore(),[r,i,n]=await Promise.all([t.getActiveWave(),t.getUnresolvedProjectionIncidentDiagnostics(Su),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 Eu(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 Au(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 bn(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(dt("runtime readiness database probe")),e.jobQueueService.getDiagnostics(t),Promise.resolve(e.jobQueueService.getExecutionRegistrations()),e.daemonRegistry.getStatuses(),(e.readProcessSignals??Ru)(),e.projectionRuntimeSupervisor.getDiagnostics(),Tu(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=[vn("entity-database",i,"Entity database is accessible"),vn("job-queue-database",n,"Job queue database is accessible"),wu(p),Iu(p),Pu(p,m),xu(p),l.status==="fulfilled"?Cu(h):{name:"projection-circuits",status:"degraded",message:x(l.reason)},d.status==="fulfilled"?Eu(d.value):{name:"projection-waves",status:"degraded",message:x(d.reason)},s.status==="fulfilled"?Au(g):{name:"daemons",status:"degraded",message:x(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 Sn(){return{dataDir:"./data",cacheDir:"./cache",distDir:"./dist"}}function me(e){return{database:{url:`file:${e.dataDir}/brain.db`},jobQueueDatabase:{url:`file:${e.dataDir}/brain-jobs.db`},conversationDatabase:{url:`file:${e.dataDir}/conversations.db`},runtimeStateDatabase:{url:`file:${e.dataDir}/runtime-state.db`},embeddingDatabase:{url:`file:${e.dataDir}/embeddings.db`},embedding:{enabled:!0}}}var Ze=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")}),kr=Ze.extend({enabled:c.boolean().default(!1),preview:c.boolean().default(!0),port:c.number().default(8080).describe("Port of the production listener")});var Dr=Sn(),ku=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 Or(){return me(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:Fe.default({}),model:c.string().refine(Rn,{error:(e)=>`Unsupported model "${String(e.input)}"`}),embeddingModel:c.string().refine((e)=>jr(e)!==void 0,{error:(e)=>Pn(String(e.input))}).default(In),modelRuntimeUrl:c.string().url().optional(),answerModel:c.string().optional(),visionModel:c.string().optional(),imageModel:c.string().optional(),temperature:c.number().min(0).max(2).default(0.7),webSearch:c.boolean().default(!0),reasoningEffort:re.optional()}).superRefine((e,t)=>{if(e.answerModel&&ge(e.answerModel)!=="local")t.addIssue({code:"custom",path:["answerModel"],message:`answerModel must be a local: model, not ${e.answerModel}`});if(e.visionModel&&ge(e.visionModel)!=="local")t.addIssue({code:"custom",path:["visionModel"],message:`visionModel must be a local: model, not ${e.visionModel}`});if(e.modelRuntimeUrl)return;let r=[...ge(e.model)==="local"?[e.model]:[],...[e.answerModel,e.visionModel].filter((i)=>i!==void 0&&ge(i)==="local"),...e.imageModel&&wn(e.imageModel).provider==="local"?[e.imageModel]:[],...jr(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(ut).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(),ku).optional(),profileKind:c.string().trim().min(1).optional(),http:kr.prefault({})});function pt(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({...Or(),...Z(p),ai:Z({...a}),logging:Z({...l}),embedding:Z({...d}),jobQueue:Z({...u}),plugins:[]});return{...g,plugins:t,permissions:r,...Z({entityDisplay:m,identity:i,profile:n,agentInstructions:o,evalHandlerRegistry:s})}}var M={NOTE:"note",BRAIN_CHARACTER:"brain-character",ANCHOR_PROFILE:"anchor-profile"},Ne={KNOWLEDGE_QUERY:"shell:knowledge-query",BASE_ENTITY_DISPLAY:"shell:base-entity-display",CONTENT_GENERATION:"shell:content-generation"},Mr={ENTITIES:"shell:entities"};var ju=xn.extend({templateName:c.string()}),Du=c.object({slug:c.string()}),Ou="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.",zu="Generate the content described in your instructions.";function Mu(e){return e instanceof c.ZodType}function Lu(e){if(!e)return;return e.replace(/^https?:\/\//,"").replace(/\/$/,"")}class gt{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=Lu(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=ju.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 Cn((v,y)=>i.getEntity(v,y),n.templateName,o.basePrompt):await mt(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(!Mu(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",Ou,"");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
|
-
`):Ou}formatRelevantEntity(e,t){let{entity:r,excerpt:i}=e,n=r.entityType,o=Du.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 Uu=c.object({entityType:c.string(),query:c.object({id:c.string()})});class gt{entityService;id=Mr.ENTITIES;name="Entity DataSource";description="Fetches entity content from the entity service";constructor(e){this.entityService=e}async fetch(e,t,r){let i=Uu.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 Tn(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 En(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 An={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 kn={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 jn={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 Dn={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 zn={lexicon:1,id:"ai.rizom.brain.post",defs:{main:{type:"record",description:"Markdown blog post distributed by a Rizom brain.",key:"any",record:{type:"object",required:["title","body","createdAt"],properties:{title:{type:"string",maxLength:300},summary:{type:"string",maxLength:2000},body:{type:"string",maxLength:1e5},format:{type:"string",knownValues:["text/markdown"]},brainDid:{type:"string"},anchorDid:{type:"string"},canonicalUrl:{type:"string",format:"uri"},topics:{type:"array",items:{type:"string"},maxLength:50},coverImage:{type:"ref",ref:"#coverImage"},series:{type:"string",maxLength:200},seriesIndex:{type:"integer"},sourceEntityType:{type:"string",knownValues:["post"]},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},updatedAt:{type:"string",format:"datetime"},publishedAt:{type:"string",format:"datetime"}}}},coverImage:{type:"object",description:"Cover image attached to the post.",required:["blob"],properties:{blob:{type:"blob"},alt:{type:"string",maxLength:1000},width:{type:"integer"},height:{type:"integer"}}}}};var On={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 Mn={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 Ln={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 Un={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 Bn=c.object({type:c.string()}).catchall(c.unknown()),Ju=c.object({type:c.literal("object"),description:c.string().optional(),required:c.array(c.string()).optional(),properties:c.record(c.string(),Bn)}),Gu=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(),Bn)})})}).catchall(Ju)});function F(e){return Gu.parse(e)}var z={"ai.rizom.brain.card":F(An),"ai.rizom.brain.deck":F(kn),"ai.rizom.brain.link":F(jn),"ai.rizom.brain.note":F(Dn),"ai.rizom.brain.post":F(zn),"ai.rizom.brain.project":F(On),"ai.rizom.brain.series":F(Mn),"ai.rizom.brain.socialPost":F(Ln),"ai.rizom.brain.topic":F(Un)},Qu="Additive optional fields are compatible; required-field, type, or constraint changes require a migration plan or new NSID.";function J(e){return{status:"approved",version:"1.0.0",revision:1,owner:"Rizom",steward:"Rizom protocol registry",projectionPackage:e,compatibility:Qu}}var $n={"ai.rizom.brain.card":J("@brains/atproto"),"ai.rizom.brain.deck":J("@brains/decks"),"ai.rizom.brain.link":J("@brains/link"),"ai.rizom.brain.note":J("@brains/note"),"ai.rizom.brain.post":J("@brains/blog"),"ai.rizom.brain.project":J("@brains/portfolio"),"ai.rizom.brain.series":J("@brains/series"),"ai.rizom.brain.socialPost":J("@brains/social-media"),"ai.rizom.brain.topic":J("@brains/topics")};function Ku(){return Object.values(z)}function Vu(e){if(!Ur(z,e))return;return z[e]}function Yu(){return Lr($n).map(([e,t])=>({id:e,...t}))}var Xu=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;function ep(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)=>Xu.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 tp(e,t){if(typeof e!=="string"||!e.startsWith("#"))return;let r=t[e.slice(1)];return r?.type==="object"?r:void 0}function Zn(e,t){switch(e.type){case"string":return ep(e);case"integer":return c.number().int();case"boolean":return c.boolean();case"array":{let r=e.items?Zn(e.items,t):c.unknown(),i=c.array(r);if(e.maxLength!==void 0)i=i.max(e.maxLength);return i}case"object":return _n(e,t);case"ref":{let r=tp(e.ref,t);if(!r)return c.custom(()=>!1,{message:`unresolvable lexicon ref ${String(e.ref)}`});return c.lazy(()=>_n(r,t))}case"blob":return c.custom(ie,{message:"expected blob"});default:return c.unknown()}}function Fn(e,t){let r=new Set(e.required??[]),i={};for(let[n,o]of Object.entries(e.properties??{})){let s=Zn(o,t);i[n]=r.has(n)?s:s.optional()}return i}function _n(e,t){return c.strictObject(Fn(e,t))}function U(e){return c.strictObject({...Fn(e.defs.main.record,e.defs),$type:c.literal(e.id).optional()})}var Br={"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 rp(e,t){let r=e;for(let i of t){if(typeof i==="symbol")return;if(Array.isArray(r)){r=r[Number(i)];continue}if(!ie(r))return;r=r[String(i)]}return r}function ip(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"&&rp(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 np(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(ip(e,t,i))}var Nn="atproto:brain-card-discovered",Hn="atproto:brain-discovered",Wn="atproto:brain-card-refreshed",qn="atproto:brain-card-unavailable",Jn="atproto:brain-card-conflict",Gn="atproto:jetstream-gap",op=c.custom((e)=>Br["ai.rizom.brain.card"].safeParse(e).success),Qn=c.object({repoDid:c.string().min(1),uri:c.string().min(1),cid:c.string().min(1),record:op}).strict(),$r=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(),Kn=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(),Vn=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(),Yn=c.object({previousCursorTimeUs:c.number().int().nonnegative(),clampedCursorTimeUs:c.number().int().nonnegative(),observedAt:c.string().datetime()}).strict(),sp=fe(Nn,Qn),ap=fe(Hn,$r),cp=fe(Wn,$r),lp=fe(qn,Kn),dp=fe(Jn,Vn),up=fe(Gn,Yn);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 pp({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,Xn,{actor:r},t);if(i.status==="unavailable")return null;if(i.status==="failed")throw eo(i.error,`Principal resolution failed: ${i.error.message}`);return i.data.principal}function ro(e,t){return new to(e,(r)=>vt(t,"shell:content-service",r))}var _r=C.Service("@brains/conversation-service/ConversationService");function mp(e){if(e.service){let r=e.service;return{service:r,close:()=>r.close()}}let t=io.createFreshFromConfig(e.logger,e.messageBus,e.dbConfig);try{return{service:t,close:()=>t.close()}}catch(r){throw t.close(),r}}function no(e){return ne(_r,()=>mp(e))}var Zr=C.Service("@brains/entity-service/EntityService");function gp(e){return"close"in e&&typeof e.close==="function"}function so(e){return ne(Zr,()=>{let t=e.service??oo.createFresh(e);return{service:t,close:()=>{if(gp(t))t.close()}}})}var Ne=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()}),Fr=c.strictObject({alerts:c.array(Ne).optional()});var bt="shell:recurring-check",Hr=86400000,fp=7*Hr,hp=3*Hr,yp=c.strictObject({checkId:c.string().min(1)}),vp=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:Ne,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 uo;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:vp});let t={validateAndParse:(r)=>{let i=yp.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){Rp(e),po(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=Fr.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(j.isSuccess(s))return!0;if(t.aborted)throw t.reason;throw oe.squash(s.cause)}getRegisteredCheckIds(){return[...this.checks.keys()]}trackCatchUp(e){let t=this.enqueueCatchUpIfNeeded(e);e.catchUpTasks.add(t);let r=()=>{e.catchUpTasks.delete(t)};return t.then(r,r),t}releaseRegisteredCheck(e,t){if(e.releasePromise)return e.releasePromise;let r=e.definition.id;if(this.checks.get(r)===e)this.checks.delete(r);let i=this.releaseRegisteredCheckOnce(e,t);return e.releasePromise=i,i}async releaseRegisteredCheckOnce(e,t){try{await this.settleRegisteredCheck(e,t)}finally{let r=this.pluginChecks.get(e.pluginId);if(r?.delete(e),r?.size===0)this.pluginChecks.delete(e.pluginId)}}async settleRegisteredCheck(e,t){let r=[];if(e.scheduledJob){let i=e.scheduledJob;delete e.scheduledJob;try{r.push(i.stop())}catch(n){r.push(Promise.reject(n))}}if(e.activeCheck)e.activeCheck.controller.abort(t),r.push(e.activeCheck.settled);r.push(...e.catchUpTasks),r.push(this.cancelEnqueueRetry(e)),await this.drainCleanupTasks(r)}async drainCleanupTasks(e){let t=await Promise.allSettled(e),r=[];for(let i of t)if(i.status==="rejected")r.push(i.reason);if(r.length===1)throw r[0];if(r.length>1)throw AggregateError(r,"Recurring check cleanup failed")}schedule(e){let t=e.definition,r=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=Nr(this.currentTime(),i).getTime()+i.periodMs,o=new AbortController,s={controller:o,settled:Promise.resolve()};e.enqueueRetry=s,s.settled=ao(()=>this.enqueue(r.id),t,{firstDelayMs:co,maxDelayMs:lo,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=Nr(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=Ne.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:bp(e,t.observedAt)})===!1)return;await this.state.set(e,{...t,status:"delivered",deliveredAt:this.currentTime().toISOString()})}currentTime(){return this.clock?new Date(this.clock.currentTimeMillisUnsafe()):new Date}lastSuccessKey(e){return`run:${G(e)}`}alertKeyPrefix(e){return`alert:${G(e)}:`}alertKey(e,t){return`${this.alertKeyPrefix(e)}${G(t)}`}}function bp(e,t){return`recurring-alert:${G(`${e}\x00${t}`)}`}function St(e,t,r){let i=r==="daily"?Hr:fp,n=i/60000,o=G(`${e}\x00${t}\x00${r}`),s=Number.parseInt(o.slice(0,12),16)%n,a=s%60,l=Math.floor(s/60),d=l%24;return{expression:r==="daily"?`${a} ${d} * * *`:`${a} ${d} * * ${Math.floor(l/24)}`,offsetMs:s*60000,periodMs:i,anchorMs:r==="daily"?0:hp}}function Nr(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 Sp=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*:[a-z][a-z0-9-]*$/;function Rp(e){if(e.length<=200&&Sp.test(e))return;po(e,"plugin ID")}function po(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=mo("runtime_state_records",{namespace:wt("namespace").notNull(),key:wt("key").notNull(),value:wt("value",{mode:"json"}).notNull(),createdAt:Wr("created_at").notNull(),updatedAt:Wr("updated_at").notNull()},(e)=>({pk:fo({columns:[e.namespace,e.key]}),namespaceUpdatedAtIdx:go("idx_runtime_state_namespace_updated_at").on(e.namespace,e.updatedAt)}));function yo(e){return ho({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 wp}from"util";var Ip=/^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,511}$/,wo=512;class qr{db;namespace;schema;now;constructor(e,t,r,i=()=>new Date){Pp(t),this.db=e,this.namespace=t,this.schema=r,this.now=i}async get(e){let t=he(e),i=(await this.db.select().from(I).where(se(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=he(e);return(await this.db.select({key:I.key}).from(I).where(se(O(I.namespace,this.namespace),O(I.key,t))).limit(1)).length>0}async set(e,t){let r=he(e),i=It(this.schema,t),n=i===null?ye`'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=he(e),i=It(this.schema,t),n=i===null?ye`'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=he(e),n=It(this.schema,r),[o]=await this.db.select({value:I.value}).from(I).where(se(O(I.namespace,this.namespace),O(I.key,i))).limit(1);if(!o||!wp(this.schema.parse(o.value),t))return!1;let s=o.value===null?ye`'null'`:o.value,a=n===null?ye`'null'`:n,l=await this.db.update(I).set({value:a,updatedAt:this.now().getTime()}).where(se(O(I.namespace,this.namespace),O(I.key,i),O(I.value,s)));return Number(l.rowsAffected)===1}async delete(e){let t=he(e),r=await this.db.delete(I).where(se(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(se(O(I.namespace,this.namespace),vo(e.keyPrefix)));return Number(t.rowsAffected)}async listRows(e){let{keyPrefix:t,afterKey:r,limit:i}=e;if(r!==void 0)he(r);if(i!==void 0)c.number().int().min(1).max(1000).parse(i);let n=this.db.select({...bo(I),key:ye`CAST(${I.key} AS BLOB)`.mapWith((o)=>new TextDecoder("utf-8",{fatal:!0}).decode(o))}).from(I).where(se(O(I.namespace,this.namespace),vo(t),r!==void 0?So(I.key,r):void 0)).orderBy(Ro(I.key)).$dynamic();return i===void 0?n:n.limit(i)}}function Pp(e){if(!Ip.test(e))throw Error(`Invalid runtime state namespace: ${e}. Use 1-512 alphanumeric, _, ., :, or - characters.`)}function he(e){if(e.length===0||e.length>wo)throw Error("Runtime state keys must be 1-512 characters long");return e}function vo(e){if(e===void 0)return;return xp(e),ye`substr(CAST(${I.key} AS BLOB), 1, length(CAST(${e} AS BLOB))) = CAST(${e} AS BLOB)`}function xp(e){if(e.length>wo)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}=yo(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 Io(this.client,this.databaseUrl)}catch(e){this.logger.warn("Failed to enable runtime state WAL mode (non-fatal)",e)}finally{if(this.walInitializationSettled=!0,this.closeRequested)this.closeClient()}}scoped(e){let t=new qr(this.db,e.namespace,e.schema);return Object.freeze({get:t.get.bind(t),has:t.has.bind(t),set:t.set.bind(t),setIfNotExists:t.setIfNotExists.bind(t),compareAndSet:t.compareAndSet.bind(t),delete:t.delete.bind(t),list:t.list.bind(t),clear:t.clear.bind(t)})}close(){if(this.closeRequested=!0,!this.walInitialization||this.walInitializationSettled)this.closeClient()}closeClient(){if(this.clientClosed)return;this.clientClosed=!0,this.client.close()}}var Jr=C.Service("@brains/runtime-state/RuntimeStateService");function Po(e){return ne(Jr,()=>{let t=e.service??Pt.createFresh(e.config,e.logger);return{service:t,close:()=>t.close()}})}async function Gr(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=He(r),t.warn(`Daemon ${e.name} failed to start: ${x(r)}`),r}}async function Qr(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=He(r),t.error(`Failed to stop daemon: ${e.name}`,r),r}}async function xo(e){if(!e.daemon.healthCheck)return;try{let t=await e.daemon.healthCheck();return e.health=t,t}catch(t){let r={status:"error",message:x(t),lastCheck:new Date};return e.health=r,r}}function Co(e){return{name:e.name,pluginId:e.pluginId,status:e.status,health:e.health}}class xt{daemons=new Map;daemonScopes=new Map;daemonTransitions=new Map;logger;static createFresh(e){return new xt(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 Gr(t,this.logger);return}let r=b.runSync(D.make()),i=b.acquireRelease(b.promise(()=>Gr(t,this.logger)),()=>b.promise(()=>Qr(t,this.logger)));try{await b.runPromise(D.provide(i,r)),this.daemonScopes.set(e,r)}catch(n){throw await b.runPromise(D.close(r,j.fail(n))),n}}stop(e){if(!this.daemons.has(e))return Promise.reject(Error(`Daemon not registered: ${e}`));return this.enqueueTransition(e,"stop",()=>this.stopDaemon(e))}async stopDaemon(e){let t=this.requireDaemon(e),r=this.daemonScopes.get(e);if(!r){await Qr(t,this.logger);return}this.daemonScopes.delete(e),await b.runPromise(D.close(r,j.void))}async checkHealth(e){let t=this.daemons.get(e);if(!t)throw Error(`Daemon not registered: ${e}`);return xo(t)}getByPlugin(e){return Array.from(this.daemons.values()).filter((t)=>t.pluginId===e)}getAll(){return Array.from(this.daemons.keys())}getAllInfo(){return Array.from(this.daemons.values())}async getStatuses(){let e=this.getAllInfo();for(let t of e)if(t.daemon.healthCheck)await this.checkHealth(t.name);return e.map(Co)}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??=He(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 Cp=c.object({projectionId:c.string().min(1),reason:c.string().min(1),openedAt:c.number().int().nonnegative(),expiresAt:c.number().int().nonnegative()}),Tp=8,Ep=32,Ap=128,kp=5,jp=600000,Dp=600000,zp=1000,Op="shell.projection-circuits";class Ct{operationContext;options;circuitStore;roots=new Map;reservedJobs=new Map;circuits=new Map;projections;static createFresh(e,t={}){return new Ct(e,t)}constructor(e,t){this.operationContext=e,this.options={maxDerivationDepth:t.maxDerivationDepth??Tp,maxJobsPerRoot:t.maxJobsPerRoot??Ep,maxMutationsPerRoot:t.maxMutationsPerRoot??Ap,repeatedTargetLimit:t.repeatedTargetLimit??kp,retentionMs:t.retentionMs??jp,circuitOpenMs:t.circuitOpenMs??Dp,maxTrackedRoots:t.maxTrackedRoots??zp,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:Op,schema:Cp})}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 Mp={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 xe(e){return Mp[e??"combined"]}var To=[Tt.created,Tt.updated,Tt.deleted];function Eo(e,t,r){let i=To.map((o)=>e.subscribe(o,(s)=>(t.send({type:o,payload:s.payload}),{success:!0}))),n=t.onEvent((o)=>{if(!To.includes(o.type))return;e.deliverPeer(o.type,o.payload).catch((s)=>{r.warn(`Failed to deliver peer event ${o.type}`,{error:s})})});return()=>{for(let o of i)o();n()}}var Lp=20,Up=0.5,Bp=0.06,$p=5;function ko(e){return async({answer:t})=>{let i=(await e.entityService.search({query:t,options:{limit:Lp,minScore:Up,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-Bp).slice(0,$p).map(({entity:o})=>Ao(o,e))}}function _p(e,t,r,i,n){return[Oo,Mo,Lo].map((o)=>e.observe(o.name,async(s)=>{let a=o.schema.safeParse(s.payload);if(a.success&&a.data.entityType===t&&(r===null||a.data.entityId===r)){await i();let l=o.name.replace("entity:","");n.debug(`${t} entity ${l}, cache refreshed`)}return{success:!0}}))}function jo(e,t,r,i){return _p(e,t,t,async()=>{await r(),await Te(e,Uo,{entityType:t},"shell")},i)}async function Zp(e,t,r){let i=Fp(e.kind);if(!i)return null;try{let n=t.scoped({namespace:i,refKind:e.kind,routePath:""}),{record:o,content:s}=await n.read(e.id);return No({...o,content:s,source:e})}catch(n){return r.debug("Skipped unavailable prior runtime upload",{uploadKind:e.kind,uploadId:e.id,error:x(n)}),null}}function Fp(e){return e===Ce.refKind?Ce.namespace:null}function Jo(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=Ho.createFresh(r,i,t.identity);d.push(...jo(n,M.BRAIN_CHARACTER,()=>p.refreshCache(),i));let m=Wo.createFresh(r,i,t.profile),g=qo.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=Fo({guestPricing:Bo(o.getConfig().model),model:o.getModel(),answerModel:o.getAnswerModel?.(),modelId:o.getConfig().model,webSearch:o.getConfig().webSearch,temperature:o.getConfig().temperature,reasoningEffort:o.getConfig().reasoningEffort,messageBus:n}),h=$o(t.name),v=new ft(t.entityDisplay),y={isCitable:(R)=>v.isCitable(R),urlFor:(R,w)=>v.generateUrl(R,w),siteBaseUrl:t.siteBaseUrl},S=_o.createFresh(s,a,p,m,i,{agentFactory:f,turnEvents:Zo(n),canonicalIdentityResolver:g,entityLinks:y,...e.generationUsage?{generationUsage:e.generationUsage}:{},...e.embeddingUsage?{embeddingUsage:e.embeddingUsage}:{},...t.embedding.enabled?{indexReadiness:r,guestAnswerSources:ko({entityService:r,...y})}:{},uploadAttachmentResolver:(R)=>Zp(R,l,i),guestAskedBefore:async(R)=>{let w=await We(n,Do,R,"shell:agent-service");return w.status==="answered"?w.answers.find((P)=>P.hit)?.hit:void 0},agentContextProvider:async(R)=>{let w=await We(n,zo,R,"shell:agent-service");return w.status==="answered"?w.answers.flatMap((P)=>P.items):[]},...h?{assistantAgentId:h}:{},...t.agentInstructions&&{agentInstructions:t.agentInstructions}});if(d.push(...jo(n,M.ANCHOR_PROFILE,()=>m.refreshCache(),i)),!u)d.push(n.subscribe(qe.identityChanged,async()=>(S.invalidateAgent(),{success:!0})));return{identityService:p,profileService:m,canonicalIdentityService:g,agentService:S}}var Je=C.Service("@brains/job-queue/JobQueueService"),Et=C.Service("@brains/job-queue/BatchJobManager"),At=C.Service("@brains/job-queue/JobProgressMonitor"),kt=C.Service("@brains/job-queue/JobQueueWorker");function Yo(e){return ne(Je,()=>{let t=e.service??Go.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 Xo(e){let t=!1,r=b.gen(function*(){let i=yield*Je,n=e.batchJobManager??Ko.createFresh(i,e.logger),o=e.jobProgressMonitor??Vo.createFresh(i,e.messageBus,n,e.logger,e.progressMonitorMode),s=e.jobQueueWorker??Qo.createFresh(i,o,e.logger,{pollInterval:100,concurrency:e.workerConcurrency,autoStart:!1,...e.onWorkerUnhealthy&&{onUnhealthy:e.onWorkerUnhealthy}},{...e.operationContext&&{operationContext:e.operationContext},...e.projectionBatchScope&&{projectionBatchScope:e.projectionBatchScope}});return C.make(Et,n).pipe(C.add(At,o),C.add(kt,s))});return{layer:Q.effectContext(b.acquireRelease(r,(i)=>t?b.void:Np(i))),abandon:()=>{t=!0}}}function Np(e){let t=C.get(e,kt),r=C.get(e,At),i=C.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(j.isFailure);if(a)yield*b.die(oe.squash(a.cause))})}function Hp(e,t=(r)=>process.exit(r)){return(r)=>{e.error("Job queue worker requires process restart",{reason:r,exitCode:1}),t(1)}}function jt(e){let t=b.runSyncExit(D.close(e,j.void));if(j.isFailure(t))throw oe.squash(t.cause)}function es(e){let t=e.operationContext??Dt.createFresh(),r=b.runSync(D.make()),i,n;try{let o=b.runSync(Q.buildWithScope(Yo({config:e.jobQueueConfig,logger:e.logger,operationContext:t,...e.projectionAdmission&&{projectionAdmission:e.projectionAdmission},...e.handlerRegistrationMode&&{handlerRegistrationMode:e.handlerRegistrationMode},...e.dependencies?.jobQueueService&&{service:e.dependencies.jobQueueService}}),r)),s=C.get(o,Je),a=b.runSync(D.make());i=a;let l=Xo({messageBus:e.messageBus,logger:e.logger,operationContext:t,...e.projectionBatchScope&&{projectionBatchScope:e.projectionBatchScope},onWorkerUnhealthy:Hp(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(Q.buildWithScope(l.layer.pipe(Q.provide(Q.succeed(Je,s))),a)),u=C.get(d,Et),p=C.get(d,At),m=C.get(d,kt),g,f=!1,h=!1;return{batchJobManager:u,jobProgressMonitor:p,jobQueueService:s,jobQueueWorker:m,closeRuntime:()=>(f=!0,g??=b.runPromise(D.close(a,j.void)),g),rollbackRuntime:()=>{if(f)return;f=!0,l.abandon(),jt(a)},closeDatabase:()=>{if(h)return;h=!0,jt(r)}}}catch(o){if(i)try{n?.abandon(),jt(i)}catch(s){e.logger.warn("Failed to release partial job runtime acquisition",s)}try{jt(r)}catch(s){e.logger.warn("Failed to release partial job database acquisition",s)}throw o}}function rs(e){return{deliver:async(t,{idempotencyKey:r})=>{let i=await yt(e,ts,{title:t.title,body:t.body,...t.html?{html:t.html}:{},...t.sensitivity?{sensitivity:t.sensitivity}:{},idempotencyKey:r},"shell.recurring-checks");if(i.status==="unavailable")return!1;if(i.status==="failed"||i.data.status!=="sent")throw Error("Recurring alert delivery failed");return!0}}}function ns(e){return{sourceId:"recurring-checks",displayName:"Recurring checks",list:async()=>(await e.listOpenAlerts()).map((t)=>({id:t.id,title:is(t.title,160),summary:is(t.body,1000),receivedAt:t.observedAt,urgency:"high",actions:[{id:"resolve",label:"Dismiss",confirm:!0}]})),act:async(t,r)=>{if(r!=="resolve")throw Error("Invalid recurring-check inbox action");await e.resolveOpenAlert(t)}}}function is(e,t){return e.length<=t?e:e.slice(0,t)}function os(e,t){if(t)return t;let r={debug:Ge.DEBUG,info:Ge.INFO,warn:Ge.WARN,error:Ge.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 zs(e){let{config:t,dependencies:r,initializerLogger:i,lifecycle:n,processRole:o,peerChannel:s}=e;i.debug("Initializing Shell services");let a=xe(o),l=os(t,r?.logger),d=r?.operationContext??Dt.createFresh(),u=[],p=Cs.createFresh(!r?.embeddingService),m=r?.embeddingService??xs.createFresh({providerKeys:t.ai.providerKeys,profile:Is(t.ai.embeddingModel),runtimeUrl:t.ai.modelRuntimeUrl,logger:l,usage:p}),g=Ts.createFresh(),f=r?.aiService??Ps.createFresh(Kr(t),l,g),h=r?.entityRegistry??cs.createFresh(l),v=r?.messageBus??as.createFresh(l,d);if(s)u.push(Eo(v,s,l));let y=r?.templateRegistry??ds.createFresh(l),S=r?.dataSourceRegistry??ls.createFresh(l),R=r?.renderService??ps.createFresh(y),w=r?.daemonRegistry??xt.createFresh(l),P=r?.pluginManager??ks.createFresh(l,w),E=r?.permissionService??new us(t.permissions,{spaces:t.spaces,entityActionFloor:(q)=>h.getEntityTypeConfig(q).actionPolicy}),L=r?.profileKindRegistry??new As(t.profileKind),Re=r?.channelRegistry??new hs,pe=r?.inboxRegistry??new vs,te=r?.inboxFollowUpRegistry??new bs(l),ru=r?.operationalHealthRegistry??new Es,iu=r?.accountSettingsRegistry??new fs,nu=new ys,ou=new ht,su=r?.attachmentRegistry??Ss.createFresh(),pn=r?.runtimeUploadRegistry??Rs.createFresh({dataDir:t.dataDir,logger:l}),au=n.buildLayer(Po({config:Ee(t.runtimeStateDatabase),logger:l,...r?.runtimeStateService&&{service:r.runtimeStateService}})),Ir=C.get(au,Jr),Pr=r?.projectionRuntimeSupervisor??Ct.createFresh(d,{runtimeState:Ir}),mn=r?.mcpService??ws.createFresh(v,l),xr={},cu={runFreshBatchScope:(q)=>xr.current?xr.current.runFreshBatchScope(q):q()},at=es({dependencies:r,jobQueueConfig:{...Ee(t.jobQueueDatabase),brainVersion:t.version},workerConcurrency:t.jobQueue.workerConcurrency,messageBus:v,operationContext:d,projectionBatchScope:cu,projectionAdmission:Pr,handlerRegistrationMode:a.handlerRegistrationMode,progressMonitorMode:a.progressMonitorMode,logger:l}),{batchJobManager:lu,jobProgressMonitor:du,jobQueueService:Cr,jobQueueWorker:uu}=at;n.addSyncFinalizer(()=>at.closeDatabase()),n.addSyncFinalizer(()=>at.rollbackRuntime());let Be=r?.recurringCheckService??new Rt({brainId:t.siteBaseUrl??t.dataDir,scheduler:new js,runtimeState:Ir,clock:b.runSync(ss.Clock),jobQueue:Cr,logger:l,delivery:rs(v)});n.addSyncFinalizer(()=>Be.abandon()),pe.registerSource("shell.recurring-checks",ns(Be)),n.addSyncFinalizer(()=>pe.unregisterPlugin("shell.recurring-checks"));let gn=(q,Er)=>{if(!a.serves)return;w.register(q,Er,"shell"),n.addSyncFinalizer(()=>w.abandon(q))};gn("shell:recurring-checks",{start:()=>Be.start(),stop:()=>Be.stop()});let pu=n.buildLayer(so({embeddingService:m,embeddingsEnabled:t.embedding.enabled,entityRegistry:h,logger:l,jobQueueService:Cr,messageBus:v,mutationAdmission:Pr,...r?.projectionRuntime?.now&&{projectionNow:r.projectionRuntime.now},dbConfig:Ee(t.database),embeddingDbConfig:Ee(t.embeddingDatabase),...r?.entityService&&{service:r.entityService}})),ct=C.get(pu,Zr);xr.current=ct.getProjectionStore();let mu=n.buildLayer(no({dbConfig:Ee(t.conversationDatabase),logger:l,messageBus:v,...r?.conversationService&&{service:r.conversationService}})),Tr=C.get(mu,_r);gn("shell:guest-retention",Ds({intervalMs:60000,logger:l,run:async()=>{await Tr.deleteExpiredGuestConversations(100)}})),n.addSyncFinalizer(()=>{for(let q of u.splice(0))try{q()}catch(Er){l.warn("Failed to dispose shell subscription",Er)}});let fn=ro(E,v),gu=r?.contentService??new gs({logger:l,entityService:ct,aiService:f,templateRegistry:y,dataSourceRegistry:S,generationAuthorizer:new ms(E,fn)}),{identityService:fu,profileService:hu,canonicalIdentityService:yu,agentService:vu}=Jo({config:t,entityService:ct,embeddingService:m,embeddingUsage:p,...!r?.aiService?{generationUsage:g}:{},entityRegistry:h,logger:l,messageBus:v,aiService:f,mcpService:mn,conversationService:Tr,runtimeUploadRegistry:pn,disposables:u,executionOnly:!a.serves});return{logger:l,operationContext:d,projectionRuntimeSupervisor:Pr,disposables:u,entityRegistry:h,messageBus:v,renderService:R,daemonRegistry:w,pluginManager:P,templateRegistry:y,dataSourceRegistry:S,mcpService:mn,embeddingService:m,entityService:ct,aiService:f,conversationService:Tr,contentService:gu,callerAuthorizer:fn,jobQueueService:Cr,jobQueueWorker:uu,batchJobManager:lu,jobProgressMonitor:du,jobServicesLifecycle:at,permissionService:E,identityService:fu,profileService:hu,canonicalIdentityService:yu,profileKindRegistry:L,channelRegistry:Re,inboxRegistry:pe,inboxFollowUpRegistry:te,operationalHealthRegistry:ru,accountSettingsRegistry:iu,authRegistry:nu,atprotoProjectionRegistry:ou,agentService:vu,attachmentRegistry:su,runtimeUploadRegistry:pn,runtimeStateService:Ir,recurringCheckService:Be}}function $s(e,t){e.register(Vr.name,Vr),t.debug("Shell system templates registered")}function _s(e,t){e.register(Fe.BASE_ENTITY_DISPLAY,{name:"base-entity-display",description:"Display template for base entities",schema:Yr,formatter:new Os,requiredPermission:"public"}),t.debug("Base entity display template registered")}function Zs(e,t){e.registerEntityType(M.NOTE,Yr,new Ms,{projectionSourceRole:"primary"}),t.debug("Fallback base entity adapter registered")}function Fs(e,t){let r=new Ls;e.registerEntityType(M.BRAIN_CHARACTER,r.schema,r,{classification:"system",projectionSource:!1,projectionSourceRole:"excluded"}),t.debug("Brain character entity support registered")}function Ns(e,t){let r=new Us;e.registerEntityType(M.ANCHOR_PROFILE,r.schema,r,{classification:"system",projectionSourceRole:"canonical"}),t.debug("Anchor profile entity support registered")}async function Hs(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 Bs||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){$s(e,this.logger)}registerBaseEntityDisplayTemplate(e){_s(e,this.logger)}registerFallbackBaseEntity(e){Zs(e,this.logger)}registerBrainCharacterSupport(e){Fs(e,this.logger)}registerAnchorProfileSupport(e){Ns(e,this.logger)}async initializePlugins(e,t){await Hs({plugins:this.config.plugins,pluginManager:e,logger:this.logger,initOptions:t})}initializeServices(e,t){return zs({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=qs.createFresh(t,r);e.registerHandler(Ws.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((P)=>P.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 P=await this.store.listPendingInputs();return await this.recordDiagnostic({...p,event:"apply-completed",applyOutcome:"superseded",highestPendingGeneration:Ot(P)}),{waveId:n.waveId,ruleId:o.id,outcome:"superseded",inputFingerprint:null,changedTargets:[]}}if(await this.store.supersedeWaveIfStale(n.waveId,this.now())){let P=await this.store.listPendingInputs();return await this.recordDiagnostic({...p,event:"apply-completed",applyOutcome:"superseded",highestPendingGeneration:Ot(P)}),await this.coordinator.continueAfterSupersession(n.waveId),{waveId:n.waveId,ruleId:o.id,outcome:"superseded",inputFingerprint:null,changedTargets:[]}}let m=Jp(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:qp(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(P){throw await this.recordDiagnostic({...h,event:i.aborted?"derive-cancelled":"derive-failed",memoHit:!1}),P}}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 qp(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 Jp(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 Gp(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 Js;scheduledWakeup;constructor(e){this.store=e.store,this.queue=e.queue,this.graph=e.graph,this.ruleById=Vp(e.graph,e.rules),this.graphFingerprint=Yp(e.graph,e.rules),this.createWaveId=e.createWaveId,this.beforeWaveCompletion=e.beforeWaveCompletion??(async()=>{}),this.scheduleWakeup=e.scheduleWakeup??Qp,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=Kp(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=Qs(this.graph,this.ruleById,s);if(a.length===0)return this.completeWave(e);await this.store.putWaveRules(e.id,a),t=await this.store.listWaveRules(e.id)}if(t.every((s)=>s.status==="completed"))return this.completeWave(e,t);let r=t.find((s)=>s.status==="failed");if(r)return this.store.failWaveWithIncident({waveId:e.id,ruleId:r.ruleId,jobId:r.jobId,failureReason:"Projection rule is in a terminal failed state",failedAt:this.now()});let i=await this.findStrandedQueuedRule(t);if(i)return this.store.failWaveWithIncident({waveId:e.id,ruleId:i.rule.ruleId,jobId:i.rule.jobId,failureReason:Gp(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 Qp(e,t){let r=setTimeout(()=>{t()},e);return()=>clearTimeout(r)}function Kp(e,t,r){let n=Qs(e,t,r).reduce((s,a)=>Math.max(s,t.get(a.ruleId)?.sourceChangeBatchDelayMs??0),0);if(n===0)return 0;return r.reduce((s,a)=>Math.max(s,a.markedAt),0)+n}function Vp(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 Yp(e,t){return Gs({projections:e.projections,edges:e.edges,rules:[...t].sort((r,i)=>r.id.localeCompare(i.id)).map((r)=>({id:r.id,version:r.version}))})}function Qs(e,t,r){let i=new Map(e.projections.map((l)=>[l.id,l])),n=Ks(e,(l)=>[l.from,l.to]),o=new Set(e.projections.filter((l)=>Xp(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=em(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 Xp(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 em(e,t){let r=Ks(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 Ks(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 Vs(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??tm)(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 tm(e,t){let r=setInterval(()=>{t()},e);return r.unref(),()=>clearInterval(r)}import{existsSync as Wm}from"fs";import{mkdir as qm,writeFile as Jm}from"fs/promises";import{join as Gm,resolve as qa}from"path";var Ys=5000;async function Xs(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 ea(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 N,join as Zm,sep as Fm}from"path";var ta=Symbol();var ra=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,(r)=>r.toLowerCase())}}).formData();var rm=1e4,Mt=(e)=>("headers"in e),oa=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 im(e,{all:r,dot:i});return{}};async function im(e,t){if(!Mt(e)&&e.bodyCache.formData)return ia(await e.bodyCache.formData,t);let r=Mt(e)?e.headers:e.raw.headers,i=await e.arrayBuffer(),n=ra(i,r.get("Content-Type")||"");if(!Mt(e))e.bodyCache.formData=n;let o=await n;if(o)return ia(o,t);return{}}function ia(e,t){let r=Object.create(null),i={count:0};if(e.forEach((n,o)=>{if(!(t.all||o.endsWith("[]")))r[o]=n;else nm(r,o,n)}),t.dot)Object.entries(r).forEach(([n,o])=>{if(n.includes("."))om(r,n,o,i),delete r[n]});return r}var nm=(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]},om=(e,t,r,i)=>{if(/(?:^|\.)__proto__\./.test(t))return;let n=e,o=t.split(".",34);if(o.length>33)na();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++>=rm)na();n[s]=Object.create(null)}n=n[s]}})},na=()=>{throw Error("Nesting limit exceeded")};var ni=(e)=>{let t=e.split("/");if(t[0]==="")t.shift();return t},sa=(e)=>{let{groups:t,path:r}=sm(e),i=ni(r);return am(i,t)},sm=(e)=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,i)=>{let n=`@${i}`;return t.push([n,r]),n}),{groups:t,path:e}},am=(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={},aa=(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},ca=(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)=>ca(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 la=(e)=>{let t=si(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},ae=(e,t,...r)=>{if(r.length)t=ae(t,...r);return`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`},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?ca(e,cm):e,ii=(e)=>{if(e.indexOf("+")!==-1)e=e.replace(/\+/g," ");return Bt(e)},da=(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},ua=da,pa=(e,t)=>da(e,t,!0),cm=decodeURIComponent;var ma=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 ua(this.url,e)}queries(e){return pa(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 oa(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[ta](){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 ga={Stringify:1,BeforeStream:2,Stream:3},fa=(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 fa(await s,o);else return s};var lm="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 ma(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(lm,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,ga.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 ha=["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 dm=(e)=>e.text("404 Not Found",404),ya=(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)},va=class e{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...ha,"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:la}#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=dm;errorHandler=ya;route(t,r){let i=this.basePath(t);return r.routes.map((n)=>{let o;if(r.errorHandler===ya)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=ae(this._basePath,t),r}onError=(t)=>(this.errorHandler=t,this);notFound=(t)=>(this.#r=t,this);mount(t,r,i){let n,o;if(i)if(typeof i==="function")o=i;else if(o=i.optionHandler,i.replaceRequest===!1)n=(l)=>l;else n=i.replaceRequest;let s=o?(l)=>{let d=o(l);return Array.isArray(d)?d:[d]}:(l)=>{let d=void 0;try{d=l.executionCtx}catch{}return[l.env,d]};n||=(()=>{let l=ae(this._basePath,t),d=l==="/"?0:l.length;return(u)=>{let p=new URL(u.url);return p.pathname=this.getPath(u).slice(d)||"/",new Request(p,u)}})();let a=async(l,d)=>{let u=await r(n(l.req.raw),...s(l));if(u)return u;await d()};return this.#o("ALL",ae(t,"*"),a),this}#o(t,r,i,n){r=ae(this._basePath,r);let o={basePath:n!==void 0?ae(this._basePath,n):this._basePath,path:r,method:t,handler:i};this.router.add(t,r,[i,o]),this.routes.push(o)}#i(t,r){if(t instanceof Error)return this.errorHandler(t,r);throw t}#n(t,r,i,n){if(n==="HEAD")return(async()=>new Response(null,await this.#n(t,r,i,"GET")))();let o=this.getPath(t,{env:i}),s=this.router.match(n,o),a=new 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${ae("/",t)}`,r),i,n)};fire=()=>{addEventListener("fetch",(t)=>{t.respondWith(this.#n(t.request,t,void 0,t.request.method))})}};var k=()=>Object.create(null);var 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="(?:|/.*)",ce=Symbol(),ba=new Set(".\\+*[^]$()");function um(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 Sa=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 ce;if(g=g.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(g))throw ce;if(g.length===1&&ba.has(g))throw ce}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 ce}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 ce;p=s.#r[d]=new e}s=p}if(s.#t!==void 0)throw ce;s.#t=o?-1:r}buildRegExpStr(){let t=Object.keys(this.#r).sort(um).map((r)=>{let i=this.#r[r],n=i.buildRegExpStr();return n===""?"":(typeof i.#e==="number"?`(${r})@${i.#e}`:ba.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 Sa;#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 Ra=k();function wa(e){return Ra[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(wa(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===ce?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=wa(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,Ra=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 Ia=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(),pm=0,Pa=class e{#t=[];#e=k();#r=[];#o;#i=hi;insert(t,r,i){let n=this,o=sa(r),s=new Set,a=0;for(let l of o){let d=o[++a],u=aa(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:++pm}})}#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[,P,E]=R;if(!u&&E===!0)continue;if(E!==!0){if(!l){l=[];let pe=r[0]==="/"?1:0;for(let te=0;te<a;te++)l[te]=pe,pe+=o[te].length+1}let L=r.slice(l[d]),Re=E.exec(L);if(Re){if(w[P]=Re[0],this.#n(i,S,t,v.#i,w),Re[0].length===L.length&&S.#e["*"])this.#n(i,S.#e["*"],t,v.#i,w);for(let pe in S.#e){S.#i=w;let te=Re[0].match(/\//g)?.length??0;(s[te]||=[]).push(S);break}continue}}if(E===!0||E.test(u))if(w[P]=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 Pa;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 va{constructor(e={}){super(e);this.router=e.router??new Ia({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=mm)=>{let r=e.match(/\.([a-zA-Z0-9]+?)$/);if(!r)return;return t[r[1].toLowerCase()]};var mm={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 xa=(...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 Ca={br:".br",zstd:".zst",gzip:".gz"},gm=Object.keys(Ca),fm="index.html",Ta=(e)=>{let t=e.root??"./",r=e.path,i=e.join??xa;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,fm);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 gm){if(!p.has(m))continue;let g=await l(a+Ca[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 hm}from"fs/promises";import{join as ym}from"path";var Si=(e={})=>async function(r,i){return Ta({...e,getContent:async(s)=>{let a=Bun.file(s);return await a.exists()?a:null},join:ym,isDir:async(s)=>{let a;try{a=(await hm(s)).isDirectory()}catch{}return a}})(r,i)};var Ea="x-hono-disable-ssg",Zw=(()=>{try{return new Response("SSG is disabled",{status:404,headers:{[Ea]:"true"}})}catch{return null}})();var{write:kI}=Bun;var Aa=(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 Rm=Aa((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 ja=(e)=>e===32||e===9||e===10||e===13,Wt=(e,t)=>{while(t<e.length){if(!ja(e.charCodeAt(t)))break;t++}return t},Ke=(e,t)=>{while(t>0){if(!ja(e.charCodeAt(t-1)))break;t--}return t},ka=(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]},wm=(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},Im=(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,Ke(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=ka(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=ka(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,Ke(e,r)),l===59)o=!0;r++;break}r++}return[r,i,n??e.slice(a,Ke(e,r)),o]},Pm=(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,Ke(e,i)),i++,a===44)return[i,r.type?r:void 0];if(!r.type)return[wm(e,i),void 0];break}i++}if(!r.type)return r.type=e.slice(t,Ke(e,e.length)),[e.length,r.type?r:void 0];let n,o,s;while(i<e.length){if([i,n,o,s]=Im(e,i),n&&o)r.params[n]=o;if(!s)break}return[i,r]},Da=(e)=>{if(!e)return[];let t=[],r=0,i,n=!1,o;while(r<e.length)if([r,i]=Pm(e,r),i){if(i.q=xm(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},xm=(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 Cm=["gzip","deflate"],Tm=/(?:^|,)\s*?no-transform\s*?(?:,|$)/i,Em=(e,t)=>{if(e===void 0)return;let r=Da(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},Am=/(?:^|,)\s*accept-encoding\s*(?:,|$)/i,za=(e)=>{let t=e?.threshold??1024,r=e?.encoding?[e.encoding]:Cm,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)||!km(s.res))return;let d=s.res.headers.get("Vary");if(d!=="*"&&!(d&&Am.test(d)))s.header("Vary",d?`${d}, Accept-Encoding`:"Accept-Encoding");let u=s.req.header("Accept-Encoding"),p=Em(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}`)}},km=(e)=>{let t=e.headers.get("Cache-Control");return!t||!Tm.test(t)};import{Readable as Oa}from"stream";import{createDeflate as jm,createGzip as Dm}from"zlib";var zm=["gzip","deflate"],Om=/(?:^|,)\s*?no-transform\s*?(?:,|$)/i,Ma=(e)=>{if(typeof CompressionStream<"u")return za(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||!Mm(i.res)||!Lm(i.res))return;let s=i.req.header("Accept-Encoding"),a=e?.encoding??zm.find((l)=>s?.includes(l));if(!a||!i.res.body)return;try{let l=a==="gzip"?Dm():jm(),d=Oa.fromWeb(i.res.body).pipe(l),u=Oa.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)}}},Mm=(e)=>{let t=e.headers.get("Content-Type");return t&&ke.test(t)},Lm=(e)=>{let t=e.headers.get("Cache-Control");return!t||!Om.test(t)};var Um=(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 La=async(e,t)=>{if(!e)return null;let r=void 0,i,n=0,o=async(a)=>{r=await t(Um(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 Bm=["cache-control","content-location","date","etag","expires","vary"],Ua=(e)=>e.replace(/^W\//,"");function $m(e,t){return t!=null&&t.split(",").some((r)=>Ua(r.trim())===Ua(e))}function _m(e){if(!e){if(crypto&&crypto.subtle)e=(t)=>crypto.subtle.digest({name:"SHA-1"},t)}return e}var Ba=(e)=>{let t=new Set((e?.retainedHeaders??Bm).map((n)=>n.toLowerCase())),r=e?.weak??!1,i=_m(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 La(l.clone().body,i);if(u===null)return;d=r?`W/"${u}"`:`"${u}"`}if(a==="*"||$m(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=$a.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 Ve(e,t){return e===t||e.startsWith(t+Fm)}var _a="public, max-age=31536000, immutable";function Nm(e){return e.getRoutes?.()??[]}var Hm=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=N(e,`.${t}`,"index.html");if(!Ve(n,N(e)))return;let o=Bun.file(n);if(!await o.exists())return;let s=`<div ${Na}="${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:N(process.cwd(),e.productionDistDir),sharedImagesDir:N(process.cwd(),e.sharedImagesDir),...e.previewDistDir&&{previewDistDir:N(process.cwd(),e.previewDistDir)}}}async start(){if(this.productionServer){this.logger.warn("Webserver already running");return}this.stopping=!1,this.routes=Object.freeze([...Nm(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??Hm,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 Xs(e,{drainMs:this.options.shutdownDrainMs??Ys,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}: ${x(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:x(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("/*",Ma());return t.use("/*",Ba()),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",_a);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(Za,(r)=>r.body(Fa,200,{"Content-Type":"image/svg+xml; charset=utf-8","Cache-Control":"public, max-age=86400"})),t.notFound(async(r)=>{let i=Bun.file(Zm(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:x(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=ea(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=N(t.distDir,`.${i}`,"index.html");if(Ve(a,N(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=N(this.options.sharedImagesDir,r);if(!Ve(i,this.options.sharedImagesDir))return null;let n=Bun.file(i);if(!await n.exists())return null;return new Response(n,{headers:{"Cache-Control":_a}})}createCleanUrlMiddleware(e){return async(t,r)=>{let i=t.req.path;if(i.includes(".")||i==="/"){await r();return}let n=N(e,`.${i}`,"index.html");if(!Ve(n,e)){await r();return}let o=Bun.file(n);if(await o.exists())return t.html(await o.text());let s=N(e,`.${i}.html`);if(Ve(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:Ha(t,"anonymous")}},sender:t})}var Pi=`<!DOCTYPE html>
|
|
10
|
+
`):zu}formatRelevantEntity(e,t){let{entity:r,excerpt:i}=e,n=r.entityType,o=Du.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 Uu=c.object({entityType:c.string(),query:c.object({id:c.string()})});class ft{entityService;id=Mr.ENTITIES;name="Entity DataSource";description="Fetches entity content from the entity service";constructor(e){this.entityService=e}async fetch(e,t,r){let i=Uu.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 Tn(e,t){e.dataSourceRegistry.register(new gt(e.aiService,e.entityService,e.templateRegistry,()=>e.identityService.getCharacterContent(),()=>e.profileService.getProfileContent(),new ht(t.entityDisplay),t.siteBaseUrl)),e.dataSourceRegistry.register(new ft(e.entityService)),e.logger.debug("Core DataSources registered")}async function En(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 An={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 kn={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 jn={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 Dn={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 On={lexicon:1,id:"ai.rizom.brain.post",defs:{main:{type:"record",description:"Markdown blog post distributed by a Rizom brain.",key:"any",record:{type:"object",required:["title","body","createdAt"],properties:{title:{type:"string",maxLength:300},summary:{type:"string",maxLength:2000},body:{type:"string",maxLength:1e5},format:{type:"string",knownValues:["text/markdown"]},brainDid:{type:"string"},anchorDid:{type:"string"},canonicalUrl:{type:"string",format:"uri"},topics:{type:"array",items:{type:"string"},maxLength:50},coverImage:{type:"ref",ref:"#coverImage"},series:{type:"string",maxLength:200},seriesIndex:{type:"integer"},sourceEntityType:{type:"string",knownValues:["post"]},sourceEntityId:{type:"string"},createdAt:{type:"string",format:"datetime"},updatedAt:{type:"string",format:"datetime"},publishedAt:{type:"string",format:"datetime"}}}},coverImage:{type:"object",description:"Cover image attached to the post.",required:["blob"],properties:{blob:{type:"blob"},alt:{type:"string",maxLength:1000},width:{type:"integer"},height:{type:"integer"}}}}};var zn={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 Mn={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 Ln={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 Un={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 Bn=c.object({type:c.string()}).catchall(c.unknown()),Ju=c.object({type:c.literal("object"),description:c.string().optional(),required:c.array(c.string()).optional(),properties:c.record(c.string(),Bn)}),Gu=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(),Bn)})})}).catchall(Ju)});function F(e){return Gu.parse(e)}var O={"ai.rizom.brain.card":F(An),"ai.rizom.brain.deck":F(kn),"ai.rizom.brain.link":F(jn),"ai.rizom.brain.note":F(Dn),"ai.rizom.brain.post":F(On),"ai.rizom.brain.project":F(zn),"ai.rizom.brain.series":F(Mn),"ai.rizom.brain.socialPost":F(Ln),"ai.rizom.brain.topic":F(Un)},Qu="Additive optional fields are compatible; required-field, type, or constraint changes require a migration plan or new NSID.";function J(e){return{status:"approved",version:"1.0.0",revision:1,owner:"Rizom",steward:"Rizom protocol registry",projectionPackage:e,compatibility:Qu}}var $n={"ai.rizom.brain.card":J("@brains/atproto"),"ai.rizom.brain.deck":J("@brains/decks"),"ai.rizom.brain.link":J("@brains/link"),"ai.rizom.brain.note":J("@brains/note"),"ai.rizom.brain.post":J("@brains/blog"),"ai.rizom.brain.project":J("@brains/portfolio"),"ai.rizom.brain.series":J("@brains/series"),"ai.rizom.brain.socialPost":J("@brains/social-media"),"ai.rizom.brain.topic":J("@brains/topics")};function Ku(){return Object.values(O)}function Vu(e){if(!Ur(O,e))return;return O[e]}function Yu(){return Lr($n).map(([e,t])=>({id:e,...t}))}var Xu=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;function ep(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)=>Xu.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 tp(e,t){if(typeof e!=="string"||!e.startsWith("#"))return;let r=t[e.slice(1)];return r?.type==="object"?r:void 0}function Zn(e,t){switch(e.type){case"string":return ep(e);case"integer":return c.number().int();case"boolean":return c.boolean();case"array":{let r=e.items?Zn(e.items,t):c.unknown(),i=c.array(r);if(e.maxLength!==void 0)i=i.max(e.maxLength);return i}case"object":return _n(e,t);case"ref":{let r=tp(e.ref,t);if(!r)return c.custom(()=>!1,{message:`unresolvable lexicon ref ${String(e.ref)}`});return c.lazy(()=>_n(r,t))}case"blob":return c.custom(ie,{message:"expected blob"});default:return c.unknown()}}function Fn(e,t){let r=new Set(e.required??[]),i={};for(let[n,o]of Object.entries(e.properties??{})){let s=Zn(o,t);i[n]=r.has(n)?s:s.optional()}return i}function _n(e,t){return c.strictObject(Fn(e,t))}function U(e){return c.strictObject({...Fn(e.defs.main.record,e.defs),$type:c.literal(e.id).optional()})}var Br={"ai.rizom.brain.card":U(O["ai.rizom.brain.card"]),"ai.rizom.brain.deck":U(O["ai.rizom.brain.deck"]),"ai.rizom.brain.link":U(O["ai.rizom.brain.link"]),"ai.rizom.brain.note":U(O["ai.rizom.brain.note"]),"ai.rizom.brain.post":U(O["ai.rizom.brain.post"]),"ai.rizom.brain.project":U(O["ai.rizom.brain.project"]),"ai.rizom.brain.series":U(O["ai.rizom.brain.series"]),"ai.rizom.brain.socialPost":U(O["ai.rizom.brain.socialPost"]),"ai.rizom.brain.topic":U(O["ai.rizom.brain.topic"])};function rp(e,t){let r=e;for(let i of t){if(typeof i==="symbol")return;if(Array.isArray(r)){r=r[Number(i)];continue}if(!ie(r))return;r=r[String(i)]}return r}function ip(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"&&rp(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 np(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(ip(e,t,i))}var Nn="atproto:brain-card-discovered",Hn="atproto:brain-discovered",Wn="atproto:brain-card-refreshed",qn="atproto:brain-card-unavailable",Jn="atproto:brain-card-conflict",Gn="atproto:jetstream-gap",op=c.custom((e)=>Br["ai.rizom.brain.card"].safeParse(e).success),Qn=c.object({repoDid:c.string().min(1),uri:c.string().min(1),cid:c.string().min(1),record:op}).strict(),$r=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(),Kn=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(),Vn=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(),Yn=c.object({previousCursorTimeUs:c.number().int().nonnegative(),clampedCursorTimeUs:c.number().int().nonnegative(),observedAt:c.string().datetime()}).strict(),sp=fe(Nn,Qn),ap=fe(Hn,$r),cp=fe(Wn,$r),lp=fe(qn,Kn),dp=fe(Jn,Vn),up=fe(Gn,Yn);class yt{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 pp({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 bt(e,t,r){let i=await vt(e,Xn,{actor:r},t);if(i.status==="unavailable")return null;if(i.status==="failed")throw eo(i.error,`Principal resolution failed: ${i.error.message}`);return i.data.principal}function ro(e,t){return new to(e,(r)=>bt(t,"shell:content-service",r))}var _r=C.Service("@brains/conversation-service/ConversationService");function mp(e){if(e.service){let r=e.service;return{service:r,close:()=>r.close()}}let t=io.createFreshFromConfig(e.logger,e.messageBus,e.dbConfig);try{return{service:t,close:()=>t.close()}}catch(r){throw t.close(),r}}function no(e){return ne(_r,()=>mp(e))}var Zr=C.Service("@brains/entity-service/EntityService");function gp(e){return"close"in e&&typeof e.close==="function"}function so(e){return ne(Zr,()=>{let t=e.service??oo.createFresh(e);return{service:t,close:()=>{if(gp(t))t.close()}}})}var He=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()}),Fr=c.strictObject({alerts:c.array(He).optional()});var St="shell:recurring-check",Hr=86400000,fp=7*Hr,hp=3*Hr,yp=c.strictObject({checkId:c.string().min(1)}),vp=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:He,observedAt:c.string().datetime(),includeInInbox:c.boolean().optional(),deliveredAt:c.string().datetime().optional(),resolvedAt:c.string().datetime().optional()})]);class wt{brainId;scheduler;state;jobQueue;delivery;logger;clock;checks=new Map;pluginChecks=new Map;alertOperations=new uo;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:vp});let t={validateAndParse:(r)=>{let i=yp.safeParse(r);return i.success?i.data:null},process:async(r)=>{await this.runNow(r.checkId)}};this.jobQueue.registerHandler(St,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(St),this.handlerRegistered=!1}namespace(e){return{register:(t)=>this.register(e,t)}}register(e,t){Rp(e),po(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=Fr.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(j.isSuccess(s))return!0;if(t.aborted)throw t.reason;throw oe.squash(s.cause)}getRegisteredCheckIds(){return[...this.checks.keys()]}trackCatchUp(e){let t=this.enqueueCatchUpIfNeeded(e);e.catchUpTasks.add(t);let r=()=>{e.catchUpTasks.delete(t)};return t.then(r,r),t}releaseRegisteredCheck(e,t){if(e.releasePromise)return e.releasePromise;let r=e.definition.id;if(this.checks.get(r)===e)this.checks.delete(r);let i=this.releaseRegisteredCheckOnce(e,t);return e.releasePromise=i,i}async releaseRegisteredCheckOnce(e,t){try{await this.settleRegisteredCheck(e,t)}finally{let r=this.pluginChecks.get(e.pluginId);if(r?.delete(e),r?.size===0)this.pluginChecks.delete(e.pluginId)}}async settleRegisteredCheck(e,t){let r=[];if(e.scheduledJob){let i=e.scheduledJob;delete e.scheduledJob;try{r.push(i.stop())}catch(n){r.push(Promise.reject(n))}}if(e.activeCheck)e.activeCheck.controller.abort(t),r.push(e.activeCheck.settled);r.push(...e.catchUpTasks),r.push(this.cancelEnqueueRetry(e)),await this.drainCleanupTasks(r)}async drainCleanupTasks(e){let t=await Promise.allSettled(e),r=[];for(let i of t)if(i.status==="rejected")r.push(i.reason);if(r.length===1)throw r[0];if(r.length>1)throw AggregateError(r,"Recurring check cleanup failed")}schedule(e){let t=e.definition,r=Rt(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=Rt(this.brainId,r.id,r.cadence),n=Nr(this.currentTime(),i).getTime()+i.periodMs,o=new AbortController,s={controller:o,settled:Promise.resolve()};e.enqueueRetry=s,s.settled=ao(()=>this.enqueue(r.id),t,{firstDelayMs:co,maxDelayMs:lo,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=Rt(this.brainId,t.id,t.cadence),n=Nr(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:St,data:{checkId:e},options:t})}async listOpenAlerts(){return(await this.state.list({keyPrefix:"alert:"})).flatMap((t)=>{let r=t.value;if(r.kind!=="alert"||r.status==="resolved")return[];if(!(r.includeInInbox??this.checks.get(r.checkId)?.definition.includeInInbox!==!1))return[];return[{id:t.key,checkId:r.checkId,title:r.alert.title,body:r.alert.body,observedAt:r.observedAt}]}).sort((t,r)=>t.observedAt.localeCompare(r.observedAt)||t.id.localeCompare(r.id))}async resolveOpenAlert(e){await this.alertOperations.run(e,async()=>{let t=await this.state.get(e),r=t?.kind==="alert"&&(t.includeInInbox??this.checks.get(t.checkId)?.definition.includeInInbox!==!1);if(t?.kind!=="alert"||t.status==="resolved"||!r)throw Error("Recurring-check inbox item is not open");await this.state.set(e,{...t,status:"resolved",resolvedAt:this.currentTime().toISOString()})})}async flushPendingAlerts(e){let t=await this.state.list({keyPrefix:this.alertKeyPrefix(e)});for(let r of t)await this.alertOperations.run(r.key,async()=>{let i=await this.state.get(r.key);if(i?.kind==="alert"&&(i.status==="pending"||i.status==="suppressed"))await this.deliverStoredAlert(r.key,i)})}async suppressPendingAlerts(e){let t=await this.state.list({keyPrefix:this.alertKeyPrefix(e)});for(let r of t)await this.alertOperations.run(r.key,async()=>{let i=await this.state.get(r.key);if(i?.kind==="alert"&&i.status==="pending")await this.state.set(r.key,{...i,status:"suppressed"})})}async recordAlert(e,t,r){let i=He.parse(t),n=this.alertKey(e,i.dedupeKey);await this.alertOperations.run(n,async()=>{let o=await this.state.get(n);if(o?.kind==="alert"){let a=o.includeInInbox===r.includeInInbox?o:{...o,includeInInbox:r.includeInInbox};if(a!==o)await this.state.set(n,a);if(a.status==="delivered"||a.status==="resolved")return;if(r.deliver)await this.deliverStoredAlert(n,a);return}let s={kind:"alert",checkId:e,dedupeKey:i.dedupeKey,status:r.deliver?"pending":"suppressed",alert:i,observedAt:this.currentTime().toISOString(),includeInInbox:r.includeInInbox};if(await this.state.set(n,s),r.deliver)await this.deliverStoredAlert(n,s)})}async deliverStoredAlert(e,t){if(await this.delivery.deliver(t.alert,{idempotencyKey:bp(e,t.observedAt)})===!1)return;await this.state.set(e,{...t,status:"delivered",deliveredAt:this.currentTime().toISOString()})}currentTime(){return this.clock?new Date(this.clock.currentTimeMillisUnsafe()):new Date}lastSuccessKey(e){return`run:${G(e)}`}alertKeyPrefix(e){return`alert:${G(e)}:`}alertKey(e,t){return`${this.alertKeyPrefix(e)}${G(t)}`}}function bp(e,t){return`recurring-alert:${G(`${e}\x00${t}`)}`}function Rt(e,t,r){let i=r==="daily"?Hr:fp,n=i/60000,o=G(`${e}\x00${t}\x00${r}`),s=Number.parseInt(o.slice(0,12),16)%n,a=s%60,l=Math.floor(s/60),d=l%24;return{expression:r==="daily"?`${a} ${d} * * *`:`${a} ${d} * * ${Math.floor(l/24)}`,offsetMs:s*60000,periodMs:i,anchorMs:r==="daily"?0:hp}}function Nr(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 Sp=/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*:[a-z][a-z0-9-]*$/;function Rp(e){if(e.length<=200&&Sp.test(e))return;po(e,"plugin ID")}function po(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=mo("runtime_state_records",{namespace:It("namespace").notNull(),key:It("key").notNull(),value:It("value",{mode:"json"}).notNull(),createdAt:Wr("created_at").notNull(),updatedAt:Wr("updated_at").notNull()},(e)=>({pk:fo({columns:[e.namespace,e.key]}),namespaceUpdatedAtIdx:go("idx_runtime_state_namespace_updated_at").on(e.namespace,e.updatedAt)}));function yo(e){return ho({url:e.url,schema:{runtimeStateRecords:I},authToken:e.authToken,authTokenEnv:"RUNTIME_STATE_DATABASE_AUTH_TOKEN"})}function Pt(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 wp}from"util";var Ip=/^[a-zA-Z0-9][a-zA-Z0-9_.:-]{0,511}$/,wo=512;class qr{db;namespace;schema;now;constructor(e,t,r,i=()=>new Date){Pp(t),this.db=e,this.namespace=t,this.schema=r,this.now=i}async get(e){let t=he(e),i=(await this.db.select().from(I).where(se(z(I.namespace,this.namespace),z(I.key,t))).limit(1))[0];if(!i)return null;return this.schema.parse(i.value)}async has(e){let t=he(e);return(await this.db.select({key:I.key}).from(I).where(se(z(I.namespace,this.namespace),z(I.key,t))).limit(1)).length>0}async set(e,t){let r=he(e),i=Pt(this.schema,t),n=i===null?ye`'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=he(e),i=Pt(this.schema,t),n=i===null?ye`'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=he(e),n=Pt(this.schema,r),[o]=await this.db.select({value:I.value}).from(I).where(se(z(I.namespace,this.namespace),z(I.key,i))).limit(1);if(!o||!wp(this.schema.parse(o.value),t))return!1;let s=o.value===null?ye`'null'`:o.value,a=n===null?ye`'null'`:n,l=await this.db.update(I).set({value:a,updatedAt:this.now().getTime()}).where(se(z(I.namespace,this.namespace),z(I.key,i),z(I.value,s)));return Number(l.rowsAffected)===1}async delete(e){let t=he(e),r=await this.db.delete(I).where(se(z(I.namespace,this.namespace),z(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(se(z(I.namespace,this.namespace),vo(e.keyPrefix)));return Number(t.rowsAffected)}async listRows(e){let{keyPrefix:t,afterKey:r,limit:i}=e;if(r!==void 0)he(r);if(i!==void 0)c.number().int().min(1).max(1000).parse(i);let n=this.db.select({...bo(I),key:ye`CAST(${I.key} AS BLOB)`.mapWith((o)=>new TextDecoder("utf-8",{fatal:!0}).decode(o))}).from(I).where(se(z(I.namespace,this.namespace),vo(t),r!==void 0?So(I.key,r):void 0)).orderBy(Ro(I.key)).$dynamic();return i===void 0?n:n.limit(i)}}function Pp(e){if(!Ip.test(e))throw Error(`Invalid runtime state namespace: ${e}. Use 1-512 alphanumeric, _, ., :, or - characters.`)}function he(e){if(e.length===0||e.length>wo)throw Error("Runtime state keys must be 1-512 characters long");return e}function vo(e){if(e===void 0)return;return xp(e),ye`substr(CAST(${I.key} AS BLOB), 1, length(CAST(${e} AS BLOB))) = CAST(${e} AS BLOB)`}function xp(e){if(e.length>wo)throw Error("Runtime state key prefixes must be 512 characters or shorter");return e}class xt{db;client;logger;databaseUrl;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;static createFresh(e,t){return new xt(e,t??Pe.getInstance())}constructor(e,t){let{db:r,client:i,url:n}=yo(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 Io(this.client,this.databaseUrl)}catch(e){this.logger.warn("Failed to enable runtime state WAL mode (non-fatal)",e)}finally{if(this.walInitializationSettled=!0,this.closeRequested)this.closeClient()}}scoped(e){let t=new qr(this.db,e.namespace,e.schema);return Object.freeze({get:t.get.bind(t),has:t.has.bind(t),set:t.set.bind(t),setIfNotExists:t.setIfNotExists.bind(t),compareAndSet:t.compareAndSet.bind(t),delete:t.delete.bind(t),list:t.list.bind(t),clear:t.clear.bind(t)})}close(){if(this.closeRequested=!0,!this.walInitialization||this.walInitializationSettled)this.closeClient()}closeClient(){if(this.clientClosed)return;this.clientClosed=!0,this.client.close()}}var Jr=C.Service("@brains/runtime-state/RuntimeStateService");function Po(e){return ne(Jr,()=>{let t=e.service??xt.createFresh(e.config,e.logger);return{service:t,close:()=>t.close()}})}async function Gr(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=We(r),t.warn(`Daemon ${e.name} failed to start: ${x(r)}`),r}}async function Qr(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=We(r),t.error(`Failed to stop daemon: ${e.name}`,r),r}}async function xo(e){if(!e.daemon.healthCheck)return;try{let t=await e.daemon.healthCheck();return e.health=t,t}catch(t){let r={status:"error",message:x(t),lastCheck:new Date};return e.health=r,r}}function Co(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 Gr(t,this.logger);return}let r=b.runSync(D.make()),i=b.acquireRelease(b.promise(()=>Gr(t,this.logger)),()=>b.promise(()=>Qr(t,this.logger)));try{await b.runPromise(D.provide(i,r)),this.daemonScopes.set(e,r)}catch(n){throw await b.runPromise(D.close(r,j.fail(n))),n}}stop(e){if(!this.daemons.has(e))return Promise.reject(Error(`Daemon not registered: ${e}`));return this.enqueueTransition(e,"stop",()=>this.stopDaemon(e))}async stopDaemon(e){let t=this.requireDaemon(e),r=this.daemonScopes.get(e);if(!r){await Qr(t,this.logger);return}this.daemonScopes.delete(e),await b.runPromise(D.close(r,j.void))}async checkHealth(e){let t=this.daemons.get(e);if(!t)throw Error(`Daemon not registered: ${e}`);return xo(t)}getByPlugin(e){return Array.from(this.daemons.values()).filter((t)=>t.pluginId===e)}getAll(){return Array.from(this.daemons.keys())}getAllInfo(){return Array.from(this.daemons.values())}async getStatuses(){let e=this.getAllInfo();for(let t of e)if(t.daemon.healthCheck)await this.checkHealth(t.name);return e.map(Co)}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??=We(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 Cp=c.object({projectionId:c.string().min(1),reason:c.string().min(1),openedAt:c.number().int().nonnegative(),expiresAt:c.number().int().nonnegative()}),Tp=8,Ep=32,Ap=128,kp=5,jp=600000,Dp=600000,Op=1000,zp="shell.projection-circuits";class Tt{operationContext;options;circuitStore;roots=new Map;reservedJobs=new Map;circuits=new Map;projections;static createFresh(e,t={}){return new Tt(e,t)}constructor(e,t){this.operationContext=e,this.options={maxDerivationDepth:t.maxDerivationDepth??Tp,maxJobsPerRoot:t.maxJobsPerRoot??Ep,maxMutationsPerRoot:t.maxMutationsPerRoot??Ap,repeatedTargetLimit:t.repeatedTargetLimit??kp,retentionMs:t.retentionMs??jp,circuitOpenMs:t.circuitOpenMs??Dp,maxTrackedRoots:t.maxTrackedRoots??Op,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:zp,schema:Cp})}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 Mp={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 xe(e){return Mp[e??"combined"]}var To=[Et.created,Et.updated,Et.deleted];function Eo(e,t,r){let i=To.map((o)=>e.subscribe(o,(s)=>(t.send({type:o,payload:s.payload}),{success:!0}))),n=t.onEvent((o)=>{if(!To.includes(o.type))return;e.deliverPeer(o.type,o.payload).catch((s)=>{r.warn(`Failed to deliver peer event ${o.type}`,{error:s})})});return()=>{for(let o of i)o();n()}}var Lp=20,Up=0.5,Bp=0.06,$p=5;function ko(e){return async({answer:t})=>{let i=(await e.entityService.search({query:t,options:{limit:Lp,minScore:Up,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-Bp).slice(0,$p).map(({entity:o})=>Ao(o,e))}}function _p(e,t,r,i,n){return[zo,Mo,Lo].map((o)=>e.observe(o.name,async(s)=>{let a=o.schema.safeParse(s.payload);if(a.success&&a.data.entityType===t&&(r===null||a.data.entityId===r)){await i();let l=o.name.replace("entity:","");n.debug(`${t} entity ${l}, cache refreshed`)}return{success:!0}}))}function jo(e,t,r,i){return _p(e,t,t,async()=>{await r(),await Te(e,Uo,{entityType:t},"shell")},i)}async function Zp(e,t,r){let i=Fp(e.kind);if(!i)return null;try{let n=t.scoped({namespace:i,refKind:e.kind,routePath:""}),{record:o,content:s}=await n.read(e.id);return No({...o,content:s,source:e})}catch(n){return r.debug("Skipped unavailable prior runtime upload",{uploadKind:e.kind,uploadId:e.id,error:x(n)}),null}}function Fp(e){return e===Ce.refKind?Ce.namespace:null}function Jo(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=Ho.createFresh(r,i,t.identity);d.push(...jo(n,M.BRAIN_CHARACTER,()=>p.refreshCache(),i));let m=Wo.createFresh(r,i,t.profile),g=qo.createFresh(i,async(R)=>{let w=await bt(n,"shell:canonical-identity-service",R).catch(()=>null);if(!w?.canonicalId)return null;return{userId:w.userId,canonicalId:w.canonicalId,displayName:w.displayName}}),f=Fo({guestPricing:Bo(o.getConfig().model),model:o.getModel(),answerModel:o.getAnswerModel?.(),modelId:o.getConfig().model,webSearch:o.getConfig().webSearch,temperature:o.getConfig().temperature,reasoningEffort:o.getConfig().reasoningEffort,messageBus:n}),h=$o(t.name),v=new ht(t.entityDisplay),y={isCitable:(R)=>v.isCitable(R),urlFor:(R,w)=>v.generateUrl(R,w),siteBaseUrl:t.siteBaseUrl},S=_o.createFresh(s,a,p,m,i,{agentFactory:f,turnEvents:Zo(n),canonicalIdentityResolver:g,entityLinks:y,...e.generationUsage?{generationUsage:e.generationUsage}:{},...e.embeddingUsage?{embeddingUsage:e.embeddingUsage}:{},...t.embedding.enabled?{indexReadiness:r,guestAnswerSources:ko({entityService:r,...y})}:{},uploadAttachmentResolver:(R)=>Zp(R,l,i),guestAskedBefore:async(R)=>{let w=await qe(n,Do,R,"shell:agent-service");return w.status==="answered"?w.answers.find((P)=>P.hit)?.hit:void 0},agentContextProvider:async(R)=>{let w=await qe(n,Oo,R,"shell:agent-service");return w.status==="answered"?w.answers.flatMap((P)=>P.items):[]},...h?{assistantAgentId:h}:{},...t.agentInstructions&&{agentInstructions:t.agentInstructions}});if(d.push(...jo(n,M.ANCHOR_PROFILE,()=>m.refreshCache(),i)),!u)d.push(n.subscribe(Je.identityChanged,async()=>(S.invalidateAgent(),{success:!0})));return{identityService:p,profileService:m,canonicalIdentityService:g,agentService:S}}var Ge=C.Service("@brains/job-queue/JobQueueService"),At=C.Service("@brains/job-queue/BatchJobManager"),kt=C.Service("@brains/job-queue/JobProgressMonitor"),jt=C.Service("@brains/job-queue/JobQueueWorker");function Yo(e){return ne(Ge,()=>{let t=e.service??Go.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 Xo(e){let t=!1,r=b.gen(function*(){let i=yield*Ge,n=e.batchJobManager??Ko.createFresh(i,e.logger),o=e.jobProgressMonitor??Vo.createFresh(i,e.messageBus,n,e.logger,e.progressMonitorMode),s=e.jobQueueWorker??Qo.createFresh(i,o,e.logger,{pollInterval:100,concurrency:e.workerConcurrency,autoStart:!1,...e.onWorkerUnhealthy&&{onUnhealthy:e.onWorkerUnhealthy}},{...e.operationContext&&{operationContext:e.operationContext},...e.projectionBatchScope&&{projectionBatchScope:e.projectionBatchScope}});return C.make(At,n).pipe(C.add(kt,o),C.add(jt,s))});return{layer:Q.effectContext(b.acquireRelease(r,(i)=>t?b.void:Np(i))),abandon:()=>{t=!0}}}function Np(e){let t=C.get(e,jt),r=C.get(e,kt),i=C.get(e,At);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(j.isFailure);if(a)yield*b.die(oe.squash(a.cause))})}function Hp(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(D.close(e,j.void));if(j.isFailure(t))throw oe.squash(t.cause)}function es(e){let t=e.operationContext??Ot.createFresh(),r=b.runSync(D.make()),i,n;try{let o=b.runSync(Q.buildWithScope(Yo({config:e.jobQueueConfig,logger:e.logger,operationContext:t,...e.projectionAdmission&&{projectionAdmission:e.projectionAdmission},...e.handlerRegistrationMode&&{handlerRegistrationMode:e.handlerRegistrationMode},...e.dependencies?.jobQueueService&&{service:e.dependencies.jobQueueService}}),r)),s=C.get(o,Ge),a=b.runSync(D.make());i=a;let l=Xo({messageBus:e.messageBus,logger:e.logger,operationContext:t,...e.projectionBatchScope&&{projectionBatchScope:e.projectionBatchScope},onWorkerUnhealthy:Hp(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(Q.buildWithScope(l.layer.pipe(Q.provide(Q.succeed(Ge,s))),a)),u=C.get(d,At),p=C.get(d,kt),m=C.get(d,jt),g,f=!1,h=!1;return{batchJobManager:u,jobProgressMonitor:p,jobQueueService:s,jobQueueWorker:m,closeRuntime:()=>(f=!0,g??=b.runPromise(D.close(a,j.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 rs(e){return{deliver:async(t,{idempotencyKey:r})=>{let i=await vt(e,ts,{title:t.title,body:t.body,...t.html?{html:t.html}:{},...t.sensitivity?{sensitivity:t.sensitivity}:{},idempotencyKey:r},"shell.recurring-checks");if(i.status==="unavailable")return!1;if(i.status==="failed"||i.data.status!=="sent")throw Error("Recurring alert delivery failed");return!0}}}function ns(e){return{sourceId:"recurring-checks",displayName:"Recurring checks",list:async()=>(await e.listOpenAlerts()).map((t)=>({id:t.id,title:is(t.title,160),summary:is(t.body,1000),receivedAt:t.observedAt,urgency:"high",actions:[{id:"resolve",label:"Dismiss",confirm:!0}]})),act:async(t,r)=>{if(r!=="resolve")throw Error("Invalid recurring-check inbox action");await e.resolveOpenAlert(t)}}}function is(e,t){return e.length<=t?e:e.slice(0,t)}function os(e,t){if(t)return t;let r={debug:Qe.DEBUG,info:Qe.INFO,warn:Qe.WARN,error:Qe.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 Os(e){let{config:t,dependencies:r,initializerLogger:i,lifecycle:n,processRole:o,peerChannel:s}=e;i.debug("Initializing Shell services");let a=xe(o),l=os(t,r?.logger),d=r?.operationContext??Ot.createFresh(),u=[],p=Cs.createFresh(!r?.embeddingService),m=r?.embeddingService??xs.createFresh({providerKeys:t.ai.providerKeys,profile:Is(t.ai.embeddingModel),runtimeUrl:t.ai.modelRuntimeUrl,logger:l,usage:p}),g=Ts.createFresh(),f=r?.aiService??Ps.createFresh(Kr(t),l,g),h=r?.entityRegistry??cs.createFresh(l),v=r?.messageBus??as.createFresh(l,d);if(s)u.push(Eo(v,s,l));let y=r?.templateRegistry??ds.createFresh(l),S=r?.dataSourceRegistry??ls.createFresh(l),R=r?.renderService??ps.createFresh(y),w=r?.daemonRegistry??Ct.createFresh(l),P=r?.pluginManager??ks.createFresh(l,w),E=r?.permissionService??new us(t.permissions,{spaces:t.spaces,entityActionFloor:(q)=>h.getEntityTypeConfig(q).actionPolicy}),L=r?.profileKindRegistry??new As(t.profileKind),Re=r?.channelRegistry??new hs,pe=r?.inboxRegistry??new vs,te=r?.inboxFollowUpRegistry??new bs(l),ru=r?.operationalHealthRegistry??new Es,iu=r?.accountSettingsRegistry??new fs,nu=new ys,ou=new yt,su=r?.attachmentRegistry??Ss.createFresh(),pn=r?.runtimeUploadRegistry??Rs.createFresh({dataDir:t.dataDir,logger:l}),au=n.buildLayer(Po({config:Ee(t.runtimeStateDatabase),logger:l,...r?.runtimeStateService&&{service:r.runtimeStateService}})),Ir=C.get(au,Jr),Pr=r?.projectionRuntimeSupervisor??Tt.createFresh(d,{runtimeState:Ir}),mn=r?.mcpService??ws.createFresh(v,l),xr={},cu={runFreshBatchScope:(q)=>xr.current?xr.current.runFreshBatchScope(q):q()},ct=es({dependencies:r,jobQueueConfig:{...Ee(t.jobQueueDatabase),brainVersion:t.version},workerConcurrency:t.jobQueue.workerConcurrency,messageBus:v,operationContext:d,projectionBatchScope:cu,projectionAdmission:Pr,handlerRegistrationMode:a.handlerRegistrationMode,progressMonitorMode:a.progressMonitorMode,logger:l}),{batchJobManager:lu,jobProgressMonitor:du,jobQueueService:Cr,jobQueueWorker:uu}=ct;n.addSyncFinalizer(()=>ct.closeDatabase()),n.addSyncFinalizer(()=>ct.rollbackRuntime());let $e=r?.recurringCheckService??new wt({brainId:t.siteBaseUrl??t.dataDir,scheduler:new js,runtimeState:Ir,clock:b.runSync(ss.Clock),jobQueue:Cr,logger:l,delivery:rs(v)});n.addSyncFinalizer(()=>$e.abandon()),pe.registerSource("shell.recurring-checks",ns($e)),n.addSyncFinalizer(()=>pe.unregisterPlugin("shell.recurring-checks"));let gn=(q,Er)=>{if(!a.serves)return;w.register(q,Er,"shell"),n.addSyncFinalizer(()=>w.abandon(q))};gn("shell:recurring-checks",{start:()=>$e.start(),stop:()=>$e.stop()});let pu=n.buildLayer(so({embeddingService:m,embeddingsEnabled:t.embedding.enabled,entityRegistry:h,logger:l,jobQueueService:Cr,messageBus:v,mutationAdmission:Pr,...r?.projectionRuntime?.now&&{projectionNow:r.projectionRuntime.now},dbConfig:Ee(t.database),embeddingDbConfig:Ee(t.embeddingDatabase),...r?.entityService&&{service:r.entityService}})),lt=C.get(pu,Zr);xr.current=lt.getProjectionStore();let mu=n.buildLayer(no({dbConfig:Ee(t.conversationDatabase),logger:l,messageBus:v,...r?.conversationService&&{service:r.conversationService}})),Tr=C.get(mu,_r);gn("shell:guest-retention",Ds({intervalMs:60000,logger:l,run:async()=>{await Tr.deleteExpiredGuestConversations(100)}})),n.addSyncFinalizer(()=>{for(let q of u.splice(0))try{q()}catch(Er){l.warn("Failed to dispose shell subscription",Er)}});let fn=ro(E,v),gu=r?.contentService??new gs({logger:l,entityService:lt,aiService:f,templateRegistry:y,dataSourceRegistry:S,generationAuthorizer:new ms(E,fn)}),{identityService:fu,profileService:hu,canonicalIdentityService:yu,agentService:vu}=Jo({config:t,entityService:lt,embeddingService:m,embeddingUsage:p,...!r?.aiService?{generationUsage:g}:{},entityRegistry:h,logger:l,messageBus:v,aiService:f,mcpService:mn,conversationService:Tr,runtimeUploadRegistry:pn,disposables:u,executionOnly:!a.serves});return{logger:l,operationContext:d,projectionRuntimeSupervisor:Pr,disposables:u,entityRegistry:h,messageBus:v,renderService:R,daemonRegistry:w,pluginManager:P,templateRegistry:y,dataSourceRegistry:S,mcpService:mn,embeddingService:m,entityService:lt,aiService:f,conversationService:Tr,contentService:gu,callerAuthorizer:fn,jobQueueService:Cr,jobQueueWorker:uu,batchJobManager:lu,jobProgressMonitor:du,jobServicesLifecycle:ct,permissionService:E,identityService:fu,profileService:hu,canonicalIdentityService:yu,profileKindRegistry:L,channelRegistry:Re,inboxRegistry:pe,inboxFollowUpRegistry:te,operationalHealthRegistry:ru,accountSettingsRegistry:iu,authRegistry:nu,atprotoProjectionRegistry:ou,agentService:vu,attachmentRegistry:su,runtimeUploadRegistry:pn,runtimeStateService:Ir,recurringCheckService:$e}}function $s(e,t){e.register(Vr.name,Vr),t.debug("Shell system templates registered")}function _s(e,t){e.register(Ne.BASE_ENTITY_DISPLAY,{name:"base-entity-display",description:"Display template for base entities",schema:Yr,formatter:new zs,requiredPermission:"public"}),t.debug("Base entity display template registered")}function Zs(e,t){e.registerEntityType(M.NOTE,Yr,new Ms,{projectionSourceRole:"primary"}),t.debug("Fallback base entity adapter registered")}function Fs(e,t){let r=new Ls;e.registerEntityType(M.BRAIN_CHARACTER,r.schema,r,{classification:"system",projectionSource:!1,projectionSourceRole:"excluded"}),t.debug("Brain character entity support registered")}function Ns(e,t){let r=new Us;e.registerEntityType(M.ANCHOR_PROFILE,r.schema,r,{classification:"system",projectionSourceRole:"canonical"}),t.debug("Anchor profile entity support registered")}async function Hs(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 Bs||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){$s(e,this.logger)}registerBaseEntityDisplayTemplate(e){_s(e,this.logger)}registerFallbackBaseEntity(e){Zs(e,this.logger)}registerBrainCharacterSupport(e){Fs(e,this.logger)}registerAnchorProfileSupport(e){Ns(e,this.logger)}async initializePlugins(e,t){await Hs({plugins:this.config.plugins,pluginManager:e,logger:this.logger,initOptions:t})}initializeServices(e,t){return Os({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=qs.createFresh(t,r);e.registerHandler(Ws.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((P)=>P.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 P=await this.store.listPendingInputs();return await this.recordDiagnostic({...p,event:"apply-completed",applyOutcome:"superseded",highestPendingGeneration:Mt(P)}),{waveId:n.waveId,ruleId:o.id,outcome:"superseded",inputFingerprint:null,changedTargets:[]}}if(await this.store.supersedeWaveIfStale(n.waveId,this.now())){let P=await this.store.listPendingInputs();return await this.recordDiagnostic({...p,event:"apply-completed",applyOutcome:"superseded",highestPendingGeneration:Mt(P)}),await this.coordinator.continueAfterSupersession(n.waveId),{waveId:n.waveId,ruleId:o.id,outcome:"superseded",inputFingerprint:null,changedTargets:[]}}let m=Jp(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:qp(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(P){throw await this.recordDiagnostic({...h,event:i.aborted?"derive-cancelled":"derive-failed",memoHit:!1}),P}}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:Mt(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:Mt(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 qp(e,t){if(typeof e==="object"&&e!==null&&"sources"in e&&Array.isArray(e.sources))return e.sources.length;return t.length}function Mt(e){if(e.length===0)return null;return e.reduce((t,r)=>Math.max(t,r.generation),e[0]?.generation??0)}function Jp(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 Gp(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 Js;scheduledWakeup;constructor(e){this.store=e.store,this.queue=e.queue,this.graph=e.graph,this.ruleById=Vp(e.graph,e.rules),this.graphFingerprint=Yp(e.graph,e.rules),this.createWaveId=e.createWaveId,this.beforeWaveCompletion=e.beforeWaveCompletion??(async()=>{}),this.scheduleWakeup=e.scheduleWakeup??Qp,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=Kp(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=Qs(this.graph,this.ruleById,s);if(a.length===0)return this.completeWave(e);await this.store.putWaveRules(e.id,a),t=await this.store.listWaveRules(e.id)}if(t.every((s)=>s.status==="completed"))return this.completeWave(e,t);let r=t.find((s)=>s.status==="failed");if(r)return this.store.failWaveWithIncident({waveId:e.id,ruleId:r.ruleId,jobId:r.jobId,failureReason:"Projection rule is in a terminal failed state",failedAt:this.now()});let i=await this.findStrandedQueuedRule(t);if(i)return this.store.failWaveWithIncident({waveId:e.id,ruleId:i.rule.ruleId,jobId:i.rule.jobId,failureReason:Gp(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 Qp(e,t){let r=setTimeout(()=>{t()},e);return()=>clearTimeout(r)}function Kp(e,t,r){let n=Qs(e,t,r).reduce((s,a)=>Math.max(s,t.get(a.ruleId)?.sourceChangeBatchDelayMs??0),0);if(n===0)return 0;return r.reduce((s,a)=>Math.max(s,a.markedAt),0)+n}function Vp(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 Yp(e,t){return Gs({projections:e.projections,edges:e.edges,rules:[...t].sort((r,i)=>r.id.localeCompare(i.id)).map((r)=>({id:r.id,version:r.version}))})}function Qs(e,t,r){let i=new Map(e.projections.map((l)=>[l.id,l])),n=Ks(e,(l)=>[l.from,l.to]),o=new Set(e.projections.filter((l)=>Xp(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=em(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 Xp(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 em(e,t){let r=Ks(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 Ks(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 Vs(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??tm)(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 tm(e,t){let r=setInterval(()=>{t()},e);return r.unref(),()=>clearInterval(r)}import{existsSync as Wm}from"fs";import{mkdir as qm,writeFile as Jm}from"fs/promises";import{join as Gm,resolve as qa}from"path";var Ys=5000;async function Xs(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 ea(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 N,join as Zm,sep as Fm}from"path";var ta=Symbol();var ra=(e,t)=>new Response(e,{headers:{"Content-Type":t.replace(/^[^;]+/,(r)=>r.toLowerCase())}}).formData();var rm=1e4,Lt=(e)=>("headers"in e),oa=async(e,t=Object.create(null))=>{let{all:r=!1,dot:i=!1}=t,n=(Lt(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 im(e,{all:r,dot:i});return{}};async function im(e,t){if(!Lt(e)&&e.bodyCache.formData)return ia(await e.bodyCache.formData,t);let r=Lt(e)?e.headers:e.raw.headers,i=await e.arrayBuffer(),n=ra(i,r.get("Content-Type")||"");if(!Lt(e))e.bodyCache.formData=n;let o=await n;if(o)return ia(o,t);return{}}function ia(e,t){let r=Object.create(null),i={count:0};if(e.forEach((n,o)=>{if(!(t.all||o.endsWith("[]")))r[o]=n;else nm(r,o,n)}),t.dot)Object.entries(r).forEach(([n,o])=>{if(n.includes("."))om(r,n,o,i),delete r[n]});return r}var nm=(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]},om=(e,t,r,i)=>{if(/(?:^|\.)__proto__\./.test(t))return;let n=e,o=t.split(".",34);if(o.length>33)na();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++>=rm)na();n[s]=Object.create(null)}n=n[s]}})},na=()=>{throw Error("Nesting limit exceeded")};var ni=(e)=>{let t=e.split("/");if(t[0]==="")t.shift();return t},sa=(e)=>{let{groups:t,path:r}=sm(e),i=ni(r);return am(i,t)},sm=(e)=>{let t=[];return e=e.replace(/\{[^}]+\}/g,(r,i)=>{let n=`@${i}`;return t.push([n,r]),n}),{groups:t,path:e}},am=(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},Ut={},aa=(e,t)=>{if(e==="*")return"*";let r=e.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/);if(r){let i=`${e}#${t}`;if(!Ut[i])if(r[2])Ut[i]=t&&t[0]!==":"&&t[0]!=="*"?[i,r[1],new RegExp(`^${r[2]}(?=/${t})`)]:[e,r[1],new RegExp(`^${r[2]}$`)];else Ut[i]=[e,r[1],!0];return Ut[i]}return null},ca=(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)=>ca(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 la=(e)=>{let t=si(e);return t.length>1&&t.at(-1)==="/"?t.slice(0,-1):t},ae=(e,t,...r)=>{if(r.length)t=ae(t,...r);return`${e?.[0]==="/"?"":"/"}${e}${t==="/"?"":`${e?.at(-1)==="/"?"":"/"}${t?.[0]==="/"?t.slice(1):t}`}`},Bt=(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)},$t=(e)=>e.indexOf("%")!==-1?ca(e,cm):e,ii=(e)=>{if(e.indexOf("+")!==-1)e=e.replace(/\+/g," ");return $t(e)},da=(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},ua=da,pa=(e,t)=>da(e,t,!0),cm=decodeURIComponent;var ma=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&&$t(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]=$t(i)}return e}#i(e){return this.#e[1]?this.#e[1][e]:e}query(e){return ua(this.url,e)}queries(e){return pa(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 oa(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[ta](){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 ga={Stringify:1,BeforeStream:2,Stream:3},fa=(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 fa(await s,o);else return s};var lm="text/plain; charset=UTF-8",ci=(e,t)=>({"Content-Type":e,...t}),Ke=(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 ma(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||=Ke(null,{headers:this.#a??=new Headers})}set res(e){if(this.#n&&e){e=Ke(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=Ke(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 Ke(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(lm,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,ga.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??=()=>Ke(),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 ha=["get","post","put","delete","options","patch","query"],_t="Can not add a route since the matcher is already built.",Zt=class extends Error{};var ui="__COMPOSED_HANDLER";var dm=(e)=>e.text("404 Not Found",404),ya=(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)},va=class e{get;post;put;delete;options;patch;query;all;on;use;router;getPath;_basePath="/";#t="/";routes=[];constructor(t={}){[...ha,"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:la}#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=dm;errorHandler=ya;route(t,r){let i=this.basePath(t);return r.routes.map((n)=>{let o;if(r.errorHandler===ya)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=ae(this._basePath,t),r}onError=(t)=>(this.errorHandler=t,this);notFound=(t)=>(this.#r=t,this);mount(t,r,i){let n,o;if(i)if(typeof i==="function")o=i;else if(o=i.optionHandler,i.replaceRequest===!1)n=(l)=>l;else n=i.replaceRequest;let s=o?(l)=>{let d=o(l);return Array.isArray(d)?d:[d]}:(l)=>{let d=void 0;try{d=l.executionCtx}catch{}return[l.env,d]};n||=(()=>{let l=ae(this._basePath,t),d=l==="/"?0:l.length;return(u)=>{let p=new URL(u.url);return p.pathname=this.getPath(u).slice(d)||"/",new Request(p,u)}})();let a=async(l,d)=>{let u=await r(n(l.req.raw),...s(l));if(u)return u;await d()};return this.#o("ALL",ae(t,"*"),a),this}#o(t,r,i,n){r=ae(this._basePath,r);let o={basePath:n!==void 0?ae(this._basePath,n):this._basePath,path:r,method:t,handler:i};this.router.add(t,r,[i,o]),this.routes.push(o)}#i(t,r){if(t instanceof Error)return this.errorHandler(t,r);throw t}#n(t,r,i,n){if(n==="HEAD")return(async()=>new Response(null,await this.#n(t,r,i,"GET")))();let o=this.getPath(t,{env:i}),s=this.router.match(n,o),a=new 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${ae("/",t)}`,r),i,n)};fire=()=>{addEventListener("fetch",(t)=>{t.respondWith(this.#n(t.request,t,void 0,t.request.method))})}};var k=()=>Object.create(null);var Ft=[];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[[],Ft];let d=l.indexOf("",1);return[s[1][d],l]};return this.match=i,i(e,t)}var mi="[^/]+";var gi="(?:|/.*)",ce=Symbol(),ba=new Set(".\\+*[^]$()");function um(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 Sa=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 ce;if(g=g.replace(/^\((?!\?:)(?=[^)]+\)$)/,"(?:"),/\((?!\?:)/.test(g))throw ce;if(g.length===1&&ba.has(g))throw ce}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 ce}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 ce;p=s.#r[d]=new e}s=p}if(s.#t!==void 0)throw ce;s.#t=o?-1:r}buildRegExpStr(){let t=Object.keys(this.#r).sort(um).map((r)=>{let i=this.#r[r],n=i.buildRegExpStr();return n===""?"":(typeof i.#e==="number"?`(${r})@${i.#e}`:ba.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 Sa;#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 Ra=k();function wa(e){return Ra[e]??=new RegExp(`^${e.replace(/\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,(t,r)=>r?`\\${r}`:t==="/*"?gi:t==="*"?".*":`/:${mi}`)}$`)}function Nt(e,t){for(let r of Object.keys(e).sort((i,n)=>n.length-i.length))if(wa(r).test(t))return[...e[r]]}var Ht=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===ce?new Zt(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=wa(t);for(let l of o)if(!i[l][t])this.#o(l,t),i[l][t]=Nt(i[l],t)||Nt(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=Bt(t)||[t];for(let a of s)for(let l of o){if(!n[l][a])this.#o(l,a),n[l][a]=Nt(i[l],a)||Nt(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,Ra=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()]),Ft];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 Ia=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 Zt)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(),pm=0,Pa=class e{#t=[];#e=k();#r=[];#o;#i=hi;insert(t,r,i){let n=this,o=sa(r),s=new Set,a=0;for(let l of o){let d=o[++a],u=aa(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:++pm}})}#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[,P,E]=R;if(!u&&E===!0)continue;if(E!==!0){if(!l){l=[];let pe=r[0]==="/"?1:0;for(let te=0;te<a;te++)l[te]=pe,pe+=o[te].length+1}let L=r.slice(l[d]),Re=E.exec(L);if(Re){if(w[P]=Re[0],this.#n(i,S,t,v.#i,w),Re[0].length===L.length&&S.#e["*"])this.#n(i,S.#e["*"],t,v.#i,w);for(let pe in S.#e){S.#i=w;let te=Re[0].match(/\//g)?.length??0;(s[te]||=[]).push(S);break}continue}}if(E===!0||E.test(u))if(w[P]=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 Pa;add(e,t,r){for(let i of Bt(t)||[t])this.#t.insert(e,i,r)}match(e,t){return this.#t.search(e,t)}};var vi=class extends va{constructor(e={}){super(e);this.router=e.router??new Ia({routers:[new Ht,new yi]})}};var Wt=(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=mm)=>{let r=e.match(/\.([a-zA-Z0-9]+?)$/);if(!r)return;return t[r[1].toLowerCase()]};var mm={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 xa=(...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 Ca={br:".br",zstd:".zst",gzip:".gz"},gm=Object.keys(Ca),fm="index.html",Ta=(e)=>{let t=e.root??"./",r=e.path,i=e.join??xa;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,fm);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 gm){if(!p.has(m))continue;let g=await l(a+Ca[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 hm}from"fs/promises";import{join as ym}from"path";var Si=(e={})=>async function(r,i){return Ta({...e,getContent:async(s)=>{let a=Bun.file(s);return await a.exists()?a:null},join:ym,isDir:async(s)=>{let a;try{a=(await hm(s)).isDirectory()}catch{}return a}})(r,i)};var Ea="x-hono-disable-ssg",Fw=(()=>{try{return new Response("SSG is disabled",{status:404,headers:{[Ea]:"true"}})}catch{return null}})();var{write:jI}=Bun;var Aa=(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 Rm=Aa((e,t)=>{let r=Wt(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 ja=(e)=>e===32||e===9||e===10||e===13,qt=(e,t)=>{while(t<e.length){if(!ja(e.charCodeAt(t)))break;t++}return t},Ve=(e,t)=>{while(t>0){if(!ja(e.charCodeAt(t-1)))break;t--}return t},ka=(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]},wm=(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},Im=(e,t)=>{t=qt(e,t);let r=t,i,n,o=!1;while(r<e.length){let l=e.charCodeAt(r);if(l===61){i=e.slice(t,Ve(e,r)),r++;break}if(l===59)return[r+1,void 0,void 0,!0];if(l===44)return[r+1,void 0,void 0,!1];r++}if(i===void 0)return[r,void 0,void 0,!1];if(r=qt(e,r),e.charCodeAt(r)===61){let l=ka(e,r+1);return[l[0],i,void 0,l[1]]}let s=!1,a=r;while(r<e.length){let l=e.charCodeAt(r);if(s&&l===92)r++;else if(l===34){if(s){let d=qt(e,r+1),u=e.charCodeAt(d);if(d<e.length&&!(u===59||u===44)){let p=ka(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,Ve(e,r)),l===59)o=!0;r++;break}r++}return[r,i,n??e.slice(a,Ve(e,r)),o]},Pm=(e,t)=>{let r={type:"",params:Object.create(null),q:1};t=qt(e,t);let i=t;while(i<e.length){let a=e.charCodeAt(i);if(a===59||a===44){if(r.type=e.slice(t,Ve(e,i)),i++,a===44)return[i,r.type?r:void 0];if(!r.type)return[wm(e,i),void 0];break}i++}if(!r.type)return r.type=e.slice(t,Ve(e,e.length)),[e.length,r.type?r:void 0];let n,o,s;while(i<e.length){if([i,n,o,s]=Im(e,i),n&&o)r.params[n]=o;if(!s)break}return[i,r]},Da=(e)=>{if(!e)return[];let t=[],r=0,i,n=!1,o;while(r<e.length)if([r,i]=Pm(e,r),i){if(i.q=xm(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},xm=(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 Cm=["gzip","deflate"],Tm=/(?:^|,)\s*?no-transform\s*?(?:,|$)/i,Em=(e,t)=>{if(e===void 0)return;let r=Da(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},Am=/(?:^|,)\s*accept-encoding\s*(?:,|$)/i,Oa=(e)=>{let t=e?.threshold??1024,r=e?.encoding?[e.encoding]:Cm,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)||!km(s.res))return;let d=s.res.headers.get("Vary");if(d!=="*"&&!(d&&Am.test(d)))s.header("Vary",d?`${d}, Accept-Encoding`:"Accept-Encoding");let u=s.req.header("Accept-Encoding"),p=Em(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}`)}},km=(e)=>{let t=e.headers.get("Cache-Control");return!t||!Tm.test(t)};import{Readable as za}from"stream";import{createDeflate as jm,createGzip as Dm}from"zlib";var Om=["gzip","deflate"],zm=/(?:^|,)\s*?no-transform\s*?(?:,|$)/i,Ma=(e)=>{if(typeof CompressionStream<"u")return Oa(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||!Mm(i.res)||!Lm(i.res))return;let s=i.req.header("Accept-Encoding"),a=e?.encoding??Om.find((l)=>s?.includes(l));if(!a||!i.res.body)return;try{let l=a==="gzip"?Dm():jm(),d=za.fromWeb(i.res.body).pipe(l),u=za.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)}}},Mm=(e)=>{let t=e.headers.get("Content-Type");return t&&ke.test(t)},Lm=(e)=>{let t=e.headers.get("Cache-Control");return!t||!zm.test(t)};var Um=(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 La=async(e,t)=>{if(!e)return null;let r=void 0,i,n=0,o=async(a)=>{r=await t(Um(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 Bm=["cache-control","content-location","date","etag","expires","vary"],Ua=(e)=>e.replace(/^W\//,"");function $m(e,t){return t!=null&&t.split(",").some((r)=>Ua(r.trim())===Ua(e))}function _m(e){if(!e){if(crypto&&crypto.subtle)e=(t)=>crypto.subtle.digest({name:"SHA-1"},t)}return e}var Ba=(e)=>{let t=new Set((e?.retainedHeaders??Bm).map((n)=>n.toLowerCase())),r=e?.weak??!1,i=_m(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 La(l.clone().body,i);if(u===null)return;d=r?`W/"${u}"`:`"${u}"`}if(a==="*"||$m(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=$a.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 Ye(e,t){return e===t||e.startsWith(t+Fm)}var _a="public, max-age=31536000, immutable";function Nm(e){return e.getRoutes?.()??[]}var Hm=255;class Gt{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=N(e,`.${t}`,"index.html");if(!Ye(n,N(e)))return;let o=Bun.file(n);if(!await o.exists())return;let s=`<div ${Na}="${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:N(process.cwd(),e.productionDistDir),sharedImagesDir:N(process.cwd(),e.sharedImagesDir),...e.previewDistDir&&{previewDistDir:N(process.cwd(),e.previewDistDir)}}}async start(){if(this.productionServer){this.logger.warn("Webserver already running");return}this.stopping=!1,this.routes=Object.freeze([...Nm(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??Hm,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 Xs(e,{drainMs:this.options.shutdownDrainMs??Ys,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}: ${x(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:x(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("/*",Ma());return t.use("/*",Ba()),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",_a);else r.header("Cache-Control",e.defaultCache)}),t.use("/*",async(r,i)=>{if(r.req.path===Jt)return r.notFound();return i()}),t.use("/*",this.createCleanUrlMiddleware(e.distDir)),t.use("/*",Si({root:e.distDir})),t.get(Za,(r)=>r.body(Fa,200,{"Content-Type":"image/svg+xml; charset=utf-8","Cache-Control":"public, max-age=86400"})),t.notFound(async(r)=>{let i=Bun.file(Zm(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:x(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=ea(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=N(t.distDir,`.${i}`,"index.html");if(Ye(a,N(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=N(this.options.sharedImagesDir,r);if(!Ye(i,this.options.sharedImagesDir))return null;let n=Bun.file(i);if(!await n.exists())return null;return new Response(n,{headers:{"Cache-Control":_a}})}createCleanUrlMiddleware(e){return async(t,r)=>{let i=t.req.path;if(i.includes(".")||i==="/"){await r();return}let n=N(e,`.${i}`,"index.html");if(!Ye(n,e)){await r();return}let o=Bun.file(n);if(await o.exists())return t.html(await o.text());let s=N(e,`.${i}.html`);if(Ye(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:Qt.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:Ha(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 Wa=c.strictObject({productionOutputDir:c.string().min(1),previewOutputDir:c.string().min(1),sharedImagesDir:c.string().min(1)});var H="webserver",K=`${H}:${H}`,Qm="./dist/site-production",Km="./dist/site-preview",Vm="./dist/images";function Ym(e){return[...e].flatMap((t)=>{let r=t.getStaticSiteOutput?.();return r?[{...Wa.parse(r),ownerPluginId:t.id}]:[]})}function Xm(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&&qa(d)!==qa(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",Qm),previewDistDir:n("previewDistDir",r?.previewOutputDir,"preview site",Km),sharedImagesDir:n("sharedImagesDir",r?.sharedImagesDir,"shared images",Vm)}}async function eg(e,t,r){let i=[e.productionDistDir,...t?[e.previewDistDir]:[]];for(let n of i){if(Wm(n))continue;await qm(n,{recursive:!0}),await Jm(Gm(n,"index.html"),Pi),r.debug(`Created site directory at ${n}`)}}function Ga(e){return e?{siteUrl:`https://${e}`,previewUrl:`https://${Ja(e)}`}:{siteUrl:void 0,previewUrl:void 0}}function Qa(e){let{config:t,logger:r}=e,{siteUrl:i,previewUrl:n}=Ga(e.domain),o;return{start:async()=>{let s=Xm(t,Ym(e.getPlugins()));await eg(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,H)}),await o.start()},stop:async()=>{await o?.stop()},healthCheck:async()=>{let s=o?.getStatus(),a=s?.running??!1,l=i??s?.productionUrl??`http://localhost:${t.port}`,d=n??s?.previewUrl??`http://localhost:${t.port}`,u=[];if(a){if(u.push(`Production: ${l}`),s?.previewUrl)u.push(`Preview: ${d}`)}return{status:a?"healthy":"error",message:a?u.join(", "):"Webserver not running",lastCheck:new Date,details:{preview:!!s?.previewUrl,production:a,previewUrl:s?.previewUrl?d:void 0,productionUrl:a?l:void 0}}}}}function Ka(e,t){let{siteUrl:r,previewUrl:i}=Ga(t);if(!r)return{endpoints:[],interactions:[]};let n=e.preview&&i?i:void 0;return{endpoints:[{pluginId:H,label:"Site",url:r,priority:10},...n?[{pluginId:H,label:"Preview",url:n,priority:20,visibility:"admin"}]:[]],interactions:[{pluginId:H,id:"site",label:"Public site",description:"Visit the published public site for this brain.",href:r,kind:"human",priority:10},...n?[{pluginId:H,id:"preview",label:"Preview site",description:"Open the private preview build.",href:n,kind:"admin",priority:20,visibility:"admin"}]:[]]}}var tg=["shell.legacy-binary-content"];async function Va(e,t){for(let r of tg){let i=await e.scoped({namespace:r,schema:c.unknown()}).clear();if(i>0)t.info("Deleted retired runtime state",{namespace:r,cleared:i})}}var rg=250,ig=c.object({projectionBatch:c.object({operationId:c.string().min(1),childKey:c.string().min(1)})});class xi{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=xe(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 Vs({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 We(this.services.messageBus,Ya,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:Xa,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=ig.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 Va(this.services.runtimeStateService,this.services.logger),await this.loadIdentityServices(),!this.role.serves){this.services.jobProgressMonitor.start(),await this.services.jobQueueWorker.start(),this.services.logger.debug("Shell boot complete (worker process)");return}let i;if(e?.mode!=="startup-check"){await this.startHttpHost(),await this.services.entityService.reprojectRegisteredGroupings();let n=await this.services.entityService.rewriteRetiredFields();if(n.rewritten>0)this.services.logger.info("Rewrote entities carrying retired fields",{rewritten:n.rewritten});let o=await this.services.entityService.reconcileDeclaredMetadata();if(o.reconciled>0)this.services.logger.info("Re-derived declared entity metadata",{reconciled:o.reconciled});let s=nc();if(this.services.disposables.push(this.services.messageBus.subscribe(qe.initialSyncCompleted,async(l)=>(s.resolve(rc.safeParse(l.payload).data?.success===!0),{success:!0}))),await this.emitPluginsRegistered())i=s.promise.then(async(l)=>{if(l)return this.settleStartupContent();this.services.logger.warn("Initial sync failed; ready-state defaults are not created")}).catch((l)=>{this.services.logger.error("Failed to settle startup content",l)});else await this.settleStartupContent()}else await this.prepareReadyState();if(await this.services.pluginManager.readyPlugins(),e?.mode==="startup-check"){this.services.logger.debug("Shell boot complete (startup-check mode)");return}if(await this.startRuntimeServices(),i)i.then(()=>this.startIndexReadinessMonitor()).catch((n)=>{this.services.logger.warn("Semantic index readiness monitor did not start",n)});else await this.startIndexReadinessMonitor();this.services.logger.debug("Shell boot complete")}async startHttpHost(){if(!this.services.daemonRegistry.has(K))return;await this.services.daemonRegistry.start(K),this.services.logger.debug("Started the HTTP host before initial sync")}async emitPluginsRegistered(){let e=await this.services.messageBus.collect({type:qe.pluginsRegistered,payload:{timestamp:new Date().toISOString(),pluginCount:this.services.pluginManager.getAllPluginIds().length},sender:"shell"});return this.services.logger.debug("Emitted plugins registered event"),e.some((t)=>("data"in t)&&tc.safeParse(t.data).data?.initialSyncPending===!0)}async settleStartupContent(){await this.prepareReadyState(),await Te(this.services.messageBus,ic,{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 ec(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:rg,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 ng=c.object({}),oc=c.string().regex(/^\d{4}-(0[1-9]|1[0-2])$/,"Expected YYYY-MM"),ac=c.array(c.string().min(1)).min(1).optional().describe("Only these entity types"),og=c.object({entityTypes:ac,from:oc.optional().describe("First month, YYYY-MM"),to:oc.optional().describe("Last month, YYYY-MM")}),sg=c.object({staleDays:c.number().int().min(1).max(3650).default(90).describe("Days without an update before content counts as stale"),entityTypes:ac});function cc(e){let t=new sc;return t.register(Kt({type:"overview",description:"Entity counts by type, recent activity, and draft and published totals.",params:ng,handler:async(r,{entityService:i,visibilityScope:n})=>ag(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:og,handler:async(r,{entityService:i,visibilityScope:n})=>lg(i,n,r)})),t.register(Kt({type:"content-health",description:"Drafts and content not updated for a long time.",params:sg,handler:async(r,{entityService:i,visibilityScope:n})=>dg(i,n,e,r)})),t}async function ag(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 Ci(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=dc(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 cg(e){let t=e.metadata.publishedAt;return new Date(typeof t==="string"&&t?t:e.created)}function lc(e,t){return t?e.filter((r)=>t.includes(r.entityType)):e}async function lg(e,t,r){let i=lc(await Ci(e,t),r.entityTypes),n=new Map;for(let s of i){let a=cg(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 dg(e,t,r,i){let n=lc(await Ci(e,t),i.entityTypes),o=dc(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 dc(e){return e.filter((t)=>t.metadata.status==="draft")}async function Ci(e,t){let r=e.getEntityTypes(),i=[];for(let n of r){let o=await e.listEntities({entityType:n,options:{limit:1000,filter:{visibilityScope:t}}});i.push(...o)}return i}class Ye{parse;idOf;items=new Map;constructor(e,t){this.parse=e,this.idOf=t}register(e){let t=this.parse(e);this.items.set(this.keyFor(t.pluginId,this.idOf(t)),t)}unregister(e,t){if(t!==void 0){this.items.delete(this.keyFor(e,t));return}let r=`${e}:`;for(let i of this.items.keys())if(i.startsWith(r))this.items.delete(i)}list(){return Array.from(this.items.values()).sort((e,t)=>e.priority-t.priority||e.label.localeCompare(t.label))}keyFor(e,t){return`${e}:${t}`}}class Ti extends Ye{constructor(){super((e)=>uc.parse(e),(e)=>e.url)}}class Ei extends Ye{constructor(){super((e)=>pc.parse(e),(e)=>e.id)}}function mc(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 ug=["/health","/images"],pg=new Set([qt]),mg=new Set(gc),gg=new Set(["GET","POST","PUT","DELETE"]);function fc(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 hc(e){return pg.has(e)||ug.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&&hc(e))throw Error(`Invalid HTTP route path "${e}" declared by plugin "${t}"`)}function yc(e,t,r){if(!e.has(t))throw Error(`Invalid HTTP route method "${t}" declared by plugin "${r}"`)}function fg(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 hg(e,t){Ai(t.path,e.pluginId);let r=t.method??"GET";yc(mg,r,e.pluginId);let i=t.match??"exact";fg(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)=>!hc(o)&&n(o)}:{},handler:t.handler})}function yg(e,t){Ai(t.path,e.pluginId,!1);let r=`/api/${e.pluginId}${t.path}`;if(Ai(r,e.pluginId),yc(gg,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 vg(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 bg(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(hg(n,o)),r.push(Object.freeze({pluginId:n.pluginId,fullPath:o.path,definition:Object.freeze({...o})}));for(let o of n.apiRoutes){let s=yg(n,o);t.push(s),i.push(Object.freeze({pluginId:n.pluginId,fullPath:s.fullPath,definition:s.definition}))}}return vg(t),this.routes=Object.freeze(t),this.manifest=bg(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 vc(e,t){e.addFinalizer(async()=>{let{entityService:r}=t;if(Sg(r))await r.releaseDatabaseLease()}),e.addFinalizer(()=>t.pluginManager.shutdownPlugins()),e.addFinalizer(async()=>{if(t.daemonRegistry.has(K))await t.daemonRegistry.unregister(K)}),e.addFinalizer(()=>t.jobServicesLifecycle.closeRuntime()),e.addFinalizer(()=>t.agentService.shutdown?.()),e.addFinalizer(()=>t.daemonRegistry.unregister("shell:guest-retention")),e.addFinalizer(()=>t.daemonRegistry.unregister("shell:recurring-checks"))}function Sg(e){return"releaseDatabaseLease"in e&&typeof e.releaseDatabaseLease==="function"}function bc(e){return Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength)}var Rg=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")]),Rc=c.object({query:c.string().describe("Search term"),scope:Rg.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")}),wc=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.")}),Ic=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)")}),Pc=c.string().min(1).describe("Upload id from the conversation's upload refs"),xc=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(),Cc=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."),et=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:Pc,transform:Cc,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(),ki=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(),xc,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:Pc,transform:Cc},{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}),et,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()]),wg=c.discriminatedUnion("kind",[c.object({kind:c.literal("prompt").describe("A new non-image entity from a broad prompt; this branch has no source field."),entityType:c.string().min(1).describe("Entity type to generate from the prompt. Do not use image here; use standalone-image or cover-image."),title:c.string().optional().describe("Title for the generated entity"),prompt:c.string().min(1).describe("Prompt for creating new generated content, written from the user's request without added voice, tone or engagement directions; the style guide supplies the voice.")}).strict(),c.object({kind:c.literal("prompt-from-source").describe("A new non-image entity grounded in a resolved existing entity, such as a newsletter from a blog post."),entityType:c.string().min(1).describe("Entity type to generate from the source and prompt. Do not use image here; use standalone-image or cover-image."),title:c.string().optional().describe("Title for the generated entity"),source:c.object({entityType:c.string().min(1).describe("Resolved content source entity type, such as post for a newsletter from a blog post. Do not use brain-character or anchor-profile."),entityId:c.string().min(1).describe("Resolved source entity ID from a prior tool result or typed entity ref.")}).strict().describe("The resolved existing entity that grounds this generation."),additionalSourceIds:c.array(c.string().min(1)).optional().describe("More source IDs of the same type."),prompt:c.string().min(1).optional().describe("Direction from the user's request, without added voice, tone or engagement directions; the style guide supplies the voice. Omit if none is given.")}).strict(),c.object({kind:c.literal("standalone-image").describe("An unattached image; never a substitute for a requested cover."),title:c.string().optional().describe("Title for the generated image"),prompt:c.string().min(1).describe("Prompt for creating an unattached image. Not for cover images requested for a generated post/entity.")}).strict(),c.object({kind:c.literal("cover-image").describe("An image attached as coverImageId to an existing entity whose real id is known."),target:c.object({entityType:c.string().min(1).describe("Existing target entity type. Use the actual type of the entity being covered: social-post for LinkedIn/social posts, post for blog posts, etc."),entityId:c.string().min(1).describe("Existing target entity ID from a prior tool result or typed entity ref")}).strict().describe("Existing entity that should receive the generated coverImageId"),title:c.string().optional().describe("Title for the generated image"),prompt:c.string().min(1).describe("Prompt for creating the cover image")}).strict(),c.object({kind:c.literal("attachment").describe("Generate a deterministic durable artifact from an existing entity attachment provider"),source:c.object({entityType:c.string().min(1).describe("Source entity type"),entityId:c.string().min(1).describe("Canonical source entity ID from a prior tool result or typed entity ref")}).strict().describe("The resolved existing entity whose attachment provider renders the artifact."),attachmentType:c.string().min(1).describe('Source artifact type such as "carousel", "printable", or "og-image"'),title:c.string().optional().describe("Title for the generated artifact"),replace:c.boolean().optional().describe("Set true for regenerate, replace, refresh, or update requests so a deterministic artifact is regenerated instead of reused")}).strict()]),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:Sc.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:ki.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(),Tc=c.object({operation:wg.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(),Ig=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(),Xe="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(Ig).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:xc.optional().describe("Replace the stored Markdown with user-supplied text. Full replacement taken verbatim from a user message, for large rewrites the user supplied. Select the text with exact boundaries instead of copying it into content. Text without frontmatter replaces the body and keeps the stored frontmatter; text with frontmatter replaces the whole document.")},{error:(e)=>{if(e.code!=="unrecognized_keys")return;if(e.keys.includes("kind"))return ie(e.input)&&e.input.kind==="user-message"?'A user-message source is the source operation: put it under `source`, as in `{ source: { kind: "user-message", ... } }`.':"An update operation has no `kind`: name it by its field, as in `{ edits: [...] }`.";return`Unrecognized key ${e.keys.map((t)=>`"${t}"`).join(", ")}: ${Xe}`}}).refine((e)=>[e.fields,e.content,e.edits,e.source].filter((t)=>t!==void 0).length===1,{message:Xe}).describe(Xe),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(),Ec=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")}),vx=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")}),Ac=c.object({batchId:c.string().optional().describe("Specific batch ID to check"),jobTypes:c.array(c.string()).optional().describe("Filter by job types")}),Pg=c.object({entityType:c.string().optional(),entityId:c.string().optional(),attachmentType:c.string().optional()}),xg=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:Pg.optional()}),bx=c.object({entityId:c.string().optional(),status:c.enum(["created","generating"]),jobId:c.string().optional(),attachment:xg.optional()}),Sx=c.object({status:c.literal("extracting"),jobId:c.string(),entityType:c.string(),source:c.string().optional(),mode:c.enum(["derive","rebuild"]).optional()});function Dc(e,t,r){return r==="create"?e.getCreateFieldsSchema(t):e.getEditableFieldsSchema(t)}function zc(e){if(e instanceof c.ZodOptional||e instanceof c.ZodNullable||e instanceof c.ZodDefault)return zc(e.unwrap());return e instanceof c.ZodType?e:void 0}function kc(e){try{let{$schema:t,...r}=c.toJSONSchema(e,{target:"draft-7",io:"input"});return r}catch{return}}function Cg(e){return jc({type:"object",properties:{value:e},required:["value"]})!==void 0}function Oc(e,t){let r=new Map,i=new Map,n=e.getAllEntityTypes().filter((d)=>!t.neverWrites?.(d,t.on));for(let d of n){let u=Dc(e,d,t.on);for(let[p,m]of Object.entries(u?.shape??{})){if(t.omit?.includes(p))continue;let g=zc(m),f=g&&kc(g);if(!g||!f||!Cg(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(kc(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 Tg(e){return Object.fromEntries((Array.isArray(e)?e:[]).flatMap((t)=>V(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(Dc(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 zi(e){return"fields"in e&&e.fields!==void 0?{...e,fields:Tg(e.fields)}:e}function Mc(e,t){return{prepare:()=>e.ensureGroupingsCurrent(),inputSchema:()=>{let r=Oc(e,{on:"create",omit:["visibility"],...t&&{neverWrites:t}}),i=et.shape.items.element,n=et.extend({items:c.array(i.extend({fields:r.optional().describe("Field changes the user stated for this file alone, one { name, value } per field, such as the date and address it was first published at: [{ name: 'publishedAt', value }, { name: 'canonicalUrl', value }]; facts shared by every file go in the top-level fields.")})).min(2).max(20)}),[o,...s]=ki.options.map((a)=>a===et?n:a);if(!o)throw Error("system_create has no source branches");return{...Yt.shape,source:c.discriminatedUnion("kind",[o,...s]).describe("Concrete source selector. Use exactly one source branch. For AI generation or source-derived artifacts, use system_generate instead."),fields:r.optional().describe("Field changes for facts the user states outside the source text, one { name, value } per field, e.g. a post first published elsewhere: [{ name: 'status', value: 'published' }, { name: 'publishedAt', value: '2025-03-12' }, { name: 'canonicalUrl', value }]; the section a doc goes in, named exactly as the user names it: [{ name: 'section', value }]; the year a project began: [{ name: 'year', value }]. Never copy values from the text or its frontmatter; omit when nothing extra is stated.")}},toToolInput:(r)=>{let i=r.source;return zi({...r,...V(i)&&Array.isArray(i.items)&&{source:{...i,items:i.items.map((n)=>V(n)?zi(n):n)}}})}}}function Di(e){let t=e.unwrap();return e.description?t.describe(e.description):t}function Lc(e,t){let{content:r,edits:i,source:n}=ji.shape;return{prepare:()=>e.ensureGroupingsCurrent(),inputSchema:()=>({...Xt.shape,operation:c.union([c.strictObject({fields:Oc(e,{on:"update",...t&&{neverWrites:t}}).describe("Change frontmatter or metadata fields, one { name, value } per field changed. Use this for status, title, coverImageId, ogImageId, and metadata changes such as approving an agent. To set an existing image as an entity cover, change coverImageId to that image id. To remove a field, such as a cover image, give it the value null, not an empty string. Do not use fields for anchor-profile; anchor-profile updates require the content operation.")}),c.strictObject({content:Di(r)}),c.strictObject({edits:Di(i)}),c.strictObject({source:Di(n)})]).describe("Exactly one update operation")}),toToolInput:(o)=>{let s=o.operation;return V(s)?{...o,operation:zi(s)}:o}}}function B(e,t,r,i){try{e.permissionService.assertEntityActionAllowed(t,r,i.userPermissionLevel);return}catch(n){if(n instanceof Error)return{success:!1,error:n.message};throw n}}function tr(e){return(t,r)=>e.getEntityActionRequiredLevel(t,r)==="never"}var Eg="system";function X(e){return{kind:"error",result:e}}function T(e,t){return X({success:!1,error:e,...t!==void 0&&{code:t}})}function W(e,t,r,i,n={}){let{visibility:o="admin",sideEffects:s}=n;return{name:`${Eg}_${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:x(u)}}},visibility:o,...s?{sideEffects:s}:{}}}function ir(e){return{interfaceType:e.interfaceType,actor:e.actor,userPermissionLevel:e.userPermissionLevel??"public",...e.channelId&&{channelId:e.channelId},...e.channelName&&{channelName:e.channelName}}}async function Uc(e,t,r,i){let n=await t(r,ir(i));if(n.kind==="handled")return{kind:"handled",result:n.result};let o=n.input;if(o.visibility!==r.visibility)return{kind:"error",result:{success:!1,error:"Create interceptor changed or dropped the requested entity visibility."}};let s=B(e,o.entityType,"create",i);if(s)return{kind:"error",result:s};return{kind:"continue",createInput:o}}function je(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 De(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 Oi(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 nr(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var Ag={base:"note"};function Bc(e){return Ag[e]??e.replaceAll("-"," ")}function ze(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 $c(e){return!!e&&Object.keys(e.shape).length>0}async function _c(e,t,r){if(!r)return!1;let i=await e.conversationService.getMessages(r,{limit:100});for(let n of i){let s=rr(n.metadata)?.attachments;if(!Array.isArray(s))continue;for(let a of s){if(!ie(a))continue;let l=a.source;if(!ie(l))continue;if(l.kind===t.kind&&l.id===t.id)return!0}}return!1}async function 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"&&!B(e,t.entityType,"delete",r))return{kind:"ok",value:{entityType:i.entityType,id:i.id}};return T(`A ${t.entityType} already exists for "${t.candidateId}". To change it, use system_update on that ${t.entityType} in this turn, without asking first; pass replace:true to ${t.copyHint}.`)}function Zc(e){return`Replaces: failed ${e.entityType} "${e.id}"`}async function Fc(e,t){if(!t)return;try{await e.entityService.deleteEntity(t);return}catch(r){return{success:!1,error:x(r,"Failed to replace the failed entity")}}}function sr(e,t,r){let i=je(e,t);if(i)return X(i);let n=B(e,t,"create",r);if(n)return X(n);return{kind:"ok",value:{interceptor:e.entityRegistry.getCreateInterceptor(t)}}}async function 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
|
-
${Zc(i)}`:a,args:t.buildArgs((d)=>({...l,confirmed:!0,confirmationToken:d}))}}async function
|
|
77
|
+
</html>`;var Wa=c.strictObject({productionOutputDir:c.string().min(1),previewOutputDir:c.string().min(1),sharedImagesDir:c.string().min(1)});var H="webserver",K=`${H}:${H}`,Qm="./dist/site-production",Km="./dist/site-preview",Vm="./dist/images";function Ym(e){return[...e].flatMap((t)=>{let r=t.getStaticSiteOutput?.();return r?[{...Wa.parse(r),ownerPluginId:t.id}]:[]})}function Xm(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&&qa(d)!==qa(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",Qm),previewDistDir:n("previewDistDir",r?.previewOutputDir,"preview site",Km),sharedImagesDir:n("sharedImagesDir",r?.sharedImagesDir,"shared images",Vm)}}async function eg(e,t,r){let i=[e.productionDistDir,...t?[e.previewDistDir]:[]];for(let n of i){if(Wm(n))continue;await qm(n,{recursive:!0}),await Jm(Gm(n,"index.html"),Pi),r.debug(`Created site directory at ${n}`)}}function Ga(e){return e?{siteUrl:`https://${e}`,previewUrl:`https://${Ja(e)}`}:{siteUrl:void 0,previewUrl:void 0}}function Qa(e){let{config:t,logger:r}=e,{siteUrl:i,previewUrl:n}=Ga(e.domain),o;return{start:async()=>{let s=Xm(t,Ym(e.getPlugins()));await eg(s,t.preview,r),o??=new Gt({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,H)}),await o.start()},stop:async()=>{await o?.stop()},healthCheck:async()=>{let s=o?.getStatus(),a=s?.running??!1,l=i??s?.productionUrl??`http://localhost:${t.port}`,d=n??s?.previewUrl??`http://localhost:${t.port}`,u=[];if(a){if(u.push(`Production: ${l}`),s?.previewUrl)u.push(`Preview: ${d}`)}return{status:a?"healthy":"error",message:a?u.join(", "):"Webserver not running",lastCheck:new Date,details:{preview:!!s?.previewUrl,production:a,previewUrl:s?.previewUrl?d:void 0,productionUrl:a?l:void 0}}}}}function Ka(e,t){let{siteUrl:r,previewUrl:i}=Ga(t);if(!r)return{endpoints:[],interactions:[]};let n=e.preview&&i?i:void 0;return{endpoints:[{pluginId:H,label:"Site",url:r,priority:10},...n?[{pluginId:H,label:"Preview",url:n,priority:20,visibility:"admin"}]:[]],interactions:[{pluginId:H,id:"site",label:"Public site",description:"Visit the published public site for this brain.",href:r,kind:"human",priority:10},...n?[{pluginId:H,id:"preview",label:"Preview site",description:"Open the private preview build.",href:n,kind:"admin",priority:20,visibility:"admin"}]:[]]}}var tg=["shell.legacy-binary-content"];async function Va(e,t){for(let r of tg){let i=await e.scoped({namespace:r,schema:c.unknown()}).clear();if(i>0)t.info("Deleted retired runtime state",{namespace:r,cleared:i})}}var rg=250,ig=c.object({projectionBatch:c.object({operationId:c.string().min(1),childKey:c.string().min(1)})});class xi{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=xe(n),this.hooks=o}async boot(e){this.services.logger.debug("Starting Shell boot");let t=this.initializer;await Kt([()=>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 Vs({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 qe(this.services.messageBus,Ya,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:Xa,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=ig.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 Va(this.services.runtimeStateService,this.services.logger),await this.loadIdentityServices(),!this.role.serves){this.services.jobProgressMonitor.start(),await this.services.jobQueueWorker.start(),this.services.logger.debug("Shell boot complete (worker process)");return}let i;if(e?.mode!=="startup-check"){await this.startHttpHost(),await this.services.entityService.reprojectRegisteredGroupings();let n=await this.services.entityService.rewriteRetiredFields();if(n.rewritten>0)this.services.logger.info("Rewrote entities carrying retired fields",{rewritten:n.rewritten});let o=await this.services.entityService.reconcileDeclaredMetadata();if(o.reconciled>0)this.services.logger.info("Re-derived declared entity metadata",{reconciled:o.reconciled});let s=nc();if(this.services.disposables.push(this.services.messageBus.subscribe(Je.initialSyncCompleted,async(l)=>(s.resolve(rc.safeParse(l.payload).data?.success===!0),{success:!0}))),await this.emitPluginsRegistered())i=s.promise.then(async(l)=>{if(l)return this.settleStartupContent();this.services.logger.warn("Initial sync failed; ready-state defaults are not created")}).catch((l)=>{this.services.logger.error("Failed to settle startup content",l)});else await this.settleStartupContent()}else await this.prepareReadyState();if(await this.services.pluginManager.readyPlugins(),e?.mode==="startup-check"){this.services.logger.debug("Shell boot complete (startup-check mode)");return}if(await this.startRuntimeServices(),i)i.then(()=>this.startIndexReadinessMonitor()).catch((n)=>{this.services.logger.warn("Semantic index readiness monitor did not start",n)});else await this.startIndexReadinessMonitor();this.services.logger.debug("Shell boot complete")}async startHttpHost(){if(!this.services.daemonRegistry.has(K))return;await this.services.daemonRegistry.start(K),this.services.logger.debug("Started the HTTP host before initial sync")}async emitPluginsRegistered(){let e=await this.services.messageBus.collect({type:Je.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)&&tc.safeParse(t.data).data?.initialSyncPending===!0)}async settleStartupContent(){await this.prepareReadyState(),await Te(this.services.messageBus,ic,{timestamp:new Date().toISOString()},"shell"),this.services.logger.debug("Emitted startup content settled event")}async loadIdentityServices(){await Kt([()=>this.services.identityService.refreshCache(),()=>this.services.profileService.refreshCache(),()=>this.services.canonicalIdentityService.refreshCache()]),this.services.logger.debug("Identity services loaded")}async initializeIdentityServices(){await Kt([()=>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 ec(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:rg,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 ng=c.object({}),oc=c.string().regex(/^\d{4}-(0[1-9]|1[0-2])$/,"Expected YYYY-MM"),ac=c.array(c.string().min(1)).min(1).optional().describe("Only these entity types"),og=c.object({entityTypes:ac,from:oc.optional().describe("First month, YYYY-MM"),to:oc.optional().describe("Last month, YYYY-MM")}),sg=c.object({staleDays:c.number().int().min(1).max(3650).default(90).describe("Days without an update before content counts as stale"),entityTypes:ac});function cc(e){let t=new sc;return t.register(Vt({type:"overview",description:"Entity counts by type, recent activity, and draft and published totals.",params:ng,handler:async(r,{entityService:i,visibilityScope:n})=>ag(i,n)})),t.register(Vt({type:"publishing-cadence",description:"Pieces per month, by type: counted in the month they were published, or created when never published.",params:og,handler:async(r,{entityService:i,visibilityScope:n})=>lg(i,n,r)})),t.register(Vt({type:"content-health",description:"Drafts and content not updated for a long time.",params:sg,handler:async(r,{entityService:i,visibilityScope:n})=>dg(i,n,e,r)})),t}async function ag(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 Ci(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=dc(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 cg(e){let t=e.metadata.publishedAt;return new Date(typeof t==="string"&&t?t:e.created)}function lc(e,t){return t?e.filter((r)=>t.includes(r.entityType)):e}async function lg(e,t,r){let i=lc(await Ci(e,t),r.entityTypes),n=new Map;for(let s of i){let a=cg(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 dg(e,t,r,i){let n=lc(await Ci(e,t),i.entityTypes),o=dc(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 dc(e){return e.filter((t)=>t.metadata.status==="draft")}async function Ci(e,t){let r=e.getEntityTypes(),i=[];for(let n of r){let o=await e.listEntities({entityType:n,options:{limit:1000,filter:{visibilityScope:t}}});i.push(...o)}return i}class Xe{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 Xe{constructor(){super((e)=>uc.parse(e),(e)=>e.url)}}class Ei extends Xe{constructor(){super((e)=>pc.parse(e),(e)=>e.id)}}function mc(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 ug=["/health","/images"],pg=new Set([Jt]),mg=new Set(gc),gg=new Set(["GET","POST","PUT","DELETE"]);function fc(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 hc(e){return pg.has(e)||ug.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&&hc(e))throw Error(`Invalid HTTP route path "${e}" declared by plugin "${t}"`)}function yc(e,t,r){if(!e.has(t))throw Error(`Invalid HTTP route method "${t}" declared by plugin "${r}"`)}function fg(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 hg(e,t){Ai(t.path,e.pluginId);let r=t.method??"GET";yc(mg,r,e.pluginId);let i=t.match??"exact";fg(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)=>!hc(o)&&n(o)}:{},handler:t.handler})}function yg(e,t){Ai(t.path,e.pluginId,!1);let r=`/api/${e.pluginId}${t.path}`;if(Ai(r,e.pluginId),yc(gg,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 vg(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 bg(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 Yt{routes;manifest;apiRoutes;webRoutes;static createFresh(){return new Yt}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(hg(n,o)),r.push(Object.freeze({pluginId:n.pluginId,fullPath:o.path,definition:Object.freeze({...o})}));for(let o of n.apiRoutes){let s=yg(n,o);t.push(s),i.push(Object.freeze({pluginId:n.pluginId,fullPath:s.fullPath,definition:s.definition}))}}return vg(t),this.routes=Object.freeze(t),this.manifest=bg(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 vc(e,t){e.addFinalizer(async()=>{let{entityService:r}=t;if(Sg(r))await r.releaseDatabaseLease()}),e.addFinalizer(()=>t.pluginManager.shutdownPlugins()),e.addFinalizer(async()=>{if(t.daemonRegistry.has(K))await t.daemonRegistry.unregister(K)}),e.addFinalizer(()=>t.jobServicesLifecycle.closeRuntime()),e.addFinalizer(()=>t.agentService.shutdown?.()),e.addFinalizer(()=>t.daemonRegistry.unregister("shell:guest-retention")),e.addFinalizer(()=>t.daemonRegistry.unregister("shell:recurring-checks"))}function Sg(e){return"releaseDatabaseLease"in e&&typeof e.releaseDatabaseLease==="function"}function bc(e){return Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength)}var Rg=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")]),Rc=c.object({query:c.string().describe("Search term"),scope:Rg.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")}),wc=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.")}),Ic=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)")}),Pc=c.string().min(1).describe("Upload id from the conversation's upload refs"),xc=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(),Cc=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."),tt=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:Pc,transform:Cc,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(),ki=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(),xc,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:Pc,transform:Cc},{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}),tt,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()]),wg=c.discriminatedUnion("kind",[c.object({kind:c.literal("prompt").describe("A new non-image entity from a broad prompt; this branch has no source field."),entityType:c.string().min(1).describe("Entity type to generate from the prompt. Do not use image here; use standalone-image or cover-image."),title:c.string().optional().describe("Title for the generated entity"),prompt:c.string().min(1).describe("Prompt for creating new generated content, written from the user's request without added voice, tone or engagement directions; the style guide supplies the voice.")}).strict(),c.object({kind:c.literal("prompt-from-source").describe("A new non-image entity grounded in a resolved existing entity, such as a newsletter from a blog post."),entityType:c.string().min(1).describe("Entity type to generate from the source and prompt. Do not use image here; use standalone-image or cover-image."),title:c.string().optional().describe("Title for the generated entity"),source:c.object({entityType:c.string().min(1).describe("Resolved content source entity type, such as post for a newsletter from a blog post. Do not use brain-character or anchor-profile."),entityId:c.string().min(1).describe("Resolved source entity ID from a prior tool result or typed entity ref.")}).strict().describe("The resolved existing entity that grounds this generation."),additionalSourceIds:c.array(c.string().min(1)).optional().describe("More source IDs of the same type."),prompt:c.string().min(1).optional().describe("Direction from the user's request, without added voice, tone or engagement directions; the style guide supplies the voice. Omit if none is given.")}).strict(),c.object({kind:c.literal("standalone-image").describe("An unattached image; never a substitute for a requested cover."),title:c.string().optional().describe("Title for the generated image"),prompt:c.string().min(1).describe("Prompt for creating an unattached image. Not for cover images requested for a generated post/entity.")}).strict(),c.object({kind:c.literal("cover-image").describe("An image attached as coverImageId to an existing entity whose real id is known."),target:c.object({entityType:c.string().min(1).describe("Existing target entity type. Use the actual type of the entity being covered: social-post for LinkedIn/social posts, post for blog posts, etc."),entityId:c.string().min(1).describe("Existing target entity ID from a prior tool result or typed entity ref")}).strict().describe("Existing entity that should receive the generated coverImageId"),title:c.string().optional().describe("Title for the generated image"),prompt:c.string().min(1).describe("Prompt for creating the cover image")}).strict(),c.object({kind:c.literal("attachment").describe("Generate a deterministic durable artifact from an existing entity attachment provider"),source:c.object({entityType:c.string().min(1).describe("Source entity type"),entityId:c.string().min(1).describe("Canonical source entity ID from a prior tool result or typed entity ref")}).strict().describe("The resolved existing entity whose attachment provider renders the artifact."),attachmentType:c.string().min(1).describe('Source artifact type such as "carousel", "printable", or "og-image"'),title:c.string().optional().describe("Title for the generated artifact"),replace:c.boolean().optional().describe("Set true for regenerate, replace, refresh, or update requests so a deterministic artifact is regenerated instead of reused")}).strict()]),Xt=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:Sc.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:ki.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(),Tc=c.object({operation:wg.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(),Ig=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(),et="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(Ig).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:xc.optional().describe("Replace the stored Markdown with user-supplied text. Full replacement taken verbatim from a user message, for large rewrites the user supplied. Select the text with exact boundaries instead of copying it into content. Text without frontmatter replaces the body and keeps the stored frontmatter; text with frontmatter replaces the whole document.")},{error:(e)=>{if(e.code!=="unrecognized_keys")return;if(e.keys.includes("kind"))return ie(e.input)&&e.input.kind==="user-message"?'A user-message source is the source operation: put it under `source`, as in `{ source: { kind: "user-message", ... } }`.':"An update operation has no `kind`: name it by its field, as in `{ edits: [...] }`.";return`Unrecognized key ${e.keys.map((t)=>`"${t}"`).join(", ")}: ${et}`}}).refine((e)=>[e.fields,e.content,e.edits,e.source].filter((t)=>t!==void 0).length===1,{message:et}).describe(et),er=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(),Ec=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")}),bx=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")}),Ac=c.object({batchId:c.string().optional().describe("Specific batch ID to check"),jobTypes:c.array(c.string()).optional().describe("Filter by job types")}),Pg=c.object({entityType:c.string().optional(),entityId:c.string().optional(),attachmentType:c.string().optional()}),xg=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:Pg.optional()}),Sx=c.object({entityId:c.string().optional(),status:c.enum(["created","generating"]),jobId:c.string().optional(),attachment:xg.optional()}),Rx=c.object({status:c.literal("extracting"),jobId:c.string(),entityType:c.string(),source:c.string().optional(),mode:c.enum(["derive","rebuild"]).optional()});function Dc(e,t,r){return r==="create"?e.getCreateFieldsSchema(t):e.getEditableFieldsSchema(t)}function Oc(e){if(e instanceof c.ZodOptional||e instanceof c.ZodNullable||e instanceof c.ZodDefault)return Oc(e.unwrap());return e instanceof c.ZodType?e:void 0}function kc(e){try{let{$schema:t,...r}=c.toJSONSchema(e,{target:"draft-7",io:"input"});return r}catch{return}}function Cg(e){return jc({type:"object",properties:{value:e},required:["value"]})!==void 0}function zc(e,t){let r=new Map,i=new Map,n=e.getAllEntityTypes().filter((d)=>!t.neverWrites?.(d,t.on));for(let d of n){let u=Dc(e,d,t.on);for(let[p,m]of Object.entries(u?.shape??{})){if(t.omit?.includes(p))continue;let g=Oc(m),f=g&&kc(g);if(!g||!f||!Cg(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(kc(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 Tg(e){return Object.fromEntries((Array.isArray(e)?e:[]).flatMap((t)=>V(t)&&typeof t.name==="string"?[[t.name,t.value]]:[]))}function tr(e,t,r,i){if(!r)return;let{allow:n}=i,o=new Set(Object.keys(Dc(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:Tg(e.fields)}:e}function Mc(e,t){return{prepare:()=>e.ensureGroupingsCurrent(),inputSchema:()=>{let r=zc(e,{on:"create",omit:["visibility"],...t&&{neverWrites:t}}),i=tt.shape.items.element,n=tt.extend({items:c.array(i.extend({fields:r.optional().describe("Field changes the user stated for this file alone, one { name, value } per field, such as the date and address it was first published at: [{ name: 'publishedAt', value }, { name: 'canonicalUrl', value }]; facts shared by every file go in the top-level fields.")})).min(2).max(20)}),[o,...s]=ki.options.map((a)=>a===tt?n:a);if(!o)throw Error("system_create has no source branches");return{...Xt.shape,source:c.discriminatedUnion("kind",[o,...s]).describe("Concrete source selector. Use exactly one source branch. For AI generation or source-derived artifacts, use system_generate instead."),fields:r.optional().describe("Field changes for facts the user states outside the source text, one { name, value } per field, e.g. a post first published elsewhere: [{ name: 'status', value: 'published' }, { name: 'publishedAt', value: '2025-03-12' }, { name: 'canonicalUrl', value }]; the section a doc goes in, named exactly as the user names it: [{ name: 'section', value }]; the year a project began: [{ name: 'year', value }]. Never copy values from the text or its frontmatter; omit when nothing extra is stated.")}},toToolInput:(r)=>{let i=r.source;return Oi({...r,...V(i)&&Array.isArray(i.items)&&{source:{...i,items:i.items.map((n)=>V(n)?Oi(n):n)}}})}}}function Di(e){let t=e.unwrap();return e.description?t.describe(e.description):t}function Lc(e,t){let{content:r,edits:i,source:n}=ji.shape;return{prepare:()=>e.ensureGroupingsCurrent(),inputSchema:()=>({...er.shape,operation:c.union([c.strictObject({fields:zc(e,{on:"update",...t&&{neverWrites:t}}).describe("Change frontmatter or metadata fields, one { name, value } per field changed. Use this for status, title, coverImageId, ogImageId, and metadata changes such as approving an agent. To set an existing image as an entity cover, change coverImageId to that image id. To remove a field, such as a cover image, give it the value null, not an empty string. Do not use fields for anchor-profile; anchor-profile updates require the content operation.")}),c.strictObject({content:Di(r)}),c.strictObject({edits:Di(i)}),c.strictObject({source:Di(n)})]).describe("Exactly one update operation")}),toToolInput:(o)=>{let s=o.operation;return V(s)?{...o,operation:Oi(s)}:o}}}function B(e,t,r,i){try{e.permissionService.assertEntityActionAllowed(t,r,i.userPermissionLevel);return}catch(n){if(n instanceof Error)return{success:!1,error:n.message};throw n}}function rr(e){return(t,r)=>e.getEntityActionRequiredLevel(t,r)==="never"}var Eg="system";function X(e){return{kind:"error",result:e}}function T(e,t){return X({success:!1,error:e,...t!==void 0&&{code:t}})}function W(e,t,r,i,n={}){let{visibility:o="admin",sideEffects:s}=n;return{name:`${Eg}_${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:x(u)}}},visibility:o,...s?{sideEffects:s}:{}}}function nr(e){return{interfaceType:e.interfaceType,actor:e.actor,userPermissionLevel:e.userPermissionLevel??"public",...e.channelId&&{channelId:e.channelId},...e.channelName&&{channelName:e.channelName}}}async function Uc(e,t,r,i){let n=await t(r,nr(i));if(n.kind==="handled")return{kind:"handled",result:n.result};let o=n.input;if(o.visibility!==r.visibility)return{kind:"error",result:{success:!1,error:"Create interceptor changed or dropped the requested entity visibility."}};let s=B(e,o.entityType,"create",i);if(s)return{kind:"error",result:s};return{kind:"continue",createInput:o}}function je(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 De(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 zi(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 or(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var Ag={base:"note"};function Bc(e){return Ag[e]??e.replaceAll("-"," ")}function Oe(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 $c(e){return!!e&&Object.keys(e.shape).length>0}async function _c(e,t,r){if(!r)return!1;let i=await e.conversationService.getMessages(r,{limit:100});for(let n of i){let s=ir(n.metadata)?.attachments;if(!Array.isArray(s))continue;for(let a of s){if(!ie(a))continue;let l=a.source;if(!ie(l))continue;if(l.kind===t.kind&&l.id===t.id)return!0}}return!1}async function sr(e,t,r){if(t.replace||!t.candidateId)return{kind:"ok",value:void 0};let i=await e.entityService.getEntity({entityType:t.entityType,id:t.candidateId,visibilityScope:A(r.userPermissionLevel)});if(!i)return{kind:"ok",value:void 0};if(i.metadata.status==="failed"&&r.userPermissionLevel==="admin"&&!B(e,t.entityType,"delete",r))return{kind:"ok",value:{entityType:i.entityType,id:i.id}};return T(`A ${t.entityType} already exists for "${t.candidateId}". To change it, use system_update on that ${t.entityType} in this turn, without asking first; pass replace:true to ${t.copyHint}.`)}function Zc(e){return`Replaces: failed ${e.entityType} "${e.id}"`}async function Fc(e,t){if(!t)return;try{await e.entityService.deleteEntity(t);return}catch(r){return{success:!1,error:x(r,"Failed to replace the failed entity")}}}function ar(e,t,r){let i=je(e,t);if(i)return X(i);let n=B(e,t,"create",r);if(n)return X(n);return{kind:"ok",value:{interceptor:e.entityRegistry.getCreateInterceptor(t)}}}async function cr(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
|
+
${Zc(i)}`:a,args:t.buildArgs((d)=>({...l,confirmed:!0,confirmationToken:d}))}}async function rt(e,t,r){let i=await Fc(e,r.replacesFailed);if(i)return i;if(!r.interceptor)return r.persist(r.createInput);let n=await Uc(e,r.interceptor,r.createInput,t);if(n.kind!=="continue")return n.result;return r.persist(n.createInput)}async function lr(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=ir(y.metadata)?.userPermissionLevel;return(R==="public"||R==="trusted"||R==="admin")&&e.permissionService.hasPermission(S,R)}):o.filter(Hc),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=Og(Dg(t,l.content),l.content),u=(y,S,R,w)=>{if(!S)return{offset:R};let P=`${y} ${JSON.stringify(S)}`;if(d.boundaryMode==="lines"&&/[\r\n]/.test(S))return{problem:`${P} contains a newline; in lines mode give the marker line's text only`};let E=kg(l.content,S,d.boundaryMode==="lines"?"lines":"literal",w),[L]=E;if(E.length===1&&L!==void 0)return{offset:L};return{problem:E.length===0?`${P} does not occur in the message`:`${P} occurs ${E.length} times in the message`}},p=u("startAfter",d.startAfter,0,!0),m=d.boundaryMode==="frontmatter"&&"offset"in p?Mg(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. ${zg(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!==G(h))return{success:!1,error:"User-message source changed after the proposal. Request the change again and confirm the new approval."};return{success:!0,messageId:l.id,content:h,source:d}}function dr(e,t){let{startAfter:r,endBefore:i,...n}=t.source??e;return{...n,...r?{startAfter:r}:{},...i?{endBefore:i}:{},messageId:t.messageId,contentHash:G(t.content)}}function kg(e,t,r,i){if(r==="lines"){let o=Mi(e,t,i);return o.length>0||!t.trim()?o:Mi(e,t,i,jg)}let n=Wc(e,t,i);return n.length>0?n:Lg(e,t,i)}function jg(e){return e.trim().replace(/\s+/g," ")}function Dg(e,t){let r=(a)=>a?.trim()==="---";if(!r(e.startAfter)&&!r(e.endBefore))return e;if((t.match(/^---\r?$/gm)?.length??0)!==2||Li(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 Og(e,t){let{startAfter:r,endBefore:i}=e;if(e.boundaryMode!==void 0||!r||!i)return e;let n=(o)=>!/[\r\n]/.test(o)&&Mi(t,o,!0).length===1;return n(r)&&n(i)?{...e,boundaryMode:"lines"}:e}function zg(e){return Li(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 Mg(e,t){let r=Li(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 Li(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 Mi(e,t,r,i=(n)=>n){let n=i(t);return e.split(/(?<=\n)/).reduce((o,s)=>({offset:o.offset+s.length,matches:i(s.replace(/\r?\n$/,""))===n?[...o.matches,o.offset+(r?s.length:0)]:o.matches}),{offset:0,matches:[]}).matches}function Lg(e,t,r){let i=t.trim().split(/\s+/);if(i.join("")===""||!/\s/.test(t))return[];let n=(s)=>s?"\\s*":"",o=new RegExp(n(/^\s/.test(t))+i.map(Nc).join("\\s+")+n(/\s$/.test(t)),"g");return Array.from(e.matchAll(o),(s)=>s.index+(r?s[0].length:0))}function Wc(e,t,r,i=0){let n=e.indexOf(t,i);if(n<0)return[];return[n+(r?t.length:0),...Wc(e,t,r,n+1)]}var Ug=/^[ \t]*---[ \t]*$/gm;function qc(e){return e.replace(/\s+/g," ").trim()}function Bg(e){return e.kind==="user-message"?e.messageId:void 0}class Ui{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=Bg(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&&qc(t.content.replace(Ug,""))===qc(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 Bi(e,t){return e?`${e}\x00${t}`:void 0}function Jc(e){if(e.kind!=="user-message")return e;let{contentHash:t,...r}=e;return r}function $i(e){return`${e.entityType} "${e.title}"`}function $g(e){return Object.entries(e).map(([t,r])=>`${t}: ${typeof r==="string"?r:JSON.stringify(r)}`).join(", ")}function Gc(e){return"error"in e?e.error:"the save was not completed"}function _g(e){let t=new Map;for(let r of e){let i=`${r.entityType}:${ee(r.title)}`,n=t.get(i);if(n)return`${n.filename} and ${r.filename} would both be saved as ${$i(r)}. Give them different titles in source.items.`;t.set(i,r)}return}function Zg(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?[` ${$g(r.fields)}`]:[],...r.replacesFailed?[` Replaces failed ${r.replacesFailed}`]:[]].join(`
|
|
79
79
|
`)),`Visibility: ${t??"public"}`].join(`
|
|
80
80
|
`)}}async function Fg(e){let t=[],r=[];for(let i of e){let n=await i.save();if("success"in n&&n.success)t.push({filename:i.filename,entityType:i.entityType,title:i.title,...V(n.data)?n.data:{}});else r.push(`${i.filename}: ${Gc(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 Qc(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}): ${Gc(d.result)}`};i.push(d.value)}let n=_g(i);if(n)return{success:!1,error:n};if(t.confirmed){let a=r.validateConfirmed(t.confirmationToken,t);if(a)return a;return Fg(i)}let o=Zg(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 Ng(e){return{summary:`Save uploaded file${e.title?` as "${e.title}"`:""}?`,preview:[`Filename: ${e.filename}`,`Media type: ${e.mediaType}`,`Entity type: ${e.entityType}`,`Visibility: ${e.visibility??"public"}`,...e.title?[`Title: ${e.title}`]:[]].join(`
|
|
81
81
|
`)}}function Hg(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 Wg(e){let t=e.title?` "${e.title}"`:"";return`Saved ${e.entityType}${t}.`}function qg(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 Jg(e,t,r){let i=await _(e.entityService,{entityType:t.entityType,identifier:t.entityId},{visibilityScope:A(r.userPermissionLevel),logger:e.logger,label:"Source entity"});if(!i.ok)return T(i.error);let{entity:n}=i,o=Oe(n.content,{trim:!0,keepEmptyBlock:!0});if(!o)return T(`Source entity ${n.entityType}/${n.id} has no text to use.`);let s=n.metadata.title;return{kind:"ok",value:{ref:{entityType:n.entityType,entityId:n.id},content:o,title:typeof s==="string"&&s.trim()?s:void 0,visibility:n.visibility}}}function Gg(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 Qg(e,t){let r=ir(t);return e.handler({upload:e.upload,...e.title&&{title:e.title},...e.visibility!==void 0?{visibility:e.visibility}:{}},r)}async function Kg(e,t,r){let{entityService:i,entityRegistry:n}=e,o=ee(t.title??`${t.entityType}-${Date.now()}`),s=n.getEffectiveFrontmatterSchema(t.entityType),a=t.content!==void 0&&$c(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:x(l,"Failed to create entity")}}}async function Vg(e,t,r){let{content:i,url:n,from:o,uploadRef:s,conversationMessageRef:a,entityRef:l,transform:d}=qg(t.source),u=l?await Jg(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 X(p);let m=p?.success===!0?p.content:u?.value.content??i;if(d==="extract-markdown"&&!s)return T('Transform "extract-markdown" requires an upload ref.');if(!m&&!n&&!o)return T('Provide `source` with kind "user-message", "text", "url", "prior-response", "upload", or "entity". Use system_generate for generated content or artifacts.');return{kind:"ok",value:{content:m,url:n,from:o,uploadRef:s,transform:d,resolvedMessageId:p?.success===!0?p.messageId:void 0,resolvedUserSource:p?.success===!0?p.source:void 0,entitySource:u?.value}}}async function Yg(e,t){if(!_i(t.mediaType))return;let{content:r}=await e.runtimeUploads.scoped(Ce).read(t.id);return bc(r).toString("utf8")}async function Xg(e,t,r){if(!await _c(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(Ce).readRecord(t.uploadRef.id),o=t.transform==="extract-markdown"?await Yg(e,{id:t.uploadRef.id,mediaType:n.mediaType}):void 0}catch{return T("Upload ref not found")}let s=Vc({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=_i(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 ef(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 tf(e,t,r){return or(e,{entityType:t.entityType,candidateId:t.title?ee(t.title):void 0,replace:t.replace===!0,copyHint:"create a new copy intentionally"},r)}function rf(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 nf(e,t,r){let i=e.entityRegistry.getCreateCheck(t.entityType);if(!i)return{kind:"ready"};try{return await i(t,ir(r))}catch(n){return{kind:"error",error:x(n,`Could not check the ${t.entityType}`)}}}function of(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(Jc(t))}.`,e.answerWith].join(" ")}function sf(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 Yc='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 af(e,t,r,i,n){let o=await Vg(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 cf(e,t,{source:r,retry:i},n){let o=r.uploadRef?await Xg(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=rf(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 lf(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=ef(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=nr(e.title),g=(a&&Kc(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 df(e,t,r,i){let n=await nf(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(of(n,i.source,i.several))}return{kind:"ok",value:sf(t,n)}}async function Xc(e,t,r,i,n){if(!(t.source.kind==="upload"&&t.source.transform==="preserve")){let P=je(e,t.entityType);if(P)return X(P)}let s=Bi(r.conversationId??r.channelId,t.entityType),a=await af(e,t,r,i,s);if(a.kind==="error")return a;let{source:l}=a.value,d=await cf(e,t,a.value,r);if(d.kind==="error")return d;let{content:u,upload:p}=d.value,m=p?.uploadPreserve,g=lf(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(Yc);let y=Gg(t.source,a.value,u),S=t.confirmed||m?{kind:"ok",value:f}:await df(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 tf(e,R,r);if(w.kind==="error")return w;return{kind:"ok",value:{createInput:R,confirmationSource:y,interceptor:v,eventContext:De(r),...p&&{uploadFilename:p.filename},...l.uploadRef&&{uploadId:l.uploadRef.id},...w.value&&{replacesFailed:w.value},...m&&{uploadPreserve:m}}}}async function el(e,t,r,i){let n=await uf(e,t,r,i),{uploadId:o}=t;if(o===void 0||!("success"in n)||!n.success)return n;if(!V(n.data))return n;return{...n,data:{entityType:t.createInput.entityType,...n.data,uploadId:o}}}async function uf(e,t,r,i){let{createInput:n,eventContext:o,uploadPreserve:s,replacesFailed:a}=t;if(s)return tt(e,r,{createInput:n,interceptor:void 0,replacesFailed:a,persist:()=>Qg({upload:s.upload,...n.title&&{title:n.title},...n.visibility!==void 0?{visibility:n.visibility}:{},handler:s.handler},r)});let l=await tt(e,r,{createInput:n,interceptor:t.interceptor,replacesFailed:a,persist:async(u)=>u.content?Kg(e,u,o):{success:!1,error:Yc}}),d=Bi(r.conversationId??r.channelId,n.entityType);if(d&&"success"in l&&l.success)i.clear(d);return l}async function pf(e,t,r,i,n){let o={...t.fields,...r.fields},s=await Xc(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:()=>el(e,a,i,n)}}}function mf(e){let{createInput:t,uploadPreserve:r}=e,{summary:i,preview:n}=r?Ng({...t.title&&{title:t.title},filename:r.filename,mediaType:r.mediaType,entityType:t.entityType,visibility:t.visibility}):Hg(t);return{toolName:"system_create",summary:i,completionSummary:Wg(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 tl(e){let t=Y({label:"create",requestNoun:"creation"}),r=new Ui;return{...W("create","Create a new entity from existing material. Never create a duplicate to save edits: use system_update for entities already created or imported in this conversation, even while an upload import is generating. Requires confirmation; call this tool without confirmed to request that confirmation instead of asking for plain-text approval. Use visibility shared for team/collaborator content such as a team note, restricted for private/admin-only content, and omit it for public content; keep visibility separate from exact source text. Public callers may write only public content, Trusted callers public or shared, and Admin callers all three. If the user only says 'not public' without saying team/shared or private/admin-only, ask which scope they mean. Entity-specific instructions may direct proactive capture of the user's request itself; in that case the request is concrete text and no separate save verb is required. Use system_generate for AI generation, generated images, cover images, and source-derived artifacts such as carousel/printable PDFs or OG images. If the user includes content in the same direct save request, use source.kind user-message, omitting messageId for the latest user message; that content is sufficient even when it is a short sentence or fragment after a colon or embedded in the request phrase (for example, 'Save this memo about the launch timeline'), so never ask the user to paste it again. For standalone delimiter lines, use boundaryMode lines with startAfter/endBefore set to the exact marker line text WITHOUT newline characters; the server preserves all intervening bytes, including final newlines. To save a pasted document that opens with --- frontmatter, use boundaryMode frontmatter without startAfter or endBefore: the server selects it from its opening fence, and the fences are content, never boundaries. For inline content, use literal startAfter/endBefore boundaries to exclude the save instruction. Omit boundaries only when saving the whole message. Never retype, shorten, correct, or include delimiter text in pasted source material, and never ask for a smaller copy just because it is long. For 'Save this as a note: ...', startAfter can be the exact 'Save this as a note: ' prefix. If boundaries are ambiguous, ask for clarification. If the user says save it/that/this after your immediately preceding upload summary/answer, use entityType note with source.kind prior-response unless they explicitly ask to save the uploaded file/document itself; do this even when the prior answer says there was limited readable content, and do not ask whether they meant the summary or the file after you just summarized/answered about the upload. A bare upload receipt like 'I got filename. What would you like me to do?' is not a summary/answer: for a following 'save it', preserve the latest uploaded file itself with upload transform preserve (image uploads as entityType image). Only use source.kind upload when the runtime supplies an actual upload reference/attachment, and then use it even though the file text also appears in the message; only a pasted uploaded-file transcript (for example, User uploaded a file \"name.md\": ...) with no listed upload ref is saved with source.kind user-message boundaries.",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 Qc({input:{...n,source:n.source},gate:t,prepare:(d)=>pf(e,n,d,o,r)});let a=await Xc(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:()=>mf(l),run:()=>el(e,l,o,r)})},{visibility:"trusted",sideEffects:"writes"}),modelInput:Mc(e.entityRegistry,tr(e.permissionService))}}function gf(e){let t=e.map((r)=>`"${r}"`);return t.length<=1?t.join(""):`${t.slice(0,-1).join(", ")} and ${t.at(-1)??""}`}function Zi(e){return gf(e.entries.map(({label:t})=>t))}function ff(e,t,r){let i=e.title?` "${e.title}"`:` ${e.entityType}`,n=e.from?.kind==="entity-attachment"?e.from:void 0,o=t?.usedUp?t:void 0,s=[`Entity type: ${e.entityType}`,...e.title?[`Title: ${e.title}`]:[],...r?[`Prompt: ${r}`]:[],...o?.entries.map(({entityId:a})=>`Removes: ${o.entityType}/${a}`)??[],...n?[`Source attachment: ${n.sourceEntityType}/${n.sourceEntityId} (${n.attachmentType})`]:[],...e.targetEntityType&&e.targetEntityId?[`Target: ${e.targetEntityType}/${e.targetEntityId}`]:[]];return{summary:o?`Generate${i} from ${Zi(o)}? ${o.entries.length===1?"It":"They"} will be removed.`:`Generate${i}?`,...o&&{completionSummary:`Generating${i} from ${Zi(o)}, which will be removed once it is saved.`},preview:s.join(`
|
|
83
|
-
`)}}async function hf(e,t,r,i){let n=await Promise.all(r.map((a)=>_(e.entityService,{entityType:t,identifier:a},{visibilityScope:i,logger:e.logger}))),o=n.find((a)=>!a.ok);if(o)return T(o.error,"source-not-found");let s=n.flatMap((a)=>a.ok?[{entityId:a.entity.id,label:ze(a.entity)}]:[]);return{kind:"ok",value:s.filter(({entityId:a},l)=>s.findIndex((d)=>d.entityId===a)===l)}}function il(e,t){return e.entityRegistry.getEntityTypeConfig(t).consumesSources??[]}function yf(e,t,r){if(t.kind!=="prompt"&&t.kind!=="prompt-from-source")return;let i=il(e,t.entityType);if(i.length===0)return;let n=`A ${t.entityType} is written from ${i.join(" or ")} entries`;if(t.kind==="prompt")return{success:!1,error:`${n}. Use operation.kind prompt-from-source and name the source.`,code:"unsupported-generation"};if(!i.includes(t.source.entityType))return{success:!1,error:`${n}, and '${t.source.entityType}' is not one of them.`,code:"unsupported-generation"};return B(e,t.source.entityType,"delete",r)}async function nl(e,t,r,i){let n=await _(e.entityService,{entityType:t.entityType,identifier:t.entityId},{visibilityScope:r,logger:e.logger});if(!n.ok)return T(n.error,i);return{kind:"ok",value:{...t,entityId:n.entity.id}}}async function vf(e,t,r,i){let n=await nl(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 bf(e,t,r,i,n,o){let{entityService:s,jobs:a}=e,l=Fi(ee(ol(t,i,r)),100);if(!l)return{success:!1,error:"Could not derive a slug from the provided title/prompt. Provide a 'title' with at least one URL-safe character."};let d=t.title??l,u=rl(e.entityRegistry,{entityType:t.entityType,id:l,title:d});if(!u)return{success:!1,error:`Entity type '${t.entityType}' does not support queued generation. Provide an exact source to system_create instead.`};let p;try{p=(await s.createEntity({entity:u,options:{deduplicateId:!0,...n?{eventContext:n}:{}}})).entityId}catch(f){return{success:!1,error:x(f,"Failed to persist generation stub")}}let m={entityId:p,prompt:r,...t.title&&{title:t.title},...t.sourceEntityType&&{sourceEntityType:t.sourceEntityType},...t.sourceEntityId&&{sourceEntityId:t.sourceEntityId},...t.sourceEntityIds&&{sourceEntityIds:t.sourceEntityIds},...t.targetEntityType&&{targetEntityType:t.targetEntityType},...t.targetEntityId&&{targetEntityId:t.targetEntityId}},g=e.entityRegistry.getGenerationEnqueuer(t.entityType);try{let f=g?await g(m,o):await a.enqueue({type:`${t.entityType}:generation`,data:m,toolContext:o});return{success:!0,data:{entityId:p,status:"generating",jobId:f}}}catch(f){return await s.deleteEntity({entityType:t.entityType,id:p}).catch((h)=>{e.logger.warn("Failed to remove unqueued generation stub",{entityType:t.entityType,entityId:p,error:h})}),{success:!1,error:x(f,"Failed to queue generation job")}}}function ol(e,t,r){return e.title??t??r}async function Sf(e,t,r){let i=nr(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 hf(e,t.source.entityType,[t.source.entityId,...t.additionalSourceIds??[]],r):void 0;if(l?.kind==="error")return l;let d=t.kind==="prompt-from-source"&&l?{entityType:t.source.entityType,entries:l.value,usedUp:il(e,t.entityType).includes(t.source.entityType)}:void 0,[u]=d?.entries??[];return{kind:"ok",value:{createInput:{entityType:t.entityType,...i?{title:i}:{},prompt:t.prompt??`Write a ${t.entityType} from ${d?Zi(d):""}.`,...d&&u&&{sourceEntityType:d.entityType,sourceEntityId:u.entityId,sourceEntityIds:d.entries.map(({entityId:p})=>p)}},sourceAttachment:void 0,writtenFrom:d}}}if(t.kind==="standalone-image")return{kind:"ok",value:{createInput:{entityType:"image",...i?{title:i}:{},prompt:t.prompt},sourceAttachment:void 0,writtenFrom:void 0}};if(t.kind==="cover-image"){let l=await nl(e,t.target,r,"target-not-found");if(l.kind==="error")return l;return{kind:"ok",value:{createInput:{entityType:"image",...i?{title:i}:{},prompt:t.prompt,targetEntityType:l.value.entityType,targetEntityId:l.value.entityId},sourceAttachment:void 0,writtenFrom:void 0}}}let n=await vf(e,t.source,t.attachmentType,r);if(n.kind==="error")return n;let{sourceAttachment:o,metadata:s}=n.value,a=t.replace===!0;return{kind:"ok",value:{createInput:{entityType:s.outputEntityType,...i?{title:i}:{},from:{kind:"entity-attachment",...o},...a&&{replace:a},...s.targetField&&{targetEntityType:o.sourceEntityType,targetEntityId:o.sourceEntityId}},sourceAttachment:o,writtenFrom:void 0}}}async function Rf(e,t,r){let i=t.operation,n=A(r.userPermissionLevel),o=yf(e,i,r);if(o)return X(o);let s=await Sf(e,i,n);if(s.kind==="error")return s;let{createInput:a,sourceAttachment:l,writtenFrom:d}=s.value,p="prompt"in i&&i.prompt!==void 0&&!d?.usedUp?void 0:d?.entries[0]?.entityId,m=sr(e,a.entityType,r);if(m.kind==="error")return m;let{interceptor:g}=m.value;if(!a.prompt&&!a.from)return T("Provide a generation source.");if(a.from&&!g)return T(`Entity type '${a.entityType}' does not support attachment-based generation. Use operation.kind prompt-from-source for AI-generated content based on referenced source material, or choose an entity type with an attachment provider.`,"unsupported-generation");let f=i.kind==="prompt"||i.kind==="prompt-from-source",h=g&&!f?void 0:await or(e,{entityType:a.entityType,candidateId:a.prompt?Fi(ee(ol(a,p,a.prompt)),100):a.title?ee(a.title):void 0,replace:a.replace===!0,copyHint:"generate a new copy intentionally"},r);if(h?.kind==="error")return h;return{kind:"ok",value:{createInput:a,operation:wf(i,a,l),interceptor:g,eventContext:De(r),...h?.value&&{replacesFailed:h.value},writtenFrom:d,sourceName:p}}}function wf(e,t,r){if(e.kind==="attachment"){let i=r??{sourceEntityType:e.source.entityType,sourceEntityId:e.source.entityId,attachmentType:e.attachmentType};return{kind:"attachment",source:{entityType:i.sourceEntityType,entityId:i.sourceEntityId},attachmentType:i.attachmentType,...t.title&&{title:t.title},...t.replace&&{replace:t.replace}}}if(e.kind==="cover-image")return{kind:"cover-image",target:{entityType:t.targetEntityType??e.target.entityType,entityId:t.targetEntityId??e.target.entityId},...t.title&&{title:t.title},prompt:e.prompt};if(e.kind==="standalone-image")return{kind:"standalone-image",...t.title&&{title:t.title},prompt:e.prompt};if(e.kind==="prompt-from-source")return{kind:"prompt-from-source",entityType:t.entityType,...t.title&&{title:t.title},source:{entityType:t.sourceEntityType??e.source.entityType,entityId:t.sourceEntityId??e.source.entityId},...(t.sourceEntityIds?.length??0)>1&&{additionalSourceIds:t.sourceEntityIds?.slice(1)},...e.prompt!==void 0&&{prompt:e.prompt}};return{kind:"prompt",entityType:t.entityType,...t.title&&{title:t.title},prompt:e.prompt}}function sl(e){let t=Y({label:"generate",requestNoun:"generation"});return W("generate","Generate durable content or artifacts. Requires confirmation: calling this tool without confirmed is how you request it, so when the user asks to create, write, draft, or generate new durable content without supplying final exact content, call it instead of drafting the content in chat, asking for separate prose approval, or saying 'I can generate it if you want' or 'I need to queue it first'. Critical: broad or underspecified topical generation uses operation.kind prompt with no source field, also in the same turn after an optional search finds no source; preserve the user's wording as the prompt and do not stop to ask what details to highlight. Critical: to generate from an existing source such as 'my latest blog post', resolve it with read/search/list tools unless the user gives an exact entity id in quotes, then call operation.kind prompt-from-source right away, for example { kind: 'prompt-from-source', entityType: 'newsletter', source: { entityType: 'post', entityId: '...' }, prompt: '...' }. For the latest published/blog source, use system_list on that type (blog posts: entityType post) and choose the newest candidate by publishedAt, not updated/created or semantic search order; do not stop with prose like 'I found it and can generate it' or 'if that is the one you mean.' Never invent source IDs, use brain-character/profile, uploads, filenames, guessed ids, or placeholders as source refs. Turning an existing entity into another type ('turn my note X into a post') keeps its text and is not generation: call system_create with source.kind entity, also after a search resolves it. 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.",Tc,async(r,i)=>{let n=await Rf(e,r,i);if(n.kind==="error")return n.result;let{createInput:o,operation:s,interceptor:a,eventContext:l,replacesFailed:d,writtenFrom:u,sourceName:p}=n.value;return ar({gate:t,input:r,replacesFailed:d,confirmation:()=>({toolName:"system_generate",...ff(o,u,"prompt"in s?s.prompt:void 0),args:{operation:s}}),run:()=>tt(e,i,{createInput:o,interceptor:a,replacesFailed:d,persist:async(m)=>{if(!m.prompt)return{success:!1,error:"Attachment generation is supported only for entity types that explicitly handle source-derived artifacts."};return bf(e,m,m.prompt,p,l,i)}})})},{visibility:"trusted",sideEffects:"writes"})}function al(e){let{entityService:t,entityRegistry:r,logger:i}=e,n=Y({label:"delete",requestNoun:"deletion"});return W("delete","Request entity deletion by id. Unauthorized callers get a permission error; authorized callers get confirmation first. Do not pass confirmed on the initial request. For an entity the user names, call this tool directly without searching for or reading it first. Protected identity/profile records such as brain-character and anchor-profile cannot be deleted; update them instead.",Ec,async(o,s)=>{if((s.userPermissionLevel??"public")==="public")return{success:!1,error:"Changing content requires higher permission; current permission is Public."};let a=B(e,o.entityType,"delete",s);if(a)return a;let l=je(e,o.entityType);if(l)return l;if(r.getAdapter(o.entityType).isSingleton===!0)return{success:!1,error:`${o.entityType} is a singleton entity and cannot be deleted through system tools. Update it instead.`};let d=A(s.userPermissionLevel),u=await _(t,{entityType:o.entityType,identifier:o.id},{visibilityScope:d,logger:i});if(!u.ok)return{success:!1,error:u.error};let{entity:p}=u;if(o.confirmed){let 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:x(h,"Failed to delete entity")}}return{success:!0,data:{deleted:p.id}}}let m=ze(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 cl(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 tn}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 P=!1;if(w){let L=w.oldPos-y;P=w&&0<=L&&L<s}let E=R&&R.oldPos+1<a;if(!P&&!E){m[y]=void 0;continue}if(!E||P&&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 ll extends mr{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}}var dl=new ll;function gr(e,t,r){return dl.diff(e,t,r)}var ve=c.enum(["png","jpg","jpeg","webp","gif","svg"]),pl=c.enum(["pending","draft","failed"]),ml=c.enum(["fallback","generated","owner"]),gl=c.object({title:c.string().optional(),alt:c.string().optional(),altSource:ml.optional().meta({studioWidget:"provenance"}),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:pl.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]})}}),fl=ul.extend({entityType:c.literal("image"),metadata:gl}),If=c.object({url:c.string(),alt:c.string(),title:c.string(),width:c.number(),height:c.number()});var Pf=c.object({alt:c.string().trim().min(1),altSource:c.enum(["generated","owner"])});function xf(e){let t=Pf.safeParse(e);return t.success?t.data.alt:void 0}function hl(e){return/^https?:\/\//i.test(e)}async function yl(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 it(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 nt(e){let t=it(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 Cf(e){return yl(e,"image/")}function vl(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 Tf=64;async function Ni(e){let t=await e(0,Tf),r=vl(t);if(!r)return;let i=r==="jpg"||r==="jpeg"?await Af(e):Ji(t);return{format:r,mediaType:be(r),width:i?.width??0,height:i?.height??0}}function Hi(e){return async(t,r)=>e.subarray(t,r)}function Wi(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 Ef(e){return(t,r)=>Bun.file(e).slice(t,r).bytes()}async function Af(e){let t=rt(2),r=async(i)=>i.done?i.value:r(t.next(await e(...i.value)));return r(t.next(new Uint8Array))}function*rt(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*rt(e+1);if(r===1||r>=208&&r<=215)return yield*rt(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*rt(e+2+i)}function qi(e){return Ji(Buffer.from(e,"base64"))}function Ji(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=rt(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 jf(e){let t=fr(e);if(!t)throw Error(`Unsupported image format: ${e}`);return t}function bl(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 Df(e){if(e===""||ot.safeParse(e).success)return{};let{format:t,base64:r}=nt(e),i=qi(r);return{format:jf(t),width:i?.width??0,height:i?.height??0}}function Gi(e){let{title:t,alt:r,...i}=bl(e);return{entityType:"image",content:e.asset.ref,metadata:{title:t,alt:r,...e.description,sizeBytes:e.asset.sizeBytes,...i}}}function zf(e){return{entityType:"image",content:"",metadata:bl(e)}}function OT(e){return Rl(e,{skipInvalid:!0,noRefs:!0,sortKeys:!0})}function wl(e){return Sl(e)}async function Pl(e,t){let r=ot.safeParse(t.content);if(!r.success){let i=it(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 Il(e,r.data),mediaType:Of(t)}}async function xl(e,t){if(!ot.safeParse(t.content).success)return it(t.content)?t.content:void 0;let r=await Pl(e,t);return r&&`data:${r.mediaType};base64,${r.bytes.toString("base64")}`}function Of(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 Mf=c.record(c.string(),c.unknown());function Cl(e,t){let r=Me.exec(e.content);if(!r?.[1])return;try{let i=Mf.safeParse(wl(r[1]));if(i.success){let n=i.data[t];return typeof n==="string"?n:void 0}}catch{return}return}function Lf(e){return Cl(e,"coverImageId")}function Uf(e){return Cl(e,"ogImageId")}function Qi(e,t){return{...e,content:st(e.content,"coverImageId",t)}}function Ki(e,t){return{...e,content:st(e.content,"ogImageId",t)}}var Vi=Tl();function Bf(e,t){let r=Vi.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?Vi.stringify(r):e}function $f(e){let t=[],r=Vi.parse(e);return hr(r,"image",(i)=>{t.push({url:i.url,alt:i.alt??"",title:i.title??void 0})}),t}var Xi=26214400,_f=["png","jpg","gif","webp"].map(be);async function Zf(e,t,r){let{read:i,bytes:n}=Ff(t),o=await Ni(i);if(!o)throw Error("Unsupported image format: not a PNG, JPEG, GIF or WebP");let s=await e.stageAsset(n,{maxBytes:Xi});return{stagedAsset:s,entity:Gi({...r,asset:s,description:o})}}function Ff(e){if("bytes"in e)return{read:Hi(e.bytes),bytes:e.bytes};let{base64:t}=nt(e.dataUrl);return{read:Wi(t),bytes:Yi(t)}}var Hf="6b7fa434f92a8b80aab02d9bf1a12e49ffcae424e4013a1c4f68b67e3d2bbcd0";function Wf(e,t){return(t==="pending"||t==="failed")&&e===Hf}var El=400;function yr(e,t,r){if(r===null)return!Object.hasOwn(e,t);return Object.hasOwn(e,t)&&tn(e[t],r)}function Le(e,t){return new Set([...t.getFrontmatterExtensions(e).flatMap((r)=>Object.keys(r.shape)),...t.getGroupings().filter((r)=>r.types.includes(e)).map((r)=>r.field)])}function qf(e,t,r){if(r.has(t))return vr(e.content).frontmatter[t];return t==="visibility"?e.visibility:e.metadata[t]}function Ol(e,t,r){let i=Le(e.entityType,r),n=new Set(Object.keys(r.getAdapter(e.entityType).frontmatterSchema?.shape??{}).filter((s)=>!i.has(s))),o=Object.fromEntries(Object.entries(vr(t).frontmatter).filter(([s])=>!n.has(s)));return Object.keys(o).length>0?{...e,content:dr(o,e.content)}:e}function Ml(e,t,r){let{visibility:i,coverImageId:n,ogImageId:o,...s}=t,a=i===void 0?e.visibility:Dl.parse(i),l=Object.hasOwn(t,"coverImageId")?Qi(e,typeof n==="string"?n:null):e,d=Object.hasOwn(t,"ogImageId")?Ki(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=Le(e.entityType,r),g=!1;for(let[f,h]of Object.entries(t)){if(!m.has(f))continue;p.content=st(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 Jf(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(tn(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 Gf=new Set(["visibility","coverImageId","ogImageId"]),Qf=c.record(c.string(),c.unknown());function Kf(e,t,r,i){if(t.kind!=="fields")return;let n=t.fields,o=r.getEffectiveFrontmatterSchema(e.entityType);if(!o)return;let s=Le(e.entityType,r),a=Object.keys(n).filter((h)=>s.has(h)),l;try{if(l=Ml(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:x(h,"Invalid field update")}}let d=r.getAdapter(e.entityType).metadataFromFrontmatter===!0,u=Object.keys(n).filter((h)=>!s.has(h)&&(!Gf.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),Qf)}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 Ll(e,t,r){let i=Me.exec(e.content)?.[0];if(i===void 0||!t.trim()||Me.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 Vf(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&&!Me.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 Yf(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 Xf(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 Ul(e,t,r){let i=Le(e.entityType,r);if(t.kind==="fields")return Object.entries(t.fields).map(([a,l])=>{let d=qf(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(`
|
|
82
|
+
`)}}function Wg(e){let t=e.title?` "${e.title}"`:"";return`Saved ${e.entityType}${t}.`}function qg(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 Jg(e,t,r){let i=await _(e.entityService,{entityType:t.entityType,identifier:t.entityId},{visibilityScope:A(r.userPermissionLevel),logger:e.logger,label:"Source entity"});if(!i.ok)return T(i.error);let{entity:n}=i,o=ze(n.content,{trim:!0,keepEmptyBlock:!0});if(!o)return T(`Source entity ${n.entityType}/${n.id} has no text to use.`);let s=n.metadata.title;return{kind:"ok",value:{ref:{entityType:n.entityType,entityId:n.id},content:o,title:typeof s==="string"&&s.trim()?s:void 0,visibility:n.visibility}}}function Gg(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 dr(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 Qg(e,t){let r=nr(t);return e.handler({upload:e.upload,...e.title&&{title:e.title},...e.visibility!==void 0?{visibility:e.visibility}:{}},r)}function Kg(e,t,r){let i=Me(t),n=i.content.match(/^#\s+(.+)$/m)?.[1]?.trim(),o=e.fields?.title!==void 0||i.frontmatter.title!==void 0||n!==void 0&&n===e.title?.trim(),s=r&&!o?e.title:void 0,a={...s!==void 0&&{title:s},...e.fields};return Object.keys(a).length>0?ur(a,t):t}async function Vg(e,t,r){let{entityService:i,entityRegistry:n}=e,o=ee(t.title??`${t.entityType}-${Date.now()}`),s=n.getEffectiveFrontmatterSchema(t.entityType),a=t.content!==void 0&&$c(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:Kg(t,t.content,"title"in(s?.shape??{})),...t.visibility!==void 0?{visibility:t.visibility}:{}},options:l}):await i.createEntity({entity:{id:o,entityType:t.entityType,content:t.content??"",metadata:{title:t.title??o},...t.visibility!==void 0?{visibility:t.visibility}:{},created:new Date().toISOString(),updated:new Date().toISOString()},options:l})).entityId,status:"created"}}}catch(l){return{success:!1,error:x(l,"Failed to create entity")}}}async function Yg(e,t,r){let{content:i,url:n,from:o,uploadRef:s,conversationMessageRef:a,entityRef:l,transform:d}=qg(t.source),u=l?await Jg(e,l,r):void 0;if(u?.kind==="error")return u;let p=a?await lr(e,a,r,{confirmed:t.confirmed===!0}):void 0;if(p&&!p.success)return X(p);let m=p?.success===!0?p.content:u?.value.content??i;if(d==="extract-markdown"&&!s)return T('Transform "extract-markdown" requires an upload ref.');if(!m&&!n&&!o)return T('Provide `source` with kind "user-message", "text", "url", "prior-response", "upload", or "entity". Use system_generate for generated content or artifacts.');return{kind:"ok",value:{content:m,url:n,from:o,uploadRef:s,transform:d,resolvedMessageId:p?.success===!0?p.messageId:void 0,resolvedUserSource:p?.success===!0?p.source:void 0,entitySource:u?.value}}}async function Xg(e,t){if(!_i(t.mediaType))return;let{content:r}=await e.runtimeUploads.scoped(Ce).read(t.id);return bc(r).toString("utf8")}async function ef(e,t,r){if(!await _c(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(Ce).readRecord(t.uploadRef.id),o=t.transform==="extract-markdown"?await Xg(e,{id:t.uploadRef.id,mediaType:n.mediaType}):void 0}catch{return T("Upload ref not found")}let s=Vc({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=_i(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 tf(e,t,r){let i=t?mr(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(!pr(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 rf(e,t,r){return sr(e,{entityType:t.entityType,candidateId:t.title?ee(t.title):void 0,replace:t.replace===!0,copyHint:"create a new copy intentionally"},r)}function nf(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 of(e,t,r){let i=e.entityRegistry.getCreateCheck(t.entityType);if(!i)return{kind:"ready"};try{return await i(t,nr(r))}catch(n){return{kind:"error",error:x(n,`Could not check the ${t.entityType}`)}}}function sf(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(Jc(t))}.`,e.answerWith].join(" ")}function af(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 Yc='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 cf(e,t,r,i,n){let o=await Yg(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 lf(e,t,{source:r,retry:i},n){let o=r.uploadRef?await ef(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=nf(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 df(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=tf(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=or(e.title),g=(a&&Kc(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 uf(e,t,r,i){let n=await of(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(sf(n,i.source,i.several))}return{kind:"ok",value:af(t,n)}}async function Xc(e,t,r,i,n){if(!(t.source.kind==="upload"&&t.source.transform==="preserve")){let P=je(e,t.entityType);if(P)return X(P)}let s=Bi(r.conversationId??r.channelId,t.entityType),a=await cf(e,t,r,i,s);if(a.kind==="error")return a;let{source:l}=a.value,d=await lf(e,t,a.value,r);if(d.kind==="error")return d;let{content:u,upload:p}=d.value,m=p?.uploadPreserve,g=df(t,l,d.value,r);if(g.kind==="error")return g;let f=g.value,h=ar(e,f.entityType,r);if(h.kind==="error")return h;let{interceptor:v}=h.value;if(!f.content&&!v&&!m)return T(Yc);let y=Gg(t.source,a.value,u),S=t.confirmed||m?{kind:"ok",value:f}:await uf(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 rf(e,R,r);if(w.kind==="error")return w;return{kind:"ok",value:{createInput:R,confirmationSource:y,interceptor:v,eventContext:De(r),...p&&{uploadFilename:p.filename},...l.uploadRef&&{uploadId:l.uploadRef.id},...w.value&&{replacesFailed:w.value},...m&&{uploadPreserve:m}}}}async function el(e,t,r,i){let n=await pf(e,t,r,i),{uploadId:o}=t;if(o===void 0||!("success"in n)||!n.success)return n;if(!V(n.data))return n;return{...n,data:{entityType:t.createInput.entityType,...n.data,uploadId:o}}}async function pf(e,t,r,i){let{createInput:n,eventContext:o,uploadPreserve:s,replacesFailed:a}=t;if(s)return rt(e,r,{createInput:n,interceptor:void 0,replacesFailed:a,persist:()=>Qg({upload:s.upload,...n.title&&{title:n.title},...n.visibility!==void 0?{visibility:n.visibility}:{},handler:s.handler},r)});let l=await rt(e,r,{createInput:n,interceptor:t.interceptor,replacesFailed:a,persist:async(u)=>u.content?Vg(e,u,o):{success:!1,error:Yc}}),d=Bi(r.conversationId??r.channelId,n.entityType);if(d&&"success"in l&&l.success)i.clear(d);return l}async function mf(e,t,r,i,n){let o={...t.fields,...r.fields},s=await Xc(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:()=>el(e,a,i,n)}}}function gf(e){let{createInput:t,uploadPreserve:r}=e,{summary:i,preview:n}=r?Ng({...t.title&&{title:t.title},filename:r.filename,mediaType:r.mediaType,entityType:t.entityType,visibility:t.visibility}):Hg(t);return{toolName:"system_create",summary:i,completionSummary:Wg(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 tl(e){let t=Y({label:"create",requestNoun:"creation"}),r=new Ui;return{...W("create","Create a new entity from existing material. Never create a duplicate to save edits: use system_update for entities already created or imported in this conversation, even while an upload import is generating. Requires confirmation; call this tool without confirmed to request that confirmation instead of asking for plain-text approval. Use visibility shared for team/collaborator content such as a team note, restricted for private/admin-only content, and omit it for public content; keep visibility separate from exact source text. Public callers may write only public content, Trusted callers public or shared, and Admin callers all three. If the user only says 'not public' without saying team/shared or private/admin-only, ask which scope they mean. Entity-specific instructions may direct proactive capture of the user's request itself; in that case the request is concrete text and no separate save verb is required. Use system_generate for AI generation, generated images, cover images, and source-derived artifacts such as carousel/printable PDFs or OG images. If the user includes content in the same direct save request, use source.kind user-message, omitting messageId for the latest user message; that content is sufficient even when it is a short sentence or fragment after a colon or embedded in the request phrase (for example, 'Save this memo about the launch timeline'), so never ask the user to paste it again. For standalone delimiter lines, use boundaryMode lines with startAfter/endBefore set to the exact marker line text WITHOUT newline characters; the server preserves all intervening bytes, including final newlines. To save a pasted document that opens with --- frontmatter, use boundaryMode frontmatter without startAfter or endBefore: the server selects it from its opening fence, and the fences are content, never boundaries. For inline content, use literal startAfter/endBefore boundaries to exclude the save instruction. Omit boundaries only when saving the whole message. Never retype, shorten, correct, or include delimiter text in pasted source material, and never ask for a smaller copy just because it is long. For 'Save this as a note: ...', startAfter can be the exact 'Save this as a note: ' prefix. If boundaries are ambiguous, ask for clarification. If the user says save it/that/this after your immediately preceding upload summary/answer, use entityType note with source.kind prior-response unless they explicitly ask to save the uploaded file/document itself; do this even when the prior answer says there was limited readable content, and do not ask whether they meant the summary or the file after you just summarized/answered about the upload. A bare upload receipt like 'I got filename. What would you like me to do?' is not a summary/answer: for a following 'save it', preserve the latest uploaded file itself with upload transform preserve (image uploads as entityType image). Only use source.kind upload when the runtime supplies an actual upload reference/attachment, and then use it even though the file text also appears in the message; only a pasted uploaded-file transcript (for example, User uploaded a file \"name.md\": ...) with no listed upload ref is saved with source.kind user-message boundaries.",Xt,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)=>tr(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 Qc({input:{...n,source:n.source},gate:t,prepare:(d)=>mf(e,n,d,o,r)});let a=await Xc(e,n,o,r);if(a.kind==="error")return a.result;let l=a.value;return cr({gate:t,input:n,replacesFailed:l.replacesFailed,confirmation:()=>gf(l),run:()=>el(e,l,o,r)})},{visibility:"trusted",sideEffects:"writes"}),modelInput:Mc(e.entityRegistry,rr(e.permissionService))}}function ff(e){let t=e.map((r)=>`"${r}"`);return t.length<=1?t.join(""):`${t.slice(0,-1).join(", ")} and ${t.at(-1)??""}`}function Zi(e){return ff(e.entries.map(({label:t})=>t))}function hf(e,t,r){let i=e.title?` "${e.title}"`:` ${e.entityType}`,n=e.from?.kind==="entity-attachment"?e.from:void 0,o=t?.usedUp?t:void 0,s=[`Entity type: ${e.entityType}`,...e.title?[`Title: ${e.title}`]:[],...r?[`Prompt: ${r}`]:[],...o?.entries.map(({entityId:a})=>`Removes: ${o.entityType}/${a}`)??[],...n?[`Source attachment: ${n.sourceEntityType}/${n.sourceEntityId} (${n.attachmentType})`]:[],...e.targetEntityType&&e.targetEntityId?[`Target: ${e.targetEntityType}/${e.targetEntityId}`]:[]];return{summary:o?`Generate${i} from ${Zi(o)}? ${o.entries.length===1?"It":"They"} will be removed.`:`Generate${i}?`,...o&&{completionSummary:`Generating${i} from ${Zi(o)}, which will be removed once it is saved.`},preview:s.join(`
|
|
83
|
+
`)}}async function yf(e,t,r,i){let n=await Promise.all(r.map((a)=>_(e.entityService,{entityType:t,identifier:a},{visibilityScope:i,logger:e.logger}))),o=n.find((a)=>!a.ok);if(o)return T(o.error,"source-not-found");let s=n.flatMap((a)=>a.ok?[{entityId:a.entity.id,label:Oe(a.entity)}]:[]);return{kind:"ok",value:s.filter(({entityId:a},l)=>s.findIndex((d)=>d.entityId===a)===l)}}function il(e,t){return e.entityRegistry.getEntityTypeConfig(t).consumesSources??[]}function vf(e,t,r){if(t.kind!=="prompt"&&t.kind!=="prompt-from-source")return;let i=il(e,t.entityType);if(i.length===0)return;let n=`A ${t.entityType} is written from ${i.join(" or ")} entries`;if(t.kind==="prompt")return{success:!1,error:`${n}. Use operation.kind prompt-from-source and name the source.`,code:"unsupported-generation"};if(!i.includes(t.source.entityType))return{success:!1,error:`${n}, and '${t.source.entityType}' is not one of them.`,code:"unsupported-generation"};return B(e,t.source.entityType,"delete",r)}async function nl(e,t,r,i){let n=await _(e.entityService,{entityType:t.entityType,identifier:t.entityId},{visibilityScope:r,logger:e.logger});if(!n.ok)return T(n.error,i);return{kind:"ok",value:{...t,entityId:n.entity.id}}}async function bf(e,t,r,i){let n=await nl(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 Sf(e,t,r,i,n,o){let{entityService:s,jobs:a}=e,l=Fi(ee(ol(t,i,r)),100);if(!l)return{success:!1,error:"Could not derive a slug from the provided title/prompt. Provide a 'title' with at least one URL-safe character."};let d=t.title??l,u=rl(e.entityRegistry,{entityType:t.entityType,id:l,title:d});if(!u)return{success:!1,error:`Entity type '${t.entityType}' does not support queued generation. Provide an exact source to system_create instead.`};let p;try{p=(await s.createEntity({entity:u,options:{deduplicateId:!0,...n?{eventContext:n}:{}}})).entityId}catch(f){return{success:!1,error:x(f,"Failed to persist generation stub")}}let m={entityId:p,prompt:r,...t.title&&{title:t.title},...t.sourceEntityType&&{sourceEntityType:t.sourceEntityType},...t.sourceEntityId&&{sourceEntityId:t.sourceEntityId},...t.sourceEntityIds&&{sourceEntityIds:t.sourceEntityIds},...t.targetEntityType&&{targetEntityType:t.targetEntityType},...t.targetEntityId&&{targetEntityId:t.targetEntityId}},g=e.entityRegistry.getGenerationEnqueuer(t.entityType);try{let f=g?await g(m,o):await a.enqueue({type:`${t.entityType}:generation`,data:m,toolContext:o});return{success:!0,data:{entityId:p,status:"generating",jobId:f}}}catch(f){return await s.deleteEntity({entityType:t.entityType,id:p}).catch((h)=>{e.logger.warn("Failed to remove unqueued generation stub",{entityType:t.entityType,entityId:p,error:h})}),{success:!1,error:x(f,"Failed to queue generation job")}}}function ol(e,t,r){return e.title??t??r}async function Rf(e,t,r){let i=or(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 yf(e,t.source.entityType,[t.source.entityId,...t.additionalSourceIds??[]],r):void 0;if(l?.kind==="error")return l;let d=t.kind==="prompt-from-source"&&l?{entityType:t.source.entityType,entries:l.value,usedUp:il(e,t.entityType).includes(t.source.entityType)}:void 0,[u]=d?.entries??[];return{kind:"ok",value:{createInput:{entityType:t.entityType,...i?{title:i}:{},prompt:t.prompt??`Write a ${t.entityType} from ${d?Zi(d):""}.`,...d&&u&&{sourceEntityType:d.entityType,sourceEntityId:u.entityId,sourceEntityIds:d.entries.map(({entityId:p})=>p)}},sourceAttachment:void 0,writtenFrom:d}}}if(t.kind==="standalone-image")return{kind:"ok",value:{createInput:{entityType:"image",...i?{title:i}:{},prompt:t.prompt},sourceAttachment:void 0,writtenFrom:void 0}};if(t.kind==="cover-image"){let l=await nl(e,t.target,r,"target-not-found");if(l.kind==="error")return l;return{kind:"ok",value:{createInput:{entityType:"image",...i?{title:i}:{},prompt:t.prompt,targetEntityType:l.value.entityType,targetEntityId:l.value.entityId},sourceAttachment:void 0,writtenFrom:void 0}}}let n=await bf(e,t.source,t.attachmentType,r);if(n.kind==="error")return n;let{sourceAttachment:o,metadata:s}=n.value,a=t.replace===!0;return{kind:"ok",value:{createInput:{entityType:s.outputEntityType,...i?{title:i}:{},from:{kind:"entity-attachment",...o},...a&&{replace:a},...s.targetField&&{targetEntityType:o.sourceEntityType,targetEntityId:o.sourceEntityId}},sourceAttachment:o,writtenFrom:void 0}}}async function wf(e,t,r){let i=t.operation,n=A(r.userPermissionLevel),o=vf(e,i,r);if(o)return X(o);let s=await Rf(e,i,n);if(s.kind==="error")return s;let{createInput:a,sourceAttachment:l,writtenFrom:d}=s.value,p="prompt"in i&&i.prompt!==void 0&&!d?.usedUp?void 0:d?.entries[0]?.entityId,m=ar(e,a.entityType,r);if(m.kind==="error")return m;let{interceptor:g}=m.value;if(!a.prompt&&!a.from)return T("Provide a generation source.");if(a.from&&!g)return T(`Entity type '${a.entityType}' does not support attachment-based generation. Use operation.kind prompt-from-source for AI-generated content based on referenced source material, or choose an entity type with an attachment provider.`,"unsupported-generation");let f=i.kind==="prompt"||i.kind==="prompt-from-source",h=g&&!f?void 0:await sr(e,{entityType:a.entityType,candidateId:a.prompt?Fi(ee(ol(a,p,a.prompt)),100):a.title?ee(a.title):void 0,replace:a.replace===!0,copyHint:"generate a new copy intentionally"},r);if(h?.kind==="error")return h;return{kind:"ok",value:{createInput:a,operation:If(i,a,l),interceptor:g,eventContext:De(r),...h?.value&&{replacesFailed:h.value},writtenFrom:d,sourceName:p}}}function If(e,t,r){if(e.kind==="attachment"){let i=r??{sourceEntityType:e.source.entityType,sourceEntityId:e.source.entityId,attachmentType:e.attachmentType};return{kind:"attachment",source:{entityType:i.sourceEntityType,entityId:i.sourceEntityId},attachmentType:i.attachmentType,...t.title&&{title:t.title},...t.replace&&{replace:t.replace}}}if(e.kind==="cover-image")return{kind:"cover-image",target:{entityType:t.targetEntityType??e.target.entityType,entityId:t.targetEntityId??e.target.entityId},...t.title&&{title:t.title},prompt:e.prompt};if(e.kind==="standalone-image")return{kind:"standalone-image",...t.title&&{title:t.title},prompt:e.prompt};if(e.kind==="prompt-from-source")return{kind:"prompt-from-source",entityType:t.entityType,...t.title&&{title:t.title},source:{entityType:t.sourceEntityType??e.source.entityType,entityId:t.sourceEntityId??e.source.entityId},...(t.sourceEntityIds?.length??0)>1&&{additionalSourceIds:t.sourceEntityIds?.slice(1)},...e.prompt!==void 0&&{prompt:e.prompt}};return{kind:"prompt",entityType:t.entityType,...t.title&&{title:t.title},prompt:e.prompt}}function sl(e){let t=Y({label:"generate",requestNoun:"generation"});return W("generate","Generate durable content or artifacts. Requires confirmation: calling this tool without confirmed is how you request it, so when the user asks to create, write, draft, or generate new durable content without supplying final exact content, call it instead of drafting the content in chat, asking for separate prose approval, or saying 'I can generate it if you want' or 'I need to queue it first'. Critical: broad or underspecified topical generation uses operation.kind prompt with no source field, also in the same turn after an optional search finds no source; preserve the user's wording as the prompt and do not stop to ask what details to highlight. Critical: to generate from an existing source such as 'my latest blog post', resolve it with read/search/list tools unless the user gives an exact entity id in quotes, then call operation.kind prompt-from-source right away, for example { kind: 'prompt-from-source', entityType: 'newsletter', source: { entityType: 'post', entityId: '...' }, prompt: '...' }. For the latest published/blog source, use system_list on that type (blog posts: entityType post) and choose the newest candidate by publishedAt, not updated/created or semantic search order; do not stop with prose like 'I found it and can generate it' or 'if that is the one you mean.' Never invent source IDs, use brain-character/profile, uploads, filenames, guessed ids, or placeholders as source refs. Turning an existing entity into another type ('turn my note X into a post') keeps its text and is not generation: call system_create with source.kind entity, also after a search resolves it. 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.",Tc,async(r,i)=>{let n=await wf(e,r,i);if(n.kind==="error")return n.result;let{createInput:o,operation:s,interceptor:a,eventContext:l,replacesFailed:d,writtenFrom:u,sourceName:p}=n.value;return cr({gate:t,input:r,replacesFailed:d,confirmation:()=>({toolName:"system_generate",...hf(o,u,"prompt"in s?s.prompt:void 0),args:{operation:s}}),run:()=>rt(e,i,{createInput:o,interceptor:a,replacesFailed:d,persist:async(m)=>{if(!m.prompt)return{success:!1,error:"Attachment generation is supported only for entity types that explicitly handle source-derived artifacts."};return Sf(e,m,m.prompt,p,l,i)}})})},{visibility:"trusted",sideEffects:"writes"})}function al(e){let{entityService:t,entityRegistry:r,logger:i}=e,n=Y({label:"delete",requestNoun:"deletion"});return W("delete","Request entity deletion by id. Unauthorized callers get a permission error; authorized callers get confirmation first. Do not pass confirmed on the initial request. For an entity the user names, call this tool directly without searching for or reading it first. Protected identity/profile records such as brain-character and anchor-profile cannot be deleted; update them instead.",Ec,async(o,s)=>{if((s.userPermissionLevel??"public")==="public")return{success:!1,error:"Changing content requires higher permission; current permission is Public."};let a=B(e,o.entityType,"delete",s);if(a)return a;let l=je(e,o.entityType);if(l)return l;if(r.getAdapter(o.entityType).isSingleton===!0)return{success:!1,error:`${o.entityType} is a singleton entity and cannot be deleted through system tools. Update it instead.`};let d=A(s.userPermissionLevel),u=await _(t,{entityType:o.entityType,identifier:o.id},{visibilityScope:d,logger:i});if(!u.ok)return{success:!1,error:u.error};let{entity:p}=u;if(o.confirmed){let 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:x(h,"Failed to delete entity")}}return{success:!0,data:{deleted:p.id}}}let m=Oe(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 cl(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 tn}from"util";class gr{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 P=!1;if(w){let L=w.oldPos-y;P=w&&0<=L&&L<s}let E=R&&R.oldPos+1<a;if(!P&&!E){m[y]=void 0;continue}if(!E||P&&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 ll extends gr{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}}var dl=new ll;function fr(e,t,r){return dl.diff(e,t,r)}var ve=c.enum(["png","jpg","jpeg","webp","gif","svg"]),pl=c.enum(["pending","draft","failed"]),ml=c.enum(["fallback","generated","owner"]),gl=c.object({title:c.string().optional(),alt:c.string().optional(),altSource:ml.optional().meta({studioWidget:"provenance"}),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:pl.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]})}}),fl=ul.extend({entityType:c.literal("image"),metadata:gl}),Pf=c.object({url:c.string(),alt:c.string(),title:c.string(),width:c.number(),height:c.number()});var xf=c.object({alt:c.string().trim().min(1),altSource:c.enum(["generated","owner"])});function Cf(e){let t=xf.safeParse(e);return t.success?t.data.alt:void 0}function hl(e){return/^https?:\/\//i.test(e)}async function yl(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 nt(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 ot(e){let t=nt(e);if(!t)throw Error("Invalid image data URL");return t}function hr(e){let t=e.toLowerCase(),r=t==="svg+xml"?"svg":t,i=ve.safeParse(r);return i.success?i.data:null}async function Tf(e){return yl(e,"image/")}function vl(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 Ef=64;async function Ni(e){let t=await e(0,Ef),r=vl(t);if(!r)return;let i=r==="jpg"||r==="jpeg"?await kf(e):Ji(t);return{format:r,mediaType:be(r),width:i?.width??0,height:i?.height??0}}function Hi(e){return async(t,r)=>e.subarray(t,r)}function Wi(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 Af(e){return(t,r)=>Bun.file(e).slice(t,r).bytes()}async function kf(e){let t=it(2),r=async(i)=>i.done?i.value:r(t.next(await e(...i.value)));return r(t.next(new Uint8Array))}function*it(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*it(e+1);if(r===1||r>=208&&r<=215)return yield*it(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*it(e+2+i)}function qi(e){return Ji(Buffer.from(e,"base64"))}function Ji(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=it(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 Df(e){let t=hr(e);if(!t)throw Error(`Unsupported image format: ${e}`);return t}function bl(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 Of(e){if(e===""||st.safeParse(e).success)return{};let{format:t,base64:r}=ot(e),i=qi(r);return{format:Df(t),width:i?.width??0,height:i?.height??0}}function Gi(e){let{title:t,alt:r,...i}=bl(e);return{entityType:"image",content:e.asset.ref,metadata:{title:t,alt:r,...e.description,sizeBytes:e.asset.sizeBytes,...i}}}function zf(e){return{entityType:"image",content:"",metadata:bl(e)}}function MT(e){return Rl(e,{skipInvalid:!0,noRefs:!0,sortKeys:!0})}function wl(e){return Sl(e)}async function Pl(e,t){let r=st.safeParse(t.content);if(!r.success){let i=nt(t.content);if(!i)return;let n=hr(i.format);return{bytes:Buffer.from(i.base64,"base64"),mediaType:n?be(n):`image/${i.format}`}}return{bytes:await Il(e,r.data),mediaType:Mf(t)}}async function xl(e,t){if(!st.safeParse(t.content).success)return nt(t.content)?t.content:void 0;let r=await Pl(e,t);return r&&`data:${r.mediaType};base64,${r.bytes.toString("base64")}`}function Mf(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 Lf=c.record(c.string(),c.unknown());function Cl(e,t){let r=Le.exec(e.content);if(!r?.[1])return;try{let i=Lf.safeParse(wl(r[1]));if(i.success){let n=i.data[t];return typeof n==="string"?n:void 0}}catch{return}return}function Uf(e){return Cl(e,"coverImageId")}function Bf(e){return Cl(e,"ogImageId")}function Qi(e,t){return{...e,content:at(e.content,"coverImageId",t)}}function Ki(e,t){return{...e,content:at(e.content,"ogImageId",t)}}var Vi=Tl();function $f(e,t){let r=Vi.parse(e),i=new Map;yr(r,"definition",(o)=>{if(!i.has(o.identifier))i.set(o.identifier,o)});let n=new Set;return yr(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?Vi.stringify(r):e}function _f(e){let t=[],r=Vi.parse(e);return yr(r,"image",(i)=>{t.push({url:i.url,alt:i.alt??"",title:i.title??void 0})}),t}var Xi=26214400,Zf=["png","jpg","gif","webp"].map(be);async function Ff(e,t,r){let{read:i,bytes:n}=Nf(t),o=await Ni(i);if(!o)throw Error("Unsupported image format: not a PNG, JPEG, GIF or WebP");let s=await e.stageAsset(n,{maxBytes:Xi});return{stagedAsset:s,entity:Gi({...r,asset:s,description:o})}}function Nf(e){if("bytes"in e)return{read:Hi(e.bytes),bytes:e.bytes};let{base64:t}=ot(e.dataUrl);return{read:Wi(t),bytes:Yi(t)}}var Wf="6b7fa434f92a8b80aab02d9bf1a12e49ffcae424e4013a1c4f68b67e3d2bbcd0";function qf(e,t){return(t==="pending"||t==="failed")&&e===Wf}var El=400;function vr(e,t,r){if(r===null)return!Object.hasOwn(e,t);return Object.hasOwn(e,t)&&tn(e[t],r)}function Ue(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 Jf(e,t,r){if(r.has(t))return Me(e.content).frontmatter[t];return t==="visibility"?e.visibility:e.metadata[t]}function zl(e,t,r){let i=Ue(e.entityType,r),n=new Set(Object.keys(r.getAdapter(e.entityType).frontmatterSchema?.shape??{}).filter((s)=>!i.has(s))),o=Object.fromEntries(Object.entries(Me(t).frontmatter).filter(([s])=>!n.has(s)));return Object.keys(o).length>0?{...e,content:ur(o,e.content)}:e}function Ml(e,t,r){let{visibility:i,coverImageId:n,ogImageId:o,...s}=t,a=i===void 0?e.visibility:Dl.parse(i),l=Object.hasOwn(t,"coverImageId")?Qi(e,typeof n==="string"?n:null):e,d=Object.hasOwn(t,"ogImageId")?Ki(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=Ue(e.entityType,r),g=!1;for(let[f,h]of Object.entries(t)){if(!m.has(f))continue;p.content=at(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 Gf(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(tn(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:mr(t)??e.visibility}}var Qf=new Set(["visibility","coverImageId","ogImageId"]),Kf=c.record(c.string(),c.unknown());function Vf(e,t,r,i){if(t.kind!=="fields")return;let n=t.fields,o=r.getEffectiveFrontmatterSchema(e.entityType);if(!o)return;let s=Ue(e.entityType,r),a=Object.keys(n).filter((h)=>s.has(h)),l;try{if(l=Ml(e,n,r),a.length>0){let h=r.validateEntity(e.entityType,l),v=i.serializeEntity(h),y=Me(v).frontmatter,S=i.deserializeEntity(v,e.entityType).metadata??{};for(let R of a){let w=n[R];if(!vr(y,R,w)||!vr(S,R,w))return{success:!1,error:`The requested ${R} value would not survive frontmatter persistence.`}}}}catch(h){return{success:!1,error:x(h,"Invalid field update")}}let d=r.getAdapter(e.entityType).metadataFromFrontmatter===!0,u=Object.keys(n).filter((h)=>!s.has(h)&&(!Qf.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(!vr(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),Kf)}catch{if(g.length===0)return}if(h){for(let v of f)if(!vr(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 Ll(e,t,r){let i=Le.exec(e.content)?.[0];if(i===void 0||!t.trim()||Le.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 Yf(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&&!Le.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 Xf(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 eh(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 Ul(e,t,r){let i=Ue(e.entityType,r);if(t.kind==="fields")return Object.entries(t.fields).map(([a,l])=>{let d=Jf(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
|
-
`),s=
|
|
87
|
-
`)}function Bl(e,t,r,i){return
|
|
88
|
-
`)}function
|
|
86
|
+
`),s=fr(n,o,{maxEditLength:El});if(!s)return`Full content replacement (line diff omitted: more than ${El} changed lines).`;return s.filter((a)=>a.added||a.removed).flatMap((a)=>a.value.map((l)=>`${a.added?"+":"-"} ${l}`)).join(`
|
|
87
|
+
`)}function Bl(e,t,r,i){return Vf(e,t,r,i)??Yf(e.entityType,t,r)??Xf(e.entityType,t,r)}function $l(e,t,r){return Ol(e.entityType,e.metadata.status,eh(e,t,r),r)==="non-publish"?"update":"publish"}function _l(e,t,r){return t.kind==="content"?Gf(e,t.content,r):Ml(e,t.fields,r)}var Al=5,kl=160;function th(e){return e.length>kl?`${e.slice(0,kl)}\u2026`:e}function rh(e){if(e===void 0)return"(removed)";return typeof e==="string"?e:JSON.stringify(e)}function jl(e){return e.trim().length>0}function en(e,t){if(t.length===0)return;let r=t.length-Al;return[e,...t.slice(0,Al).map((i)=>`> ${th(i)}`),...r>0?[`\u2026 and ${r} more changed lines`]:[]].join(`
|
|
88
|
+
`)}function ih(e,t){return[...new Set([...Object.keys(e.metadata),...Object.keys(t.metadata)])].filter((r)=>!tn(e.metadata[r],t.metadata[r])).map((r)=>`${r}: ${rh(t.metadata[r])}`)}function Zl(e,t){if(t.content===e.content)return en("Stored now:",ih(e,t));let r=fr(e.content.split(`
|
|
89
89
|
`),t.content.split(`
|
|
90
|
-
`)),i=r.filter((n)=>n.added).flatMap((n)=>n.value).filter(jl);if(i.length>0)return en("Stored now:",i);return en("No longer stored:",r.filter((n)=>n.removed).flatMap((n)=>n.value).filter(jl))}function Se(e){return{success:!1,error:e}}async function
|
|
90
|
+
`)),i=r.filter((n)=>n.added).flatMap((n)=>n.value).filter(jl);if(i.length>0)return en("Stored now:",i);return en("No longer stored:",r.filter((n)=>n.removed).flatMap((n)=>n.value).filter(jl))}function Se(e){return{success:!1,error:e}}async function nh(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:cl(r.content,n.edits)}};if(n.content!==void 0)return Fl(e,r,n.content);if(n.source===void 0)return Se(et);let o=await lr(e,n.source,i,{confirmed:t.confirmed===!0});if(!o.success)return o;return Fl(e,r,o.content,dr(n.source,o))}function Fl(e,t,r,i){let n=Ll(t,r,e.entityRegistry);if(typeof n!=="string")return n;return{operation:{kind:"content",content:n},...i?{source:i}:{}}}function Nl(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=_l(u,p,i);if(f.visibility!==u.visibility&&!pr(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=De(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(x(y,"Failed to update entity"))}let h=await t.getEntity({entityType:u.entityType,id:u.id,visibilityScope:A(m.userPermissionLevel)}),v=h?Zl(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=Ue(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?zl(d,g.content,i):d},a=(d,u,{operation:p,source:m})=>({needsConfirmation:!0,toolName:"system_update",summary:`Update "${Oe(u)}"?`,completionSummary:`Updated ${Bc(u.entityType)}.`,preview:Ul(u,p,i),args:n.buildArgs((g)=>({...d,...m?{operation:{source:m}}:{},id:u.id,confirmed:!0,confirmationToken:g,contentHash:u.contentHash}))});return{...W("update","Update an entity with exactly one typed operation: fields for partial frontmatter/metadata changes, content for full replacement text you wrote, edits for exact text patches, or source for replacement text the user supplied. For a fields change to an entity the user names, call this tool directly without reading the entity first. For small content changes, fetch the entity (an upload ref marked saved already holds its text, so edit that note without fetching it) and use the edits operation with exact oldText/newText pairs, several non-overlapping edits in one call, instead of regenerating the whole document. Never replace unchanged content with placeholders or ellipses. For a large rewrite whose text the user supplied, use the source operation with exact user-message boundaries instead of copying it into content. Requires confirmation; call this tool without confirmed to request that confirmation instead of asking for plain-text approval. For direct requests that provide exact IDs to set an existing image as an entity cover, call this tool on the target entity with the fields operation setting coverImageId to the image ID, even when ogImageId already points at that image; do not stop after lookup. Cover images use coverImageId and OG/social previews ogImageId; they are not interchangeable. To generate a new cover, use system_generate cover-image. For explicit publish requests, use the publishing tool if available instead of changing status here; a follow-up like 'publish it' targets the entity just read or updated.",er,async(d,u)=>{await i.ensureGroupingsCurrent(d.entityType);let p=tr(i,d.entityType,d.operation.fields,{on:"update",allow:["visibility","coverImageId","ogImageId"]});if(p)return Se(p);let m=await _(t,{entityType:d.entityType,identifier:d.id},{visibilityScope:A(u.userPermissionLevel),logger:r});if(!m.ok)return Se(m.error);let g=await nh(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=Bl(h,f,i,t);if(v)return v;let y=B(e,d.entityType,$l(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:Lc(e.entityRegistry,rr(e.permissionService))}}function Hl(e){return[tl(e),sl(e),al(e),Nl(e)]}function br(e){if(e.interfaceType!==Wl)return;if(e.userPermissionLevel!=="public"||e.isAnchor)throw Error("Guest execution denied")}var Ql=3000,oh={limit:10,excerptChars:Ql},sh={limit:5,maxLimit:5,excerptChars:800};function Kl(e){return e!==void 0&&ge(e)==="local"?sh:oh}var ql=`
|
|
91
91
|
|
|
92
92
|
\u2026
|
|
93
93
|
|
|
94
|
-
`,
|
|
95
|
-
`),{starts:r}=t.reduce((n,o,s)=>{if(!n.inFence&&s>0&&Jl.test(o))n.starts.push(s);if(
|
|
94
|
+
`,ah=new Set(["about","and","are","can","does","for","from","how","into","the","this","what","when","where","which","who","why","with","you","your"]);function rn(e){return new Set(e.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter((t)=>t.length>=3&&!ah.has(t)).map((t)=>t.length>3&&t.endsWith("s")?t.slice(0,-1):t))}var Jl=/^#{1,6}\s/,ch=/^\s*(```|~~~)/;function lh(e){let t=e.split(`
|
|
95
|
+
`),{starts:r}=t.reduce((n,o,s)=>{if(!n.inFence&&s>0&&Jl.test(o))n.starts.push(s);if(ch.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:Jl.test(n)?n.split(`
|
|
97
|
-
`)[0]??"":"",text:n}))}function
|
|
97
|
+
`)[0]??"":"",text:n}))}function dh(e,t){let r=rn(t.heading),i=rn(t.text);return Array.from(e).reduce((n,o)=>n+(i.has(o)?1:0)+(r.has(o)?1:0),0)}function Gl(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 Vl(e,t,r=Ql){if(e.length<=r)return e;let i=rn(t),n=lh(e).map((a)=>({section:a,score:dh(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 Gl(e.trim(),r);if(o.text.length>r)return Gl(o.text,r);let{kept:s}=n.reduce((a,l)=>{let d=l.text.length+(a.kept.length>0?ql.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
|
-
`:ql}${a.text}`}).join("")}var
|
|
99
|
+
`:ql}${a.text}`}).join("")}var uh=0.5;function Yl(e,t){let r=e??t.limit;return t.maxLimit===void 0?r:Math.min(r,t.maxLimit)}function Xl(e,t,r,i){let n=zi(e.entity,r);if(n!==e.entity)return{...e,entity:n,excerpt:n.content};let o=ze(n.content);if(o.length<=i)return{...e,entity:n};let{content:s,...a}=n;return{...e,entity:a,excerpt:Vl(o,t,i),excerpted:!0}}var Sr=(e)=>e==="public"?{publishedOnly:!0}:{};function ph(e,t){if(e.length===0)return;let r=Math.round(Math.max(...e.map((i)=>i.score))*100)/100;return{minScore:t,weakerMatches:e.length,bestScore:r,hint:`No result reached minScore ${t}, but ${e.length} weaker match${e.length===1?"":"es"} exist (best score ${r}). Broad or abstract questions match content weakly: search again with a lower minScore, such as 0.3, before concluding that nothing relevant exists.`}}function ed(e){let{entityService:t,logger:r}=e;return[le("system","search","Search entities using semantic search. For broad search, make one system_search call with scope.kind all. Use scope.kind type only when the user asks for a specific entity type. When the user names entity types, search each with scope.kind type in the same step, without a broad search first. Applies a default minScore of 0.5 to reduce weak matches; lower minScore only for exploratory or loose recall. An empty result with belowThreshold means weaker matches exist: search again with a lower minScore before concluding that nothing relevant exists. When the question is in a different language from the saved content, also search with the query translated into the content's language before concluding that little exists; the content's language is the language of the search results and of the brain's profile, and matches across languages score lower. Search results include each matched entity's content; a long one's is excerpted to its best-matching sections, which system_get reads whole. When relevant results already contain the complete evidence needed, answer from those results instead of redundantly listing or getting the same entities. When a typed search's results hold that type's entities but not a detail the user asked about, the detail is not saved there: answer from what the results say and name what is missing, rather than searching the same type again with added words. 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?'.",Rc,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:Yl(i.limit,e.searchBudget),filter:{visibilityScope:o},...Sr(o)}})).map((m)=>Xl({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??uh,a=await t.search({query:i.query,options:{limit:Yl(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?ph(a,s):void 0;return{success:!0,data:{results:l.map((u)=>Xl(u,i.query,e.entityRegistry,e.searchBudget.excerptChars)),...d&&{belowThreshold:d}}}},{visibility:"public",sideEffects:"none",cli:{name:"search"}}),le("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.",wc,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 _(t,{entityType:i.entityType,identifier:i.id},{visibilityScope:o,logger:r,read:{...Sr(o),source:!0}});if(!s.ok)return{success:!1,error:s.error};let a=zi(s.entity,e.entityRegistry);return{success:!0,data:{entity:i.part==="body"?{...a,content:ze(a.content)}:a}}},{visibility:"public",sideEffects:"none",cli:{name:"get"}}),le("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.",Ic,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,...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 mh(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 gh(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(mh),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 td(e){let{entityService:t,analytics:r}=e,i=r.getDefinitions(),n=i.map((o)=>`${o.type} (${o.description})`).join("; ");return[le("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}.`,gh(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 rd(e){let{jobs:t}=e;return[W("job_status","Inspect runtime job status for ready checks only when the prior operation created a job, or for status disputes. With a known batch ID, pass batchId. Without an ID, call this tool with no arguments to list active jobs and batches; do not ask the user for an ID first. Do not argue from the transcript alone.",Ac,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 fh(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 id(e){return[le("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:fh(await e.getAppInfo(),(i)=>e.permissionService.hasPermission(r.userPermissionLevel??"public",i))}),{visibility:"public",sideEffects:"none",cli:{name:"status"}})]}function nd(e){return[...ed(e),...rd(e),...id(e),...Hl(e),...td(e)]}function od(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 ad(e){let{entityService:t}=e;return[{name:"entity-list",uriTemplate:"entity://{type}",description:"List entities of a given type",mimeType:"application/json",list:async()=>t.getEntityTypes().map((i)=>({uri:`entity://${i}`,name:`${i} entities`})),complete:{type:async()=>t.getEntityTypes()},handler:async({type:r})=>{let i=t.getEntityTypes();if(!i.includes(r))throw Error(`Unknown entity type: ${r}. Available: ${i.join(", ")}`);let o=(await t.listEntities({entityType:r})).map((s)=>({id:s.id,entityType:s.entityType,...s.metadata,updated:s.updated}));return{contents:[{uri:`entity://${r}`,mimeType:"application/json",text:JSON.stringify(o,null,2)}]}}},{name:"entity-detail",uriTemplate:"entity://{type}/{id}",description:"Read a single entity by type and ID",mimeType:"text/markdown",complete:{type:async(r)=>{let i=t.getEntityTypes();return r?i.filter((n)=>n.startsWith(r)):i},id:async()=>[]},handler:async({type:r,id:i})=>{let n=await t.getEntity({entityType:r,id:i});if(!n)throw Error(`Entity not found: ${r}/${i}`);let o=e.entityRegistry.getEntityTypeConfig(r).binaryStorage==="asset"?await sd(t,n.content,n.metadata):n.content;return{contents:[{uri:`entity://${r}/${i}`,mimeType:"text/markdown",text:o}]}}}]}function cd(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 ld(e){return["## Entity CRUD","","Use the system tools for ALL entity operations; each tool's description is its contract.","","Treat explicit verbs such as save, create, capture, remember, import, add/connect an agent, approve/archive an agent, update, delete, generate, publish, or sync as mutation requests. Entity-specific instructions may require proactively recording the user's request itself for demand or workflow tracking; follow those instructions even when the user did not use a separate save/create verb. Ordinary status questions like 'what is the status', 'is it ready', 'did that finish', or 'what happened' are not capture requests; answer them by using the relevant status/read tool for the prior operation. Never call system_create for a status follow-up.","","Do not ask for prose confirmation instead of calling the applicable mutating tool; for create, update, delete, generate, publish, sync, and similar state-changing requests, the initial tool call without `confirmed` is how you create the pending confirmation. Never pass `confirmed: true` on the initial user request. Deletion is Admin-only: if system_delete is not available in the current tool surface, say deletion requires Admin access without calling any tool to find or read the target; do not imply a confirmation flow is available. Never claim a durable create/update/delete change was saved, created, done, or completed unless the relevant tool call succeeded or returned a pending confirmation. If a create/update/delete tool is unavailable, unauthorized, or intentionally not called, say you can't make that durable change from the current context; never say saved/created/done. For an explicit write request from an unauthorized/currently unwritable context, refuse directly; do not call system_status or system_search to check permission or look up related content. Entity type descriptions may mark projection-owned or system-maintained types read-only; refuse mutation requests for those types directly without calling read or write tools, searching for a target, or asking which record to mutate.","","Entity types \u2014 select `entityType` by what the type is for:",...e.entityService.getEntityTypes().map((i)=>`- ${i}: ${e.entityRegistry.getAdapter(i).purpose}`)].join(`
|
|
101
|
-
`)}var fh=c.union([c.object({needsConfirmation:c.literal(!0),summary:c.string(),completionSummary:c.string().optional(),preview:c.string(),args:c.record(c.string(),c.unknown())}),c.object({success:c.literal(!0),data:c.object({entityId:c.string(),jobId:c.string().optional()})}),c.object({success:c.literal(!1),error:c.string(),code:c.string().optional()})]);function pd(e){let[t="",...r]=e.source.entityIds;return{kind:"prompt-from-source",entityType:e.entityType,source:{entityType:e.source.entityType,entityId:t},...r.length>0&&{additionalSourceIds:r},...e.prompt!==void 0&&{prompt:e.prompt}}}var hh=c.object({operation:c.looseObject({kind:c.literal("prompt-from-source"),entityType:c.string(),source:c.looseObject({entityType:c.string(),entityId:c.string()}),additionalSourceIds:c.array(c.string()).optional(),prompt:c.string().optional()})});function yh(e,t){let r=hh.safeParse(e);if(!r.success)return!1;let{operation:i}=r.data,n=pd(t),o=[n.source.entityId,...n.additionalSourceIds??[]],s=[i.source.entityId,...i.additionalSourceIds??[]];return i.entityType===n.entityType&&i.source.entityType===n.source.entityType&&i.prompt===n.prompt&&s.length===o.length&&s.every((a,l)=>a===o[l])}function md(e,t,r){return ud(t,dd,async(i)=>{let n=e.find(({name:a})=>a==="system_generate");if(!n)return{status:"refused",error:"Generation is unavailable."};if(i.approval&&!yh(i.approval,i))return{status:"refused",error:"The approval is not for this generation."};let o={interfaceType:i.interfaceType,actor:i.actor,userPermissionLevel:i.userPermissionLevel},s=fh.parse(await n.handler(i.approval??{operation:pd(i)},o));if("needsConfirmation"in s)return{status:"confirm",summary:s.summary,...s.completionSummary!==void 0&&{completionSummary:s.completionSummary},preview:s.preview,approval:s.args};if(s.success)return{status:"queued",entityId:s.data.entityId,...s.data.jobId!==void 0&&{jobId:s.data.jobId}};return{status:"refused",error:s.error,...s.code!==void 0&&{code:s.code}}},{owner:"system",logger:r})}var Ue="system",vh=c.object({toolName:c.string(),args:c.unknown(),...gd.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 fd(e,t,r,i){let n=nd(e);Rr(n,(p)=>t.registerTool(Ue,p),(p)=>p.name,"tool",i);let o=r.subscribe(Gt.toolExecute(Ue),async(p)=>{let m=vh.safeParse(p.payload);if(!m.success)return{success:!1,error:"Invalid system tool execute payload"};let{toolName:g,args:f,interfaceType:h,actor:v,conversationId:y,channelId:S,userPermissionLevel:R}=m.data,w=n.find((L)=>L.name===g);if(!w)return{success:!1,error:`System tool not found: ${g}`};let P={interfaceType:h??"system",actor:v??{kind:"service",serviceId:"system"}};if(y)P.conversationId=y;if(S)P.channelId=S;if(R)P.userPermissionLevel=R;return{success:!0,data:await w.handler(f,P)}});i.debug(`Registered ${n.length} system tools`);let s=od(e);Rr(s,(p)=>t.registerResource(Ue,p),(p)=>p.uri,"resource",i),i.debug(`Registered ${s.length} system resources`);let a=ad(e);Rr(a,(p)=>t.registerResourceTemplate(Ue,p),(p)=>p.uriTemplate,"resource template",i),i.debug(`Registered ${a.length} system resource templates`);let l=cd(e);Rr(l,(p)=>t.registerPrompt(Ue,p),(p)=>p.name,"prompt",i),i.debug(`Registered ${l.length} system prompts`);let d=ld(e);try{t.registerInstructions(Ue,d)}catch{i.debug("System instructions already registered, skipping")}i.debug("Registered system instructions");let u=md(n,r,i);return()=>{o(),u()}}function Sd(e){let{services:t,jobs:r,analytics:i,query:n,getAppInfo:o}=e,s=t.jobQueueService,a=t.logger.child("system"),l=fd({entityService:t.entityService,entityRegistry:t.entityRegistry,jobs:{...r,enqueue:hd(s,"system",!1),enqueueBatch:vd(r,"system"),registerHandler:bd(s,"system"),has:yd(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:Kl(t.aiService.getConfig().model),analytics:i,permissionService:t.permissionService},t.mcpService,t.messageBus,a);t.disposables.push(l)}class nn{scope;closePromise=null;closed=!1;constructor(){this.scope=b.runSync(D.make())}buildLayer(e){this.assertOpen();let t=b.runSyncExit(Q.buildWithScope(e,this.scope));if(j.isFailure(t))throw oe.squash(t.cause);return t.value}addFinalizer(e){this.assertOpen(),b.runSync(D.addFinalizer(this.scope,b.promise(async()=>{await e()})))}addSyncFinalizer(e){this.assertOpen(),b.runSync(D.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=j.void){if(this.closePromise)return this.closePromise;if(this.closed)return Promise.resolve();return this.closed=!0,this.closePromise=b.runPromise(D.close(this.scope,e)),this.closePromise}closeSync(e){if(this.closed)return;this.closed=!0,b.runSync(D.close(this.scope,e))}assertOpen(){if(this.closed)throw Error("Cannot register cleanup after shell shutdown")}}class on{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 on(ut(e),t,r)}constructor(e,t,r){this.config=e,this.httpServed=e.http.enabled&&xe(r?.processRole).serves,this.lifecycle=new nn,Ed(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=mc(this.services.batchJobManager,this.services.jobQueueService),this.analyticsRegistry=cc(this.services.entityRegistry),this.bootloader=new xi(this.config,this.services,this.lifecycle,n,r?.processRole,{registerCoreDataSources:()=>Tn(this.services,this.config),finalizeHttpRoutes:()=>{this.httpRouteRegistry.finalize(fc(this.services.pluginManager))},registerSystemCapabilities:()=>Sd({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();vc(this.lifecycle,this.services)}catch(o){try{this.lifecycle.closeSync(j.fail(o))}catch(s){i.error("Failed to roll back Shell service construction",s)}throw o}}createProjectionInputContext(){return{entities:this.services.entityService,resolvePrompt:(e,t)=>pt(this.services.entityService,e,t),appInfo:()=>this.getAppInfo(),identityInput:()=>{let e=this.getIdentity(),t=this.getProfile();return wd.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:Pd(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,xd,{timestamp:new Date().toISOString()},"shell"),this.services.logger.debug("Emitted shell ready event")}}catch(t){if(this.initialized=!1,this.services.logger.error("Failed to initialize Shell",t),this.lifecycleState!=="closing")this.lifecycleState="failed";try{await this.lifecycle.close(j.fail(t))}catch(r){this.services.logger.error("Failed to clean up Shell after initialization failure",r)}throw t}}registerTemplates(e,t){this.services.logger.debug("Registering templates",{pluginId:t,count:Object.keys(e).length});for(let[r,i]of Object.entries(e))this.registerTemplate(r,i,t)}shutdown(){return this.shutdownPromise??=this.shutdownShell(),this.shutdownPromise}async shutdownShell(){if(this.services.logger.debug("Shutting down Shell"),this.lifecycleState==="closed")return;let e=this.bootPromise;if(this.lifecycleState="closing",this.initialized=!1,e)try{await e}catch{}await this.lifecycle.close(),this.lifecycleState="closed",this.services.logger.debug("Shell shutdown complete")}async generateContent(e,t){return this.requireInitialized("Shell content generation"),En(this.services,e,t)}async query(e,t){this.requireInitialized("Shell query");let r=await this.getAppInfo(),i={...t,appInfo:r,timestamp:new Date().toISOString()},{conversationHistory:n,...o}=i;return Rd.parse(await this.generateContent({prompt:e,templateName:Fe.KNOWLEDGE_QUERY,...n&&{conversationHistory:n},data:o,interfacePermissionGrant:"public"}))}registerPlugin(e){this.requireInitialized("Plugin registration"),this.services.pluginManager.registerPlugin(e)}isInitialized(){return this.initialized}requireInitialized(e){if(!this.initialized)throw Error(`${e} attempted before initialization`)}getEntityService(){return this.services.entityService}getConversationService(){return this.services.conversationService}getEntityRegistry(){return this.services.entityRegistry}async generateObject(e,t,r){this.requireInitialized("Shell generateObject");let{object:i}=await this.services.aiService.generateObject("You are a helpful assistant. Respond with the requested structured data.",e,t,r);return{object:i}}async judge(e){return this.requireInitialized("Shell judge"),this.services.aiService.judge(e)}getAIService(){return this.services.aiService}generateImage(e,t){return this.services.aiService.generateImage(e,t)}canGenerateImages(){return this.services.aiService.canGenerateImages()}canDescribeImages(){return this.services.aiService.canDescribeImages?.()??!1}async describeImage(e,t){return this.services.aiService.describeImage?.(e,t)}getPluginManager(){return this.services.pluginManager}getContentService(){return this.services.contentService}getCallerAuthorizer(){return this.services.callerAuthorizer}getRenderService(){return this.services.renderService}getAttachmentRegistry(){return wr(this.services.attachmentRegistry)}getRuntimeUploadRegistry(){return Cd(this.services.runtimeUploadRegistry)}getRuntimeState(){return this.services.runtimeStateService}getRecurringChecks(e){return this.services.recurringCheckService.namespace(e)}isJobQueueWorkerRunning(){return this.services.jobQueueWorker.isWorkerRunning()}getMessageBus(){return this.services.messageBus}getLogger(){return this.services.logger}getJobQueueService(){return this.services.jobQueueService}getMCPService(){return this.services.mcpService}listToolsForPermissionLevel(e){return this.services.mcpService.listToolsForPermissionLevel(e).map(({pluginId:t,tool:r})=>({name:r.name,description:r.description,pluginId:t}))}getPermissionService(){return this.services.permissionService}getAgentService(){return this.services.agentService}registerTools(e,t){for(let r of t)this.services.mcpService.registerTool(e,r)}registerResources(e,t){for(let r of t)this.services.mcpService.registerResource(e,r)}registerResourceTemplate(e,t){this.services.mcpService.registerResourceTemplate(e,t)}registerPrompt(e,t){this.services.mcpService.registerPrompt(e,t)}registerInstructions(e,t){if(this.services.mcpService.registerInstructions(e,t),this.initialized)this.services.agentService.invalidateAgent()}async unregisterPluginCapabilities(e){this.services.mcpService.unregisterPlugin?.(e),this.services.jobQueueService.unregisterPluginHandlers(e),this.endpointRegistry.unregister(e),this.interactionRegistry.unregister(e);for(let r of this.services.templateRegistry.getNames())if(r.startsWith(`${e}:`))this.services.templateRegistry.unregister(r);let t=this.config.evalHandlerRegistry;if(t){for(let r of t.list())if(r.pluginId===e)t.unregister(e,r.handlerId)}this.services.agentService.invalidateAgent(),await this.services.recurringCheckService.unregisterPlugin(e)}getPluginPackageName(e){return this.services.pluginManager.getPluginPackageName(e)}hasPlugin(e){return this.services.pluginManager.hasPlugin(e)}getPluginHttpRouteManifest(){return this.httpRouteRegistry.getManifest()}getPluginApiRoutes(){return this.httpRouteRegistry.getApiRoutes()}getPluginWebRoutes(){return this.httpRouteRegistry.getWebRoutes()}registerDaemon(e,t,r){this.services.daemonRegistry.register(e,t,r)}registerEndpoint(e){this.endpointRegistry.register(e)}listEndpoints(){return this.endpointRegistry.list()}registerInteraction(e){this.interactionRegistry.register(e)}listInteractions(){return this.interactionRegistry.list()}registerTemplate(e,t,r){let i=r?`${r}:${e}`:`shell:${e}`;this.services.templateRegistry.register(i,t),this.services.logger.debug(`Registered template: ${i}`)}getTemplate(e){return this.services.templateRegistry.get(e)}getDataSourceRegistry(){return this.services.dataSourceRegistry}getIdentity(){return this.services.identityService.getCharacter()}getProfile(){return this.services.profileService.getProfile()}getProfileKindRegistry(){return this.services.profileKindRegistry}getChannelRegistry(){return this.services.channelRegistry}getInboxRegistry(){return this.services.inboxRegistry}getInboxFollowUpRegistry(){return this.services.inboxFollowUpRegistry}getOperationalHealthRegistry(){return this.services.operationalHealthRegistry}getAccountSettingsRegistry(){return this.services.accountSettingsRegistry}getAuthRegistry(){return this.services.authRegistry}getAtprotoProjectionRegistry(){return this.services.atprotoProjectionRegistry}getDomain(){return this.config.siteBaseUrl}getLocalSiteUrl(){return this.config.localSiteUrl}shouldPreferLocalUrls(){return this.config.preferLocalUrls}isProduction(){return this.config.production}servesHttp(){return this.httpServed}registerHttpHost(){let{daemonRegistry:e,logger:t,messageBus:r,pluginManager:i}=this.services;e.register(K,Qa({config:this.config.http,domain:this.config.siteBaseUrl,logger:t.child(H),messageBus:r,getRoutes:()=>this.httpRouteRegistry.getSnapshot(),getPlugins:()=>[...i.getAllPlugins().values()].map(({plugin:s})=>s),getOperationalInfo:async()=>Td(Id(await this.getAppInfo())),getReadinessData:()=>this.getRuntimeReadiness()}),H),this.lifecycle.addSyncFinalizer(()=>e.abandon(K));let{endpoints:n,interactions:o}=Ka(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 hn({config:this.config,services:this.services,bootTime:this.bootTime,endpoints:()=>this.listEndpoints(),interactions:()=>this.listInteractions()})}getRuntimeReadiness(){return bn(this.services)}}async function $d(e,t){await de({label:"entity",config:e,schema:{assets:kd,entities:Ad,entityMutationReceipts:jd,projectionDirtyInputs:Dd,projectionWaves:zd,projectionIncidents:Od,projectionWaveInputs:Md,projectionWaveRules:Ld,projectionRuleMemos:Ud},migrationsFolder:ue(import.meta.url,"entity-service"),authTokenEnv:"DATABASE_AUTH_TOKEN",logger:t,afterMigrate:Bd})}async function Fd(e,t){await de({label:"job-queue",config:e,schema:{jobQueue:_d,jobWorkerSessions:Zd},migrationsFolder:ue(import.meta.url,"job-queue"),authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",logger:t})}async function qd(e,t){await de({label:"conversation",config:e,schema:{conversations:Nd,messages:Hd,summaryTracking:Wd},migrationsFolder:ue(import.meta.url,"conversation-service"),authTokenEnv:"CONVERSATION_DATABASE_AUTH_TOKEN",logger:t})}async function Jd(e,t){await de({label:"runtime-state",config:e,schema:{runtimeStateRecords:I},migrationsFolder:ue(import.meta.url,"runtime-state"),authTokenEnv:"RUNTIME_STATE_DATABASE_AUTH_TOKEN",logger:t})}import{mkdir as an}from"fs/promises";import{isAbsolute as bh}from"path";function Gd(e=process.env){return{dataDir:e.XDG_DATA_HOME??"./data",cacheDir:e.XDG_CACHE_HOME??"./cache",distDir:"./dist"}}function Qd(e=process.env){let t=e.BRAIN_GIT_BROKER_CHECKOUT;if(!t)return;if(!bh(t))throw Error(`Git broker checkout path must be absolute: ${t}`);return t}function Kd(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 Vd(e=process.env){return me(Gd(e))}async function Yd(e=process.env){let t=Gd(e);try{await an(t.dataDir,{recursive:!0}),await an(t.cacheDir,{recursive:!0}),await an(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: ${x(r)}`;throw Error(i,{cause:r})}return me(t)}class Sh{logger;migrations;constructor(e,t){this.logger=e,this.migrations=t??{getStandardConfigWithDirectories:()=>Yd(),migrateEntities:$d,migrateJobQueue:Fd,migrateConversations:qd,migrateRuntimeState:Jd}}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 cn={kind:"service",serviceId:"brain-cli"},ln=`${cn.kind}:${cn.serviceId}`;function cj(e="admin"){return{interfaceType:"cli",actor:cn,userPermissionLevel:e}}var uj=c.enum(["eval"]),pj=c.enum(["person","team","organization"]),dn=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 Rh=c.object({providerKeys:Ze.optional(),model:c.string().optional(),embeddingModel:c.string().optional(),modelRuntimeUrl:c.string().optional(),answerModel:c.string().optional(),visionModel:c.string().optional(),imageModel:c.string().optional(),reasoningEffort:re.optional()}),eu=c.object({name:c.string().default("brain-app"),version:c.string().default("1.0.0"),database:c.string().optional(),ai:Rh.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:Xd.optional(),agentInstructions:c.array(c.string()).optional(),deployment:dn.prefault({}),http:_e.prefault({})});var wh="NODE_ENV";function Ih(){return process.env[wh]}function un(){return Ih()==="production"}function tu(){return!un()}var Ph="startup-check";function xh(){return Object.fromEntries(sn.map((e)=>[e,Ph]))}function Aj(e){let r={...eu.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 kj(e,t){let r={plugins:e.plugins??[],...e.shellConfig};return Ch(r),Th(e,r),Eh(e,r,t),Ah(e,r),kh(e,r),jh(e,r),Dh(e,r),zh(e,r),Mh(e,r),Oh(e,r),r}function Ch(e){let t=Vd();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??=Kd(),e.gitBrokerCheckout??=Qd()}function Th(e,t){if(e.database)t.database={url:e.database};if(e.profileKind)t.profileKind=e.profileKind;t.features={}}function Eh(e,t,r){let i=r?.mode==="startup-check",{providerKeys:n,...o}=Z(e.ai??{});if(!n&&Object.keys(o).length===0&&!i)return;t.ai={...t.ai,providerKeys:{...i&&xh(),...t.ai?.providerKeys,...n},...o}}function Ah(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 kh(e,t){let r=e.permissions?.rules??[];t.permissions={...e.permissions,rules:r.some((i)=>i.pattern===ln)?r:[{pattern:ln,level:"admin"},...r]}}function jh(e,t){if(e.spaces)t.spaces=e.spaces}function Dh(e,t){if(e.identity)t.identity=e.identity}function zh(e,t){if(e.agentInstructions)t.agentInstructions=e.agentInstructions}function Oh(e,t){t.http??={...Z(e.http),port:e.deployment.ports.production}}function Mh(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=tu(),t.production=un()}
|
|
102
|
-
export{me as P,
|
|
101
|
+
`)}var hh=c.union([c.object({needsConfirmation:c.literal(!0),summary:c.string(),completionSummary:c.string().optional(),preview:c.string(),args:c.record(c.string(),c.unknown())}),c.object({success:c.literal(!0),data:c.object({entityId:c.string(),jobId:c.string().optional()})}),c.object({success:c.literal(!1),error:c.string(),code:c.string().optional()})]);function pd(e){let[t="",...r]=e.source.entityIds;return{kind:"prompt-from-source",entityType:e.entityType,source:{entityType:e.source.entityType,entityId:t},...r.length>0&&{additionalSourceIds:r},...e.prompt!==void 0&&{prompt:e.prompt}}}var yh=c.object({operation:c.looseObject({kind:c.literal("prompt-from-source"),entityType:c.string(),source:c.looseObject({entityType:c.string(),entityId:c.string()}),additionalSourceIds:c.array(c.string()).optional(),prompt:c.string().optional()})});function vh(e,t){let r=yh.safeParse(e);if(!r.success)return!1;let{operation:i}=r.data,n=pd(t),o=[n.source.entityId,...n.additionalSourceIds??[]],s=[i.source.entityId,...i.additionalSourceIds??[]];return i.entityType===n.entityType&&i.source.entityType===n.source.entityType&&i.prompt===n.prompt&&s.length===o.length&&s.every((a,l)=>a===o[l])}function md(e,t,r){return ud(t,dd,async(i)=>{let n=e.find(({name:a})=>a==="system_generate");if(!n)return{status:"refused",error:"Generation is unavailable."};if(i.approval&&!vh(i.approval,i))return{status:"refused",error:"The approval is not for this generation."};let o={interfaceType:i.interfaceType,actor:i.actor,userPermissionLevel:i.userPermissionLevel},s=hh.parse(await n.handler(i.approval??{operation:pd(i)},o));if("needsConfirmation"in s)return{status:"confirm",summary:s.summary,...s.completionSummary!==void 0&&{completionSummary:s.completionSummary},preview:s.preview,approval:s.args};if(s.success)return{status:"queued",entityId:s.data.entityId,...s.data.jobId!==void 0&&{jobId:s.data.jobId}};return{status:"refused",error:s.error,...s.code!==void 0&&{code:s.code}}},{owner:"system",logger:r})}var Be="system",bh=c.object({toolName:c.string(),args:c.unknown(),...gd.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 fd(e,t,r,i){let n=nd(e);Rr(n,(p)=>t.registerTool(Be,p),(p)=>p.name,"tool",i);let o=r.subscribe(Qt.toolExecute(Be),async(p)=>{let m=bh.safeParse(p.payload);if(!m.success)return{success:!1,error:"Invalid system tool execute payload"};let{toolName:g,args:f,interfaceType:h,actor:v,conversationId:y,channelId:S,userPermissionLevel:R}=m.data,w=n.find((L)=>L.name===g);if(!w)return{success:!1,error:`System tool not found: ${g}`};let P={interfaceType:h??"system",actor:v??{kind:"service",serviceId:"system"}};if(y)P.conversationId=y;if(S)P.channelId=S;if(R)P.userPermissionLevel=R;return{success:!0,data:await w.handler(f,P)}});i.debug(`Registered ${n.length} system tools`);let s=od(e);Rr(s,(p)=>t.registerResource(Be,p),(p)=>p.uri,"resource",i),i.debug(`Registered ${s.length} system resources`);let a=ad(e);Rr(a,(p)=>t.registerResourceTemplate(Be,p),(p)=>p.uriTemplate,"resource template",i),i.debug(`Registered ${a.length} system resource templates`);let l=cd(e);Rr(l,(p)=>t.registerPrompt(Be,p),(p)=>p.name,"prompt",i),i.debug(`Registered ${l.length} system prompts`);let d=ld(e);try{t.registerInstructions(Be,d)}catch{i.debug("System instructions already registered, skipping")}i.debug("Registered system instructions");let u=md(n,r,i);return()=>{o(),u()}}function Sd(e){let{services:t,jobs:r,analytics:i,query:n,getAppInfo:o}=e,s=t.jobQueueService,a=t.logger.child("system"),l=fd({entityService:t.entityService,entityRegistry:t.entityRegistry,jobs:{...r,enqueue:hd(s,"system",!1),enqueueBatch:vd(r,"system"),registerHandler:bd(s,"system"),has:yd(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:Kl(t.aiService.getConfig().model),analytics:i,permissionService:t.permissionService},t.mcpService,t.messageBus,a);t.disposables.push(l)}class nn{scope;closePromise=null;closed=!1;constructor(){this.scope=b.runSync(D.make())}buildLayer(e){this.assertOpen();let t=b.runSyncExit(Q.buildWithScope(e,this.scope));if(j.isFailure(t))throw oe.squash(t.cause);return t.value}addFinalizer(e){this.assertOpen(),b.runSync(D.addFinalizer(this.scope,b.promise(async()=>{await e()})))}addSyncFinalizer(e){this.assertOpen(),b.runSync(D.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=j.void){if(this.closePromise)return this.closePromise;if(this.closed)return Promise.resolve();return this.closed=!0,this.closePromise=b.runPromise(D.close(this.scope,e)),this.closePromise}closeSync(e){if(this.closed)return;this.closed=!0,b.runSync(D.close(this.scope,e))}assertOpen(){if(this.closed)throw Error("Cannot register cleanup after shell shutdown")}}class on{config;services;lifecycle;bootloader;initialized=!1;lifecycleState="constructed";bootMode;bootPromise=null;shutdownPromise=null;analyticsRegistry;bootTime=Date.now();endpointRegistry=new Ti;interactionRegistry=new Ei;httpRouteRegistry=Yt.createFresh();httpServed;jobs;static createFresh(e,t,r){return new on(pt(e),t,r)}constructor(e,t,r){this.config=e,this.httpServed=e.http.enabled&&xe(r?.processRole).serves,this.lifecycle=new nn,Ed(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=mc(this.services.batchJobManager,this.services.jobQueueService),this.analyticsRegistry=cc(this.services.entityRegistry),this.bootloader=new xi(this.config,this.services,this.lifecycle,n,r?.processRole,{registerCoreDataSources:()=>Tn(this.services,this.config),finalizeHttpRoutes:()=>{this.httpRouteRegistry.finalize(fc(this.services.pluginManager))},registerSystemCapabilities:()=>Sd({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();vc(this.lifecycle,this.services)}catch(o){try{this.lifecycle.closeSync(j.fail(o))}catch(s){i.error("Failed to roll back Shell service construction",s)}throw o}}createProjectionInputContext(){return{entities:this.services.entityService,resolvePrompt:(e,t)=>mt(this.services.entityService,e,t),appInfo:()=>this.getAppInfo(),identityInput:()=>{let e=this.getIdentity(),t=this.getProfile();return wd.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:Pd(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,xd,{timestamp:new Date().toISOString()},"shell"),this.services.logger.debug("Emitted shell ready event")}}catch(t){if(this.initialized=!1,this.services.logger.error("Failed to initialize Shell",t),this.lifecycleState!=="closing")this.lifecycleState="failed";try{await this.lifecycle.close(j.fail(t))}catch(r){this.services.logger.error("Failed to clean up Shell after initialization failure",r)}throw t}}registerTemplates(e,t){this.services.logger.debug("Registering templates",{pluginId:t,count:Object.keys(e).length});for(let[r,i]of Object.entries(e))this.registerTemplate(r,i,t)}shutdown(){return this.shutdownPromise??=this.shutdownShell(),this.shutdownPromise}async shutdownShell(){if(this.services.logger.debug("Shutting down Shell"),this.lifecycleState==="closed")return;let e=this.bootPromise;if(this.lifecycleState="closing",this.initialized=!1,e)try{await e}catch{}await this.lifecycle.close(),this.lifecycleState="closed",this.services.logger.debug("Shell shutdown complete")}async generateContent(e,t){return this.requireInitialized("Shell content generation"),En(this.services,e,t)}async query(e,t){this.requireInitialized("Shell query");let r=await this.getAppInfo(),i={...t,appInfo:r,timestamp:new Date().toISOString()},{conversationHistory:n,...o}=i;return Rd.parse(await this.generateContent({prompt:e,templateName:Ne.KNOWLEDGE_QUERY,...n&&{conversationHistory:n},data:o,interfacePermissionGrant:"public"}))}registerPlugin(e){this.requireInitialized("Plugin registration"),this.services.pluginManager.registerPlugin(e)}isInitialized(){return this.initialized}requireInitialized(e){if(!this.initialized)throw Error(`${e} attempted before initialization`)}getEntityService(){return this.services.entityService}getConversationService(){return this.services.conversationService}getEntityRegistry(){return this.services.entityRegistry}async generateObject(e,t,r){this.requireInitialized("Shell generateObject");let{object:i}=await this.services.aiService.generateObject("You are a helpful assistant. Respond with the requested structured data.",e,t,r);return{object:i}}async judge(e){return this.requireInitialized("Shell judge"),this.services.aiService.judge(e)}getAIService(){return this.services.aiService}generateImage(e,t){return this.services.aiService.generateImage(e,t)}canGenerateImages(){return this.services.aiService.canGenerateImages()}canDescribeImages(){return this.services.aiService.canDescribeImages?.()??!1}async describeImage(e,t){return this.services.aiService.describeImage?.(e,t)}getPluginManager(){return this.services.pluginManager}getContentService(){return this.services.contentService}getCallerAuthorizer(){return this.services.callerAuthorizer}getRenderService(){return this.services.renderService}getAttachmentRegistry(){return wr(this.services.attachmentRegistry)}getRuntimeUploadRegistry(){return Cd(this.services.runtimeUploadRegistry)}getRuntimeState(){return this.services.runtimeStateService}getRecurringChecks(e){return this.services.recurringCheckService.namespace(e)}isJobQueueWorkerRunning(){return this.services.jobQueueWorker.isWorkerRunning()}getMessageBus(){return this.services.messageBus}getLogger(){return this.services.logger}getJobQueueService(){return this.services.jobQueueService}getMCPService(){return this.services.mcpService}listToolsForPermissionLevel(e){return this.services.mcpService.listToolsForPermissionLevel(e).map(({pluginId:t,tool:r})=>({name:r.name,description:r.description,pluginId:t}))}getPermissionService(){return this.services.permissionService}getAgentService(){return this.services.agentService}registerTools(e,t){for(let r of t)this.services.mcpService.registerTool(e,r)}registerResources(e,t){for(let r of t)this.services.mcpService.registerResource(e,r)}registerResourceTemplate(e,t){this.services.mcpService.registerResourceTemplate(e,t)}registerPrompt(e,t){this.services.mcpService.registerPrompt(e,t)}registerInstructions(e,t){if(this.services.mcpService.registerInstructions(e,t),this.initialized)this.services.agentService.invalidateAgent()}async unregisterPluginCapabilities(e){this.services.mcpService.unregisterPlugin?.(e),this.services.jobQueueService.unregisterPluginHandlers(e),this.endpointRegistry.unregister(e),this.interactionRegistry.unregister(e);for(let r of this.services.templateRegistry.getNames())if(r.startsWith(`${e}:`))this.services.templateRegistry.unregister(r);let t=this.config.evalHandlerRegistry;if(t){for(let r of t.list())if(r.pluginId===e)t.unregister(e,r.handlerId)}this.services.agentService.invalidateAgent(),await this.services.recurringCheckService.unregisterPlugin(e)}getPluginPackageName(e){return this.services.pluginManager.getPluginPackageName(e)}hasPlugin(e){return this.services.pluginManager.hasPlugin(e)}getPluginHttpRouteManifest(){return this.httpRouteRegistry.getManifest()}getPluginApiRoutes(){return this.httpRouteRegistry.getApiRoutes()}getPluginWebRoutes(){return this.httpRouteRegistry.getWebRoutes()}registerDaemon(e,t,r){this.services.daemonRegistry.register(e,t,r)}registerEndpoint(e){this.endpointRegistry.register(e)}listEndpoints(){return this.endpointRegistry.list()}registerInteraction(e){this.interactionRegistry.register(e)}listInteractions(){return this.interactionRegistry.list()}registerTemplate(e,t,r){let i=r?`${r}:${e}`:`shell:${e}`;this.services.templateRegistry.register(i,t),this.services.logger.debug(`Registered template: ${i}`)}getTemplate(e){return this.services.templateRegistry.get(e)}getDataSourceRegistry(){return this.services.dataSourceRegistry}getIdentity(){return this.services.identityService.getCharacter()}getProfile(){return this.services.profileService.getProfile()}getProfileKindRegistry(){return this.services.profileKindRegistry}getChannelRegistry(){return this.services.channelRegistry}getInboxRegistry(){return this.services.inboxRegistry}getInboxFollowUpRegistry(){return this.services.inboxFollowUpRegistry}getOperationalHealthRegistry(){return this.services.operationalHealthRegistry}getAccountSettingsRegistry(){return this.services.accountSettingsRegistry}getAuthRegistry(){return this.services.authRegistry}getAtprotoProjectionRegistry(){return this.services.atprotoProjectionRegistry}getDomain(){return this.config.siteBaseUrl}getLocalSiteUrl(){return this.config.localSiteUrl}shouldPreferLocalUrls(){return this.config.preferLocalUrls}isProduction(){return this.config.production}servesHttp(){return this.httpServed}registerHttpHost(){let{daemonRegistry:e,logger:t,messageBus:r,pluginManager:i}=this.services;e.register(K,Qa({config:this.config.http,domain:this.config.siteBaseUrl,logger:t.child(H),messageBus:r,getRoutes:()=>this.httpRouteRegistry.getSnapshot(),getPlugins:()=>[...i.getAllPlugins().values()].map(({plugin:s})=>s),getOperationalInfo:async()=>Td(Id(await this.getAppInfo())),getReadinessData:()=>this.getRuntimeReadiness()}),H),this.lifecycle.addSyncFinalizer(()=>e.abandon(K));let{endpoints:n,interactions:o}=Ka(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 hn({config:this.config,services:this.services,bootTime:this.bootTime,endpoints:()=>this.listEndpoints(),interactions:()=>this.listInteractions()})}getRuntimeReadiness(){return bn(this.services)}}async function $d(e,t){await de({label:"entity",config:e,schema:{assets:kd,entities:Ad,entityMutationReceipts:jd,projectionDirtyInputs:Dd,projectionWaves:Od,projectionIncidents:zd,projectionWaveInputs:Md,projectionWaveRules:Ld,projectionRuleMemos:Ud},migrationsFolder:ue(import.meta.url,"entity-service"),authTokenEnv:"DATABASE_AUTH_TOKEN",logger:t,afterMigrate:Bd})}async function Fd(e,t){await de({label:"job-queue",config:e,schema:{jobQueue:_d,jobWorkerSessions:Zd},migrationsFolder:ue(import.meta.url,"job-queue"),authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",logger:t})}async function qd(e,t){await de({label:"conversation",config:e,schema:{conversations:Nd,messages:Hd,summaryTracking:Wd},migrationsFolder:ue(import.meta.url,"conversation-service"),authTokenEnv:"CONVERSATION_DATABASE_AUTH_TOKEN",logger:t})}async function Jd(e,t){await de({label:"runtime-state",config:e,schema:{runtimeStateRecords:I},migrationsFolder:ue(import.meta.url,"runtime-state"),authTokenEnv:"RUNTIME_STATE_DATABASE_AUTH_TOKEN",logger:t})}import{mkdir as an}from"fs/promises";import{isAbsolute as Sh}from"path";function Gd(e=process.env){return{dataDir:e.XDG_DATA_HOME??"./data",cacheDir:e.XDG_CACHE_HOME??"./cache",distDir:"./dist"}}function Qd(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 Kd(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 Vd(e=process.env){return me(Gd(e))}async function Yd(e=process.env){let t=Gd(e);try{await an(t.dataDir,{recursive:!0}),await an(t.cacheDir,{recursive:!0}),await an(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: ${x(r)}`;throw Error(i,{cause:r})}return me(t)}class Rh{logger;migrations;constructor(e,t){this.logger=e,this.migrations=t??{getStandardConfigWithDirectories:()=>Yd(),migrateEntities:$d,migrateJobQueue:Fd,migrateConversations:qd,migrateRuntimeState:Jd}}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 cn={kind:"service",serviceId:"brain-cli"},ln=`${cn.kind}:${cn.serviceId}`;function lj(e="admin"){return{interfaceType:"cli",actor:cn,userPermissionLevel:e}}var pj=c.enum(["eval"]),mj=c.enum(["person","team","organization"]),dn=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 wh=c.object({providerKeys:Fe.optional(),model:c.string().optional(),embeddingModel:c.string().optional(),modelRuntimeUrl:c.string().optional(),answerModel:c.string().optional(),visionModel:c.string().optional(),imageModel:c.string().optional(),reasoningEffort:re.optional()}),eu=c.object({name:c.string().default("brain-app"),version:c.string().default("1.0.0"),database:c.string().optional(),ai:wh.optional(),logLevel:Ie.optional(),logFile:c.string().optional(),profileKind:c.string().trim().min(1).optional(),plugins:c.array(ut).default([]),spaces:c.array(c.string()).default([]),identity:Xd.optional(),agentInstructions:c.array(c.string()).optional(),deployment:dn.prefault({}),http:Ze.prefault({})});var Ih="NODE_ENV";function Ph(){return process.env[Ih]}function un(){return Ph()==="production"}function tu(){return!un()}var xh="startup-check";function Ch(){return Object.fromEntries(sn.map((e)=>[e,xh]))}function kj(e){let r={...eu.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 jj(e,t){let r={plugins:e.plugins??[],...e.shellConfig};return Th(r),Eh(e,r),Ah(e,r,t),kh(e,r),jh(e,r),Dh(e,r),Oh(e,r),zh(e,r),Lh(e,r),Mh(e,r),r}function Th(e){let t=Vd();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??=Kd(),e.gitBrokerCheckout??=Qd()}function Eh(e,t){if(e.database)t.database={url:e.database};if(e.profileKind)t.profileKind=e.profileKind;t.features={}}function Ah(e,t,r){let i=r?.mode==="startup-check",{providerKeys:n,...o}=Z(e.ai??{});if(!n&&Object.keys(o).length===0&&!i)return;t.ai={...t.ai,providerKeys:{...i&&Ch(),...t.ai?.providerKeys,...n},...o}}function kh(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 jh(e,t){let r=e.permissions?.rules??[];t.permissions={...e.permissions,rules:r.some((i)=>i.pattern===ln)?r:[{pattern:ln,level:"admin"},...r]}}function Dh(e,t){if(e.spaces)t.spaces=e.spaces}function Oh(e,t){if(e.identity)t.identity=e.identity}function zh(e,t){if(e.agentInstructions)t.agentInstructions=e.agentInstructions}function Mh(e,t){t.http??={...Z(e.http),port:e.deployment.ports.production}}function Lh(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=tu(),t.production=un()}
|
|
102
|
+
export{me as P,Ze as Q,Ie as R,pt as S,O as T,Ku as U,Vu as V,Yu as W,np as X,Qn as Y,sp as Z,ap as _,cp as $,lp as aa,dp as ba,up as ca,pp as da,Kr as ea,ea as fa,vi as ga,bc as ha,gl as ia,Cf as ja,hl as ka,nt as la,Tf as ma,be as na,Ni as oa,Hi as pa,Wi as qa,Af as ra,Of as sa,zf as ta,MT as ua,Pl as va,xl as wa,Uf as xa,Bf as ya,$f as za,_f as Aa,Xi as Ba,Zf as Ca,Ff as Da,qf as Ea,on as Fa,$d as Ga,Fd as Ha,qd as Ia,Jd as Ja,Rh as Ka,lj as La,mj as Ma,kj as Na,jj as Oa};
|
|
103
103
|
|
|
104
|
-
//# debugId=
|
|
105
|
-
//# sourceMappingURL=index-
|
|
104
|
+
//# debugId=5D3CC562E7C53A0B64756E2164756E21
|
|
105
|
+
//# sourceMappingURL=index-rkq6mgh1.js.map
|