@rizom/brain 0.2.0-alpha.749 → 0.2.0-alpha.750

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.
Files changed (28) hide show
  1. package/dist/brain.js +11 -11
  2. package/dist/chunks/app-7e5m9g6k.js +5 -0
  3. package/dist/chunks/{index-sw6zmn97.js → index-18gtvkxj.js} +2 -2
  4. package/dist/chunks/{index-dz05sh35.js → index-68ge01gj.js} +6 -6
  5. package/dist/chunks/{index-dz05sh35.js.map → index-68ge01gj.js.map} +6 -6
  6. package/dist/chunks/{index-k8mhqgy0.js → index-dv5k8aft.js} +3 -3
  7. package/dist/chunks/{index-k8mhqgy0.js.map → index-dv5k8aft.js.map} +1 -1
  8. package/dist/chunks/{index-tchhjqm2.js → index-g3c3c3y0.js} +2 -2
  9. package/dist/chunks/{index-key3y4em.js → index-ppg0xa7k.js} +2 -2
  10. package/dist/chunks/{index-qfgnh1b2.js → index-q6pcp7gc.js} +4 -4
  11. package/dist/chunks/{index-qfgnh1b2.js.map → index-q6pcp7gc.js.map} +4 -4
  12. package/dist/chunks/{package-zw8n5jm7.js → package-6203jv7y.js} +3 -3
  13. package/dist/chunks/{package-zw8n5jm7.js.map → package-6203jv7y.js.map} +1 -1
  14. package/dist/entities.js +1 -1
  15. package/dist/git-broker.js +1 -1
  16. package/dist/index.js +1 -1
  17. package/dist/interfaces.js +1 -1
  18. package/dist/model.js +6 -6
  19. package/dist/model.js.map +4 -4
  20. package/dist/services.js +1 -1
  21. package/dist/testing.js +1 -1
  22. package/dist/ui/studio-chunks/main-5ndk80hz.js.map +1 -1
  23. package/package.json +1 -1
  24. package/dist/chunks/app-32s4n60w.js +0 -5
  25. /package/dist/chunks/{app-32s4n60w.js.map → app-7e5m9g6k.js.map} +0 -0
  26. /package/dist/chunks/{index-sw6zmn97.js.map → index-18gtvkxj.js.map} +0 -0
  27. /package/dist/chunks/{index-tchhjqm2.js.map → index-g3c3c3y0.js.map} +0 -0
  28. /package/dist/chunks/{index-key3y4em.js.map → index-ppg0xa7k.js.map} +0 -0
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Qa as Ls,Ra as Us}from"./index-wpzfnffx.js";import{$a as mt,$b as Bl,$d as _,Ad as _s,Af as Qd,Bd as al,Bf as Kd,Bg as cc,Cb as Ro,Cf as Vd,Cg as jd,Ci as zo,Db as Eo,Dd as $l,De as so,Dg as No,Di as Ho,Ed as fs,Ee as vs,Ei as Wo,Fb as ue,Fe as kn,Fi as qo,Gb as pe,Gc as Ed,Gd as ee,Ge as bs,Gg as xr,Gi as Jo,Hb as Ld,Hc as Ys,Hd as Hi,Hf as or,Hg as Ps,Ib as Ud,Ic as ho,Ie as Vs,If as Qc,Ig as Te,Jb as Bd,Je as Xr,Jf as co,Kb as $d,Kf as ou,Kg as Dd,Lb as _d,Lc as pd,Lg as Cs,Mb as Fd,Mc as uo,Me as qd,Mg as bc,Nb as Nd,Ne as Jd,Ng as Ga,Ob as Zd,Oe as Xo,Og as xi,Oi as Go,Oj as Fs,Pb as Hd,Pe as es,Pj as Qo,Qb as mo,Qe as ts,Rb as fo,Sb as go,Se as rs,Sj as Ns,Te as wd,Tj as Ko,Ub as Lt,Ue as Id,Uj as zs,Vb as ps,Vc as ms,Ve as xd,Vi as hc,Vj as Vo,Wa as Al,Wb as Rt,Wd as Gc,We as Pd,Wi as yc,Xa as lt,Xb as Qe,Xe as Ad,Xf as jn,Xi as ft,Yb as Ee,Ye as Vl,Yf as ht,Zb as yd,Zf as oc,Zi as Od,_a as nn,_b as Pc,_f as kd,_i as Os,ab as ve,ae as Xs,ak as Zs,bb as xo,bc as A,bi as We,bk as zd,cb as M,cc as fr,cg as Ni,ci as un,dc as ei,dg as tl,dk as Ms,eb as se,ec as yl,eg as rl,ei as Cn,ek as uc,fc as $o,fg as Ss,fi as ge,fk as er,gb as Po,gc as _o,gg as Rs,gi as Tn,hc as Fo,hg as ws,hi as En,ii as Or,jc as Br,ji as Es,kc as $r,ki as An,ob as Co,qc as gr,sd as br,tb as Jr,ub as Ct,ug as Is,ui as As,vb as vo,vi as ks,wb as bo,wd as Ol,wg as xs,wi as Lc,xg as Ke,xi as js,yb as So,yd as $s,ye as Ya,yg as sc,yi as Zo,zb as Md,ze as bt,zg as ac,zi as Ds}from"./index-qfgnh1b2.js";import{Dm as he,Fm as jt,Km as Ks,Lm as Yt,Ln as qa,Ml as Uo,Nn as Ja,Tl as Bo,Um as ic,Un as re,Vn as V,Wl as no,Xm as Kt,ao as gs,go as hs,hm as Ie,ho as ys,io as Sd,jl as G,jm as P,km as Ge,nk as Cl,nl as Qa,nn as hd,ok as Tl,ol as F,on as Td,oo as Ts,pk as ie,qo as Ha,rk as $e,rm as oo,sk as Le,sn as ss,tk as Ue,to as de,uk as mr,vk as dt,xo as Y}from"./index-9881eck9.js";import{Ao as Pe,yo as Ye}from"./index-nwdvz1vw.js";import{Bq as C,Bw as lc,Fs as oe,Hs as us,Ts as j,fw as w,gt as D,ot as Q,vw as ne,xw as Xt,yw as nc}from"./index-6gqg29bj.js";import{Tx as c}from"./index-7ne5672k.js";function jr(e,t){let r=new Set(t.map((i)=>i.type));return e.byType.filter((i)=>(i.status==="pending"||i.status==="processing")&&!r.has(i.type))}function Ze(e,t){let r=e.workerSessions,i=r.active===0?"missing":r.stale>0?"stale":"active",n=e.duePending>0&&(e.oldestDuePendingAgeMs??0)>=120000&&e.totals.processing===0&&(e.latestClaimAgeMs===null||e.latestClaimAgeMs>=120000),o=[];if(i==="missing")o.push("No live worker session");else if(i==="stale")o.push(`${r.stale} stale worker session(s)`);if(n)o.push(`${e.duePending} due job(s) have remained unclaimed for at least 120000ms`);if(t){let s=jr(e,t).reduce((a,l)=>a+l.count,0);if(s>0)o.push(`${s} active job(s) have no declared executor`)}return{status:o.length===0?"operational":"degraded",reasons:o,worker:{state:i,activeSessions:r.active,staleSessions:r.stale,latestHeartbeatAgeMs:r.latestHeartbeatAgeMs},queue:{duePending:e.duePending,processing:e.totals.processing,oldestDuePendingAgeMs:e.oldestDuePendingAgeMs,latestClaimAgeMs:e.latestClaimAgeMs,stalled:n}}}async function Rn(e){let{config:t,services:r,bootTime:i,endpoints:n,interactions:o}=e,[s,a,l,d]=await Promise.all([r.entityService.getEntityCounts(mt("runtime app info reports operator-facing aggregate status")),r.entityService.countEmbeddings(),r.daemonRegistry.getStatuses(),r.jobQueueService.getDiagnostics()]),u=s.reduce((p,m)=>p+m.count,0);return{model:t.name||"brain-app",version:t.version||"1.0.0",uptime:Math.floor((Date.now()-i)/1000),entities:u,entityCounts:s,embeddings:a,backgroundWork:Ze(d,r.jobQueueService.getExecutionRegistrations()),ai:{model:t.ai.model,embeddingModel:r.embeddingService.identity.model},daemons:l,endpoints:n(),interactions:o()}}import{readdir as wn,readFile as Pu}from"fs/promises";var Cu=10;async function Tu(e="/proc"){let t=null;try{t=(await wn(`${e}/self/fd`)).length}catch{}try{let i=(await wn(e,{withFileTypes:!0})).filter((s)=>s.isDirectory()&&/^\d+$/.test(s.name)).map((s)=>s.name),n=0,o=0;return await Promise.all(i.map(async(s)=>{try{let a=await Pu(`${e}/${s}/status`,"utf8");if(o++,/^State:\s+Z\b/m.test(a))n++}catch{}})),{fileDescriptors:t,processCount:o,zombieCount:n}}catch{return{fileDescriptors:t,processCount:null,zombieCount:null}}}function In(e,t,r){return t.status==="fulfilled"?{name:e,status:"healthy",message:r}:{name:e,status:"unhealthy",message:P(t.reason)}}function Eu(e){if(!e)return{name:"job-worker",status:"degraded",message:"Worker session state is unavailable"};let t=e.workerSessions,r=Ze(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 Au(e){if(!e)return{name:"job-queue-progress",status:"degraded",message:"Queue progress state is unavailable"};let t=Ze(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 ku(e,t){if(!e||!t)return{name:"job-execution-inventory",status:"degraded",message:"Job execution inventory is unavailable"};let r=jr(e,t),i=r.reduce((n,o)=>n+o.count,0);return i===0?{name:"job-execution-inventory",status:"healthy",message:"Every active job type has a declared executor"}:{name:"job-execution-inventory",status:"degraded",message:`${i} active job(s) have no declared executor`,details:{jobs:r}}}function ju(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 Du(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 Ou(e){let t=e.entityService.getProjectionStore(),[r,i,n]=await Promise.all([t.getActiveWave(),t.getUnresolvedProjectionIncidentDiagnostics(Cu),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 zu(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 Mu(e){let t=e.filter((r)=>r.status!=="running"||r.health?.status==="error");return t.length===0?{name:"daemons",status:"healthy",message:`${e.length} daemon(s) healthy`}:{name:"daemons",status:"degraded",message:`${t.length} daemon(s) unhealthy`,details:{daemons:t.map((r)=>({name:r.name,status:r.status,health:r.health?.status,message:r.health?.message}))}}}async function xn(e){let t=e.now?.()??Date.now(),r=(e.memoryUsage??process.memoryUsage)(),[i,n,o,s,a,l,d,u]=await Promise.allSettled([e.entityService.getEntityCounts(mt("runtime readiness database probe")),e.jobQueueService.getDiagnostics(t),Promise.resolve(e.jobQueueService.getExecutionRegistrations()),e.daemonRegistry.getStatuses(),(e.readProcessSignals??Tu)(),e.projectionRuntimeSupervisor.getDiagnostics(),Ou(e),e.operationalHealthRegistry.getChecks()]),p=n.status==="fulfilled"?n.value:null,m=o.status==="fulfilled"?o.value??null:null,f=s.status==="fulfilled"?s.value:[],g=a.status==="fulfilled"?a.value:{fileDescriptors:null,processCount:null,zombieCount:null},h=l.status==="fulfilled"?l.value:{status:"unhealthy",initialized:!1,trackedRoots:0,openCircuits:[]},v=[In("entity-database",i,"Entity database is accessible"),In("job-queue-database",n,"Job queue database is accessible"),Eu(p),Au(p),ku(p,m),ju(p),l.status==="fulfilled"?Du(h):{name:"projection-circuits",status:"degraded",message:P(l.reason)},d.status==="fulfilled"?zu(d.value):{name:"projection-waves",status:"degraded",message:P(d.reason)},s.status==="fulfilled"?Mu(f):{name:"daemons",status:"degraded",message:P(s.reason)}],y=u.status==="fulfilled"?u.value:[{name:"plugin-operational-health",status:"degraded",message:"Plugin operational health is unavailable"}],S=[...v,...y];return{status:v.some((b)=>b.status==="unhealthy")?"not_ready":"ready",operationalStatus:S.some((b)=>b.status!=="healthy")?"degraded":"operational",checkedAt:new Date(t).toISOString(),checks:S,resources:{memory:{rssBytes:r.rss,heapUsedBytes:r.heapUsed,heapTotalBytes:r.heapTotal},fileDescriptors:g.fileDescriptors,processes:{total:g.processCount,zombies:g.zombieCount},queue:p,projection:{initialized:h.initialized,trackedRoots:h.trackedRoots,openCircuits:h.openCircuits},worker:p?.workerSessions??{total:0,active:0,stale:0,latestHeartbeatAgeMs:null}}}}function Pn(){return{dataDir:"./data",cacheDir:"./cache",distDir:"./dist"}}function fe(e){return{database:{url:`file:${e.dataDir}/brain.db`},jobQueueDatabase:{url:`file:${e.dataDir}/brain-jobs.db`},conversationDatabase:{url:`file:${e.dataDir}/conversations.db`},runtimeStateDatabase:{url:`file:${e.dataDir}/runtime-state.db`},embeddingDatabase:{url:`file:${e.dataDir}/embeddings.db`},embedding:{enabled:!0}}}var He=c.strictObject({enabled:c.boolean().optional().describe("Serve HTTP; defaults to whether the selected bundles host the web surface"),preview:c.boolean().optional().describe("Serve the preview site; defaults to whether a site builder runs"),hostname:c.string().trim().min(1).optional().describe("Bind address; use 127.0.0.1 for isolated local tests"),productionDistDir:c.string().min(1).optional().describe("Directory of the production site, when no site builder writes it"),previewDistDir:c.string().min(1).optional().describe("Directory of the preview site, when no site builder writes it"),sharedImagesDir:c.string().min(1).optional().describe("Directory of shared optimized images")}),Dr=He.extend({enabled:c.boolean().default(!1),preview:c.boolean().default(!0),port:c.number().default(8080).describe("Port of the production listener")});var zr=Pn(),Lu=c.looseObject({label:c.string().min(1),pluralName:c.string().optional(),layout:c.string().optional(),paginate:c.boolean().optional(),pageSize:c.number().optional(),navigation:c.object({show:c.boolean().optional(),slot:c.enum(["primary","secondary"]).optional(),priority:c.number().optional()}).optional()});function Mr(){return fe(zr)}var xe=c.enum(["debug","info","warn","error"]);var Lr=c.object({name:c.string().default("brain-app"),version:c.string().default("1.0.0"),database:Ie,jobQueueDatabase:Ie,jobQueue:c.object({workerConcurrency:c.number().int().min(1).max(32).default(4)}).prefault({}),conversationDatabase:Ie,runtimeStateDatabase:Ie,embeddingDatabase:Ie,ai:c.object({providerKeys:We.default({}),model:c.string().refine(Cn,{error:(e)=>`Unsupported model "${String(e.input)}"`}),embeddingModel:c.string().refine((e)=>Or(e)!==void 0,{error:(e)=>An(String(e.input))}).default(En),modelRuntimeUrl:c.string().url().optional(),answerModel:c.string().optional(),visionModel:c.string().optional(),imageModel:c.string().optional(),temperature:c.number().min(0).max(2).default(0.7),webSearch:c.boolean().default(!0),reasoningEffort:re.optional()}).superRefine((e,t)=>{if(e.answerModel&&ge(e.answerModel)!=="local")t.addIssue({code:"custom",path:["answerModel"],message:`answerModel must be a local: model, not ${e.answerModel}`});if(e.visionModel&&ge(e.visionModel)!=="local")t.addIssue({code:"custom",path:["visionModel"],message:`visionModel must be a local: model, not ${e.visionModel}`});if(e.modelRuntimeUrl)return;let r=[...ge(e.model)==="local"?[e.model]:[],...[e.answerModel,e.visionModel].filter((i)=>i!==void 0&&ge(i)==="local"),...e.imageModel&&Tn(e.imageModel).provider==="local"?[e.imageModel]:[],...Or(e.embeddingModel)?.provider==="local"?[e.embeddingModel]:[]];for(let i of r)t.addIssue({code:"custom",path:["modelRuntimeUrl"],message:`${i} needs modelRuntime.url`})}),embedding:c.object({enabled:c.boolean().default(!0)}),logging:c.object({level:xe.default("info"),format:c.enum(["text","json"]).default("text"),file:c.string().optional(),context:c.string().default("shell")}).prefault({level:"info",context:"shell"}),features:c.object({}).default({}),plugins:c.array(ft).default([]),dataDir:c.string().default("./brain-data"),gitBrokerSocket:c.string().min(1).optional(),gitBrokerCheckout:c.string().min(1).optional(),spaces:c.array(c.string()).default([]),siteBaseUrl:c.string().optional(),localSiteUrl:c.string().optional(),preferLocalUrls:c.boolean().default(!1),production:c.boolean().default(!1),themeCSS:c.string().default(""),entityDisplay:c.record(c.string(),Lu).optional(),profileKind:c.string().trim().min(1).optional(),http:Dr.prefault({})});function gt(e={}){let{plugins:t=[],permissions:r={},identity:i,profile:n,agentInstructions:o,evalHandlerRegistry:s,ai:a,logging:l,embedding:d,jobQueue:u,...p}=e,{entityDisplay:m,...f}=Lr.parse({...Mr(),...F(p),ai:F({...a}),logging:F({...l}),embedding:F({...d}),jobQueue:F({...u}),plugins:[]});return{...f,plugins:t,permissions:r,...F({entityDisplay:m,identity:i,profile:n,agentInstructions:o,evalHandlerRegistry:s})}}var L={NOTE:"note",BRAIN_CHARACTER:"brain-character",ANCHOR_PROFILE:"anchor-profile"},qe={KNOWLEDGE_QUERY:"shell:knowledge-query",BASE_ENTITY_DISPLAY:"shell:base-entity-display",CONTENT_GENERATION:"shell:content-generation"},Ur={ENTITIES:"shell:entities"};var Uu=kn.extend({templateName:c.string()}),Bu=c.object({slug:c.string()}),$u="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.",_u="Generate the content described in your instructions.";function Fu(e){return e instanceof c.ZodType}function Nu(e){if(!e)return;return e.replace(/^https?:\/\//,"").replace(/\/$/,"")}class yt{aiService;entityService;templateRegistry;getIdentityContent;getProfileContent;entityUrls;id="ai-content";name="AI Content Generator";description="Generates content using AI based on templates and prompts";constructor(e,t,r,i,n,o,s){this.aiService=e,this.entityService=t,this.templateRegistry=r,this.getIdentityContent=i,this.getProfileContent=n,this.entityUrls=o,this.siteBaseUrl=Nu(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=Uu.parse(e),o=this.templateRegistry.get(n.templateName);if(!o)throw Error(`Template not found: ${n.templateName}`);if(!o.basePrompt)throw Error(`Template ${n.templateName} must have basePrompt for content generation`);let s=i?await jn((v,y)=>i.getEntity(v,y),n.templateName,o.basePrompt):await ht(this.entityService,n.templateName,o.basePrompt);r?.throwIfAborted();let a=[s,n.prompt].filter(Boolean).join(" "),l=a.length>0&&o.useKnowledgeContext===!0,d=this.entityService.getWeightMap(),u=Object.keys(d).length>0,p=l?i?await i.search(a,{limit:5,...u&&{weight:d}}):await this.entityService.search({query:a,options:{limit:5,...u&&{weight:d},...r&&{signal:r}}}):[];r?.throwIfAborted();let m=this.buildPrompt(n,p),f=i?await this.readIdentities(i,n.representedIdentity):void 0,g=this.buildSystemPrompt(s,n,f);if(!Fu(o.schema))throw Error(`Template ${o.name} cannot be used for AI generation: schema is not an AI generation schema`);r?.throwIfAborted();let h=await this.aiService.generateObject(g,m,o.schema,r);return r?.throwIfAborted(),t.parse(h.object)}async readIdentities(e,t){let r=async(o)=>(await e.getEntity(o,o))?.content??"",[i,n]=await Promise.all([t!=="none"?r(L.BRAIN_CHARACTER):"",t===void 0||t==="anchor"?r(L.ANCHOR_PROFILE):""]);return{brain:i,anchor:n}}buildSystemPrompt(e,t,r){let i=[];if(t.representedIdentity===void 0||t.representedIdentity==="brain"||t.representedIdentity==="anchor")i.push("# Brain Identity",r?.brain??this.getIdentityContent(),"");if(t.representedIdentity===void 0||t.representedIdentity==="anchor")i.push("# Represented Anchor",r?.anchor??this.getProfileContent(),"");let n=this.selectStyleGuidance(t);if(n)i.push("# Style Guide",n,"","# Precedence",$u,"");return i.push("# Instructions",e),i.join(`
2
+ import{Qa as Ls,Ra as Us}from"./index-wpzfnffx.js";import{$a as mt,$b as Bl,$d as _,Ad as _s,Af as Qd,Bd as al,Bf as Kd,Bg as cc,Cb as Ro,Cf as Vd,Cg as jd,Ci as zo,Db as Eo,Dd as $l,De as so,Dg as No,Di as Ho,Ed as fs,Ee as vs,Ei as Wo,Fb as ue,Fe as kn,Fi as qo,Gb as pe,Gc as Ed,Gd as ee,Ge as bs,Gg as xr,Gi as Jo,Hb as Ld,Hc as Ys,Hd as Hi,Hf as or,Hg as Ps,Ib as Ud,Ic as ho,Ie as Vs,If as Qc,Ig as Te,Jb as Bd,Je as Xr,Jf as co,Kb as $d,Kf as ou,Kg as Dd,Lb as _d,Lc as pd,Lg as Cs,Mb as Fd,Mc as uo,Me as qd,Mg as bc,Nb as Nd,Ne as Jd,Ng as Ga,Ob as Zd,Oe as Xo,Og as xi,Oi as Go,Oj as Fs,Pb as Hd,Pe as es,Pj as Qo,Qb as mo,Qe as ts,Rb as fo,Sb as go,Se as rs,Sj as Ns,Te as wd,Tj as Ko,Ub as Lt,Ue as Id,Uj as zs,Vb as ps,Vc as ms,Ve as xd,Vi as hc,Vj as Vo,Wa as Al,Wb as Rt,Wd as Gc,We as Pd,Wi as yc,Xa as lt,Xb as Qe,Xe as Ad,Xf as jn,Xi as ft,Yb as Ee,Ye as Vl,Yf as ht,Zb as yd,Zf as oc,Zi as Od,_a as nn,_b as Pc,_f as kd,_i as Os,ab as ve,ae as Xs,ak as Zs,bb as xo,bc as A,bi as We,bk as zd,cb as M,cc as fr,cg as Ni,ci as un,dc as ei,dg as tl,dk as Ms,eb as se,ec as yl,eg as rl,ei as Cn,ek as uc,fc as $o,fg as Ss,fi as ge,fk as er,gb as Po,gc as _o,gg as Rs,gi as Tn,hc as Fo,hg as ws,hi as En,ii as Or,jc as Br,ji as Es,kc as $r,ki as An,ob as Co,qc as gr,sd as br,tb as Jr,ub as Ct,ug as Is,ui as As,vb as vo,vi as ks,wb as bo,wd as Ol,wg as xs,wi as Lc,xg as Ke,xi as js,yb as So,yd as $s,ye as Ya,yg as sc,yi as Zo,zb as Md,ze as bt,zg as ac,zi as Ds}from"./index-q6pcp7gc.js";import{Dm as he,Fm as jt,Km as Ks,Lm as Yt,Ln as qa,Ml as Uo,Nn as Ja,Tl as Bo,Um as ic,Un as re,Vn as V,Wl as no,Xm as Kt,ao as gs,go as hs,hm as Ie,ho as ys,io as Sd,jl as G,jm as P,km as Ge,nk as Cl,nl as Qa,nn as hd,ok as Tl,ol as F,on as Td,oo as Ts,pk as ie,qo as Ha,rk as $e,rm as oo,sk as Le,sn as ss,tk as Ue,to as de,uk as mr,vk as dt,xo as Y}from"./index-9881eck9.js";import{Ao as Pe,yo as Ye}from"./index-nwdvz1vw.js";import{Bq as C,Bw as lc,Fs as oe,Hs as us,Ts as j,fw as w,gt as D,ot as Q,vw as ne,xw as Xt,yw as nc}from"./index-6gqg29bj.js";import{Tx as c}from"./index-7ne5672k.js";function jr(e,t){let r=new Set(t.map((i)=>i.type));return e.byType.filter((i)=>(i.status==="pending"||i.status==="processing")&&!r.has(i.type))}function Ze(e,t){let r=e.workerSessions,i=r.active===0?"missing":r.stale>0?"stale":"active",n=e.duePending>0&&(e.oldestDuePendingAgeMs??0)>=120000&&e.totals.processing===0&&(e.latestClaimAgeMs===null||e.latestClaimAgeMs>=120000),o=[];if(i==="missing")o.push("No live worker session");else if(i==="stale")o.push(`${r.stale} stale worker session(s)`);if(n)o.push(`${e.duePending} due job(s) have remained unclaimed for at least 120000ms`);if(t){let s=jr(e,t).reduce((a,l)=>a+l.count,0);if(s>0)o.push(`${s} active job(s) have no declared executor`)}return{status:o.length===0?"operational":"degraded",reasons:o,worker:{state:i,activeSessions:r.active,staleSessions:r.stale,latestHeartbeatAgeMs:r.latestHeartbeatAgeMs},queue:{duePending:e.duePending,processing:e.totals.processing,oldestDuePendingAgeMs:e.oldestDuePendingAgeMs,latestClaimAgeMs:e.latestClaimAgeMs,stalled:n}}}async function Rn(e){let{config:t,services:r,bootTime:i,endpoints:n,interactions:o}=e,[s,a,l,d]=await Promise.all([r.entityService.getEntityCounts(mt("runtime app info reports operator-facing aggregate status")),r.entityService.countEmbeddings(),r.daemonRegistry.getStatuses(),r.jobQueueService.getDiagnostics()]),u=s.reduce((p,m)=>p+m.count,0);return{model:t.name||"brain-app",version:t.version||"1.0.0",uptime:Math.floor((Date.now()-i)/1000),entities:u,entityCounts:s,embeddings:a,backgroundWork:Ze(d,r.jobQueueService.getExecutionRegistrations()),ai:{model:t.ai.model,embeddingModel:r.embeddingService.identity.model},daemons:l,endpoints:n(),interactions:o()}}import{readdir as wn,readFile as Pu}from"fs/promises";var Cu=10;async function Tu(e="/proc"){let t=null;try{t=(await wn(`${e}/self/fd`)).length}catch{}try{let i=(await wn(e,{withFileTypes:!0})).filter((s)=>s.isDirectory()&&/^\d+$/.test(s.name)).map((s)=>s.name),n=0,o=0;return await Promise.all(i.map(async(s)=>{try{let a=await Pu(`${e}/${s}/status`,"utf8");if(o++,/^State:\s+Z\b/m.test(a))n++}catch{}})),{fileDescriptors:t,processCount:o,zombieCount:n}}catch{return{fileDescriptors:t,processCount:null,zombieCount:null}}}function In(e,t,r){return t.status==="fulfilled"?{name:e,status:"healthy",message:r}:{name:e,status:"unhealthy",message:P(t.reason)}}function Eu(e){if(!e)return{name:"job-worker",status:"degraded",message:"Worker session state is unavailable"};let t=e.workerSessions,r=Ze(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 Au(e){if(!e)return{name:"job-queue-progress",status:"degraded",message:"Queue progress state is unavailable"};let t=Ze(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 ku(e,t){if(!e||!t)return{name:"job-execution-inventory",status:"degraded",message:"Job execution inventory is unavailable"};let r=jr(e,t),i=r.reduce((n,o)=>n+o.count,0);return i===0?{name:"job-execution-inventory",status:"healthy",message:"Every active job type has a declared executor"}:{name:"job-execution-inventory",status:"degraded",message:`${i} active job(s) have no declared executor`,details:{jobs:r}}}function ju(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 Du(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 Ou(e){let t=e.entityService.getProjectionStore(),[r,i,n]=await Promise.all([t.getActiveWave(),t.getUnresolvedProjectionIncidentDiagnostics(Cu),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 zu(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 Mu(e){let t=e.filter((r)=>r.status!=="running"||r.health?.status==="error");return t.length===0?{name:"daemons",status:"healthy",message:`${e.length} daemon(s) healthy`}:{name:"daemons",status:"degraded",message:`${t.length} daemon(s) unhealthy`,details:{daemons:t.map((r)=>({name:r.name,status:r.status,health:r.health?.status,message:r.health?.message}))}}}async function xn(e){let t=e.now?.()??Date.now(),r=(e.memoryUsage??process.memoryUsage)(),[i,n,o,s,a,l,d,u]=await Promise.allSettled([e.entityService.getEntityCounts(mt("runtime readiness database probe")),e.jobQueueService.getDiagnostics(t),Promise.resolve(e.jobQueueService.getExecutionRegistrations()),e.daemonRegistry.getStatuses(),(e.readProcessSignals??Tu)(),e.projectionRuntimeSupervisor.getDiagnostics(),Ou(e),e.operationalHealthRegistry.getChecks()]),p=n.status==="fulfilled"?n.value:null,m=o.status==="fulfilled"?o.value??null:null,f=s.status==="fulfilled"?s.value:[],g=a.status==="fulfilled"?a.value:{fileDescriptors:null,processCount:null,zombieCount:null},h=l.status==="fulfilled"?l.value:{status:"unhealthy",initialized:!1,trackedRoots:0,openCircuits:[]},v=[In("entity-database",i,"Entity database is accessible"),In("job-queue-database",n,"Job queue database is accessible"),Eu(p),Au(p),ku(p,m),ju(p),l.status==="fulfilled"?Du(h):{name:"projection-circuits",status:"degraded",message:P(l.reason)},d.status==="fulfilled"?zu(d.value):{name:"projection-waves",status:"degraded",message:P(d.reason)},s.status==="fulfilled"?Mu(f):{name:"daemons",status:"degraded",message:P(s.reason)}],y=u.status==="fulfilled"?u.value:[{name:"plugin-operational-health",status:"degraded",message:"Plugin operational health is unavailable"}],S=[...v,...y];return{status:v.some((b)=>b.status==="unhealthy")?"not_ready":"ready",operationalStatus:S.some((b)=>b.status!=="healthy")?"degraded":"operational",checkedAt:new Date(t).toISOString(),checks:S,resources:{memory:{rssBytes:r.rss,heapUsedBytes:r.heapUsed,heapTotalBytes:r.heapTotal},fileDescriptors:g.fileDescriptors,processes:{total:g.processCount,zombies:g.zombieCount},queue:p,projection:{initialized:h.initialized,trackedRoots:h.trackedRoots,openCircuits:h.openCircuits},worker:p?.workerSessions??{total:0,active:0,stale:0,latestHeartbeatAgeMs:null}}}}function Pn(){return{dataDir:"./data",cacheDir:"./cache",distDir:"./dist"}}function fe(e){return{database:{url:`file:${e.dataDir}/brain.db`},jobQueueDatabase:{url:`file:${e.dataDir}/brain-jobs.db`},conversationDatabase:{url:`file:${e.dataDir}/conversations.db`},runtimeStateDatabase:{url:`file:${e.dataDir}/runtime-state.db`},embeddingDatabase:{url:`file:${e.dataDir}/embeddings.db`},embedding:{enabled:!0}}}var He=c.strictObject({enabled:c.boolean().optional().describe("Serve HTTP; defaults to whether the selected bundles host the web surface"),preview:c.boolean().optional().describe("Serve the preview site; defaults to whether a site builder runs"),hostname:c.string().trim().min(1).optional().describe("Bind address; use 127.0.0.1 for isolated local tests"),productionDistDir:c.string().min(1).optional().describe("Directory of the production site, when no site builder writes it"),previewDistDir:c.string().min(1).optional().describe("Directory of the preview site, when no site builder writes it"),sharedImagesDir:c.string().min(1).optional().describe("Directory of shared optimized images")}),Dr=He.extend({enabled:c.boolean().default(!1),preview:c.boolean().default(!0),port:c.number().default(8080).describe("Port of the production listener")});var zr=Pn(),Lu=c.looseObject({label:c.string().min(1),pluralName:c.string().optional(),layout:c.string().optional(),paginate:c.boolean().optional(),pageSize:c.number().optional(),navigation:c.object({show:c.boolean().optional(),slot:c.enum(["primary","secondary"]).optional(),priority:c.number().optional()}).optional()});function Mr(){return fe(zr)}var xe=c.enum(["debug","info","warn","error"]);var Lr=c.object({name:c.string().default("brain-app"),version:c.string().default("1.0.0"),database:Ie,jobQueueDatabase:Ie,jobQueue:c.object({workerConcurrency:c.number().int().min(1).max(32).default(4)}).prefault({}),conversationDatabase:Ie,runtimeStateDatabase:Ie,embeddingDatabase:Ie,ai:c.object({providerKeys:We.default({}),model:c.string().refine(Cn,{error:(e)=>`Unsupported model "${String(e.input)}"`}),embeddingModel:c.string().refine((e)=>Or(e)!==void 0,{error:(e)=>An(String(e.input))}).default(En),modelRuntimeUrl:c.string().url().optional(),answerModel:c.string().optional(),visionModel:c.string().optional(),imageModel:c.string().optional(),temperature:c.number().min(0).max(2).default(0.7),webSearch:c.boolean().default(!0),reasoningEffort:re.optional()}).superRefine((e,t)=>{if(e.answerModel&&ge(e.answerModel)!=="local")t.addIssue({code:"custom",path:["answerModel"],message:`answerModel must be a local: model, not ${e.answerModel}`});if(e.visionModel&&ge(e.visionModel)!=="local")t.addIssue({code:"custom",path:["visionModel"],message:`visionModel must be a local: model, not ${e.visionModel}`});if(e.modelRuntimeUrl)return;let r=[...ge(e.model)==="local"?[e.model]:[],...[e.answerModel,e.visionModel].filter((i)=>i!==void 0&&ge(i)==="local"),...e.imageModel&&Tn(e.imageModel).provider==="local"?[e.imageModel]:[],...Or(e.embeddingModel)?.provider==="local"?[e.embeddingModel]:[]];for(let i of r)t.addIssue({code:"custom",path:["modelRuntimeUrl"],message:`${i} needs modelRuntime.url`})}),embedding:c.object({enabled:c.boolean().default(!0)}),logging:c.object({level:xe.default("info"),format:c.enum(["text","json"]).default("text"),file:c.string().optional(),context:c.string().default("shell")}).prefault({level:"info",context:"shell"}),features:c.object({}).default({}),plugins:c.array(ft).default([]),dataDir:c.string().default("./brain-data"),gitBrokerSocket:c.string().min(1).optional(),gitBrokerCheckout:c.string().min(1).optional(),spaces:c.array(c.string()).default([]),siteBaseUrl:c.string().optional(),localSiteUrl:c.string().optional(),preferLocalUrls:c.boolean().default(!1),production:c.boolean().default(!1),themeCSS:c.string().default(""),entityDisplay:c.record(c.string(),Lu).optional(),profileKind:c.string().trim().min(1).optional(),http:Dr.prefault({})});function gt(e={}){let{plugins:t=[],permissions:r={},identity:i,profile:n,agentInstructions:o,evalHandlerRegistry:s,ai:a,logging:l,embedding:d,jobQueue:u,...p}=e,{entityDisplay:m,...f}=Lr.parse({...Mr(),...F(p),ai:F({...a}),logging:F({...l}),embedding:F({...d}),jobQueue:F({...u}),plugins:[]});return{...f,plugins:t,permissions:r,...F({entityDisplay:m,identity:i,profile:n,agentInstructions:o,evalHandlerRegistry:s})}}var L={NOTE:"note",BRAIN_CHARACTER:"brain-character",ANCHOR_PROFILE:"anchor-profile"},qe={KNOWLEDGE_QUERY:"shell:knowledge-query",BASE_ENTITY_DISPLAY:"shell:base-entity-display",CONTENT_GENERATION:"shell:content-generation"},Ur={ENTITIES:"shell:entities"};var Uu=kn.extend({templateName:c.string()}),Bu=c.object({slug:c.string()}),$u="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.",_u="Generate the content described in your instructions.";function Fu(e){return e instanceof c.ZodType}function Nu(e){if(!e)return;return e.replace(/^https?:\/\//,"").replace(/\/$/,"")}class yt{aiService;entityService;templateRegistry;getIdentityContent;getProfileContent;entityUrls;id="ai-content";name="AI Content Generator";description="Generates content using AI based on templates and prompts";constructor(e,t,r,i,n,o,s){this.aiService=e,this.entityService=t,this.templateRegistry=r,this.getIdentityContent=i,this.getProfileContent=n,this.entityUrls=o,this.siteBaseUrl=Nu(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=Uu.parse(e),o=this.templateRegistry.get(n.templateName);if(!o)throw Error(`Template not found: ${n.templateName}`);if(!o.basePrompt)throw Error(`Template ${n.templateName} must have basePrompt for content generation`);let s=i?await jn((v,y)=>i.getEntity(v,y),n.templateName,o.basePrompt):await ht(this.entityService,n.templateName,o.basePrompt);r?.throwIfAborted();let a=[s,n.prompt].filter(Boolean).join(" "),l=a.length>0&&o.useKnowledgeContext===!0,d=this.entityService.getWeightMap(),u=Object.keys(d).length>0,p=l?i?await i.search(a,{limit:5,...u&&{weight:d}}):await this.entityService.search({query:a,options:{limit:5,...u&&{weight:d},...r&&{signal:r}}}):[];r?.throwIfAborted();let m=this.buildPrompt(n,p),f=i?await this.readIdentities(i,n.representedIdentity):void 0,g=this.buildSystemPrompt(s,n,f);if(!Fu(o.schema))throw Error(`Template ${o.name} cannot be used for AI generation: schema is not an AI generation schema`);r?.throwIfAborted();let h=await this.aiService.generateObject(g,m,o.schema,r);return r?.throwIfAborted(),t.parse(h.object)}async readIdentities(e,t){let r=async(o)=>(await e.getEntity(o,o))?.content??"",[i,n]=await Promise.all([t!=="none"?r(L.BRAIN_CHARACTER):"",t===void 0||t==="anchor"?r(L.ANCHOR_PROFILE):""]);return{brain:i,anchor:n}}buildSystemPrompt(e,t,r){let i=[];if(t.representedIdentity===void 0||t.representedIdentity==="brain"||t.representedIdentity==="anchor")i.push("# Brain Identity",r?.brain??this.getIdentityContent(),"");if(t.representedIdentity===void 0||t.representedIdentity==="anchor")i.push("# Represented Anchor",r?.anchor??this.getProfileContent(),"");let n=this.selectStyleGuidance(t);if(n)i.push("# Style Guide",n,"","# Precedence",$u,"");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(`
@@ -74,13 +74,13 @@ ${JSON.stringify(e.data,null,2)}`);if(e.prompt)r.push(`Additional instructions:
74
74
  <p>Once built, this page will be replaced with your actual website.</p>
75
75
  </div>
76
76
  </body>
77
- </html>`;var Ka=c.strictObject({productionOutputDir:c.string().min(1),previewOutputDir:c.string().min(1),sharedImagesDir:c.string().min(1)});var H="webserver",K=`${H}:${H}`,tf="./dist/site-production",rf="./dist/site-preview",nf="./dist/images";function of(e){return[...e].flatMap((t)=>{let r=t.getStaticSiteOutput?.();return r?[{...Ka.parse(r),ownerPluginId:t.id}]:[]})}function sf(e,t){let[r,i]=t;if(r&&i)throw Error(`Two plugins write the site the HTTP host serves: "${r.ownerPluginId}" and "${i.ownerPluginId}"`);let n=(o,s,a,l)=>{let d=e[o];if(r&&s!==void 0&&d!==void 0&&Va(d)!==Va(s))throw Error(`http.${o} "${d}" is not where "${r.ownerPluginId}" writes the ${a} ("${s}"); remove it or set it to the same directory`);return s??d??l};return{productionDistDir:n("productionDistDir",r?.productionOutputDir,"production site",tf),previewDistDir:n("previewDistDir",r?.previewOutputDir,"preview site",rf),sharedImagesDir:n("sharedImagesDir",r?.sharedImagesDir,"shared images",nf)}}async function af(e,t,r){let i=[e.productionDistDir,...t?[e.previewDistDir]:[]];for(let n of i){if(Vm(n))continue;await Ym(n,{recursive:!0}),await Xm(ef(n,"index.html"),Ci),r.debug(`Created site directory at ${n}`)}}function Xa(e){return e?{siteUrl:`https://${e}`,previewUrl:`https://${Ya(e)}`}:{siteUrl:void 0,previewUrl:void 0}}function ec(e){let{config:t,logger:r}=e,{siteUrl:i,previewUrl:n}=Xa(e.domain),o;return{start:async()=>{let s=sf(t,of(e.getPlugins()));await af(s,t.preview,r),o??=new Vt({logger:r,productionDistDir:s.productionDistDir,sharedImagesDir:s.sharedImagesDir,productionPort:t.port,...t.hostname?{hostname:t.hostname}:{},...t.preview&&{previewDistDir:s.previewDistDir},getOperationalInfo:e.getOperationalInfo,getReadinessData:e.getReadinessData,getRoutes:e.getRoutes,executeTool:Pi(e.messageBus,H)}),await o.start()},stop:async()=>{await o?.stop()},healthCheck:async()=>{let s=o?.getStatus(),a=s?.running??!1,l=i??s?.productionUrl??`http://localhost:${t.port}`,d=n??s?.previewUrl??`http://localhost:${t.port}`,u=[];if(a){if(u.push(`Production: ${l}`),s?.previewUrl)u.push(`Preview: ${d}`)}return{status:a?"healthy":"error",message:a?u.join(", "):"Webserver not running",lastCheck:new Date,details:{preview:!!s?.previewUrl,production:a,previewUrl:s?.previewUrl?d:void 0,productionUrl:a?l:void 0}}}}}function tc(e,t){let{siteUrl:r,previewUrl:i}=Xa(t);if(!r)return{endpoints:[],interactions:[]};let n=e.preview&&i?i:void 0;return{endpoints:[{pluginId:H,label:"Site",url:r,priority:10},...n?[{pluginId:H,label:"Preview",url:n,priority:20,visibility:"admin"}]:[]],interactions:[{pluginId:H,id:"site",label:"Public site",description:"Visit the published public site for this brain.",href:r,kind:"human",priority:10},...n?[{pluginId:H,id:"preview",label:"Preview site",description:"Open the private preview build.",href:n,kind:"admin",priority:20,visibility:"admin"}]:[]]}}var cf=["shell.legacy-binary-content"];async function rc(e,t){for(let r of cf){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 lf=250,df=c.object({projectionBatch:c.object({operationId:c.string().min(1),childKey:c.string().min(1)})});class Ti{config;services;lifecycle;initializer;role;hooks;constructor(e,t,r,i,n,o){this.config=e,this.services=t,this.lifecycle=r,this.initializer=i,this.role=Ce(n),this.hooks=o}async boot(e){this.services.logger.debug("Starting Shell boot");let t=this.initializer;await Xt([()=>this.services.entityService.initialize(),()=>this.services.jobQueueService.initialize?.()??Promise.resolve(),()=>this.services.runtimeStateService.initialize(),()=>this.services.conversationService.initialize?.()??Promise.resolve()]);let r={...this.config.entityDisplay!==void 0&&{entityDisplay:this.config.entityDisplay},...!this.role.serves&&{executionOnly:!0}};if(await t.initializeAll(this.services.templateRegistry,this.services.entityRegistry,this.services.pluginManager,{...e?.mode==="register-only"&&{registerOnly:!0},...Object.keys(r).length>0&&{registrationContext:r}}),this.services.profileKindRegistry.finalize(),this.services.channelRegistry.finalize(),this.services.inboxRegistry.finalize(),this.services.inboxFollowUpRegistry.finalize(),await this.services.pluginManager.finalizePluginRegistrations(),this.hooks.finalizeHttpRoutes(),await this.services.projectionRuntimeSupervisor.initialize(this.services.pluginManager.getProjectionGraphSnapshot()),t.registerJobHandlers(this.services.jobQueueService,this.services.contentService,this.services.entityService),e?.mode===void 0){let n=await ra({store:this.services.entityService.getProjectionStore(),queue:this.services.jobQueueService,setWakeup:(o)=>this.services.entityService.setProjectionWakeup(o),graph:this.services.pluginManager.getProjectionGraphSnapshot(),rules:this.services.pluginManager.getProjectionRulesSnapshot(),inputContext:this.hooks.createProjectionInputContext(),executionContext:this.hooks.createProjectionExecutionContext(),reconcileTargets:(o)=>this.services.entityService.reconcileProjectionTargets(o),beforeWaveCompletion:async(o)=>{let s=await Qe(this.services.messageBus,ic,o,"shell");if(s.status==="unavailable")return;if(s.failures.length>0||s.answers.length===0)throw Error(`Projection wave ${o.waveId} completion was not acknowledged`)},logger:this.services.logger,createWaveId:nc,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=df.safeParse(JSON.parse(l.data));if(!d.success||d.data.projectionBatch.operationId!==s)return[];return[{jobId:l.id,childKey:d.data.projectionBatch.childKey,status:l.status,terminalAt:l.completedAt}]})),activationMode:this.role.projectionActivation});this.services.disposables.push(()=>n.dispose())}if(this.services.jobQueueService.finalizeHandlerRegistrations(),this.hooks.registerCoreDataSources(),this.role.serves)this.hooks.registerSystemCapabilities();if(e?.mode==="register-only"){this.services.logger.debug("Shell boot complete (register-only mode)");return}if(await rc(this.services.runtimeStateService,this.services.logger),await this.loadIdentityServices(),!this.role.serves){this.services.jobProgressMonitor.start(),await this.services.jobQueueWorker.start(),this.services.logger.debug("Shell boot complete (worker process)");return}let i;if(e?.mode!=="startup-check"){await this.startHttpHost(),await this.services.entityService.reprojectRegisteredGroupings();let n=await this.services.entityService.rewriteRetiredFields();if(n.rewritten>0)this.services.logger.info("Rewrote entities carrying retired fields",{rewritten:n.rewritten});let o=await this.services.entityService.reconcileDeclaredMetadata();if(o.reconciled>0)this.services.logger.info("Re-derived declared entity metadata",{reconciled:o.reconciled});let s=lc();if(this.services.disposables.push(this.services.messageBus.subscribe(Ke.initialSyncCompleted,async(l)=>(s.resolve(ac.safeParse(l.payload).data?.success===!0),{success:!0}))),await this.emitPluginsRegistered())i=s.promise.then(async(l)=>{if(l)return this.settleStartupContent();this.services.logger.warn("Initial sync failed; ready-state defaults are not created")}).catch((l)=>{this.services.logger.error("Failed to settle startup content",l)});else await this.settleStartupContent()}else await this.prepareReadyState();if(await this.services.pluginManager.readyPlugins(),e?.mode==="startup-check"){this.services.logger.debug("Shell boot complete (startup-check mode)");return}if(await this.startRuntimeServices(),i)i.then(()=>this.startIndexReadinessMonitor()).catch((n)=>{this.services.logger.warn("Semantic index readiness monitor did not start",n)});else await this.startIndexReadinessMonitor();this.services.logger.debug("Shell boot complete")}async startHttpHost(){if(!this.services.daemonRegistry.has(K))return;await this.services.daemonRegistry.start(K),this.services.logger.debug("Started the HTTP host before initial sync")}async emitPluginsRegistered(){let e=await this.services.messageBus.collect({type:Ke.pluginsRegistered,payload:{timestamp:new Date().toISOString(),pluginCount:this.services.pluginManager.getAllPluginIds().length},sender:"shell"});return this.services.logger.debug("Emitted plugins registered event"),e.some((t)=>("data"in t)&&sc.safeParse(t.data).data?.initialSyncPending===!0)}async settleStartupContent(){await this.prepareReadyState(),await Ee(this.services.messageBus,cc,{timestamp:new Date().toISOString()},"shell"),this.services.logger.debug("Emitted startup content settled event")}async loadIdentityServices(){await Xt([()=>this.services.identityService.refreshCache(),()=>this.services.profileService.refreshCache(),()=>this.services.canonicalIdentityService.refreshCache()]),this.services.logger.debug("Identity services loaded")}async initializeIdentityServices(){await Xt([()=>this.services.identityService.initialize(),()=>this.services.profileService.initialize(),()=>this.services.canonicalIdentityService.refreshCache()]),this.services.logger.debug("Identity services initialized")}async prepareReadyState(){await this.initializeIdentityServices();let{logger:e}=this.services,t=await oc(this.services.templateRegistry,this.services.entityService);if(t.created.length>0)e.debug(`Materialized ${t.created.length} prompt entities`);if(t.refreshed.length>0)e.info("Refreshed untouched prompts to their current defaults",{targets:t.refreshed});if(t.retitled.length>0)e.info("Corrected generated prompt titles",{targets:t.retitled});if(t.staleOverrides.length>0)e.info("Edited prompts are based on an older default",{targets:t.staleOverrides});if(t.unverifiedOverrides.length>0)e.info("Prompts without provenance differ from their default and are kept; delete one to restore its default",{targets:t.unverifiedOverrides});for(let{target:r,error:i}of t.failed)e.warn(`Could not sync prompt ${r}: ${i}`)}async startRuntimeServices(){for(let e of["shell:recurring-checks","shell:guest-retention"])if(this.services.daemonRegistry.has(e))await this.services.daemonRegistry.start(e);if(await this.services.pluginManager.startPluginDaemons(),this.role.executes)await this.services.jobQueueWorker.start();this.services.jobProgressMonitor.start(),await this.services.batchJobManager.start()}async startIndexReadinessMonitor(){await this.lifecycle.fork(this.runIndexReadinessMonitor())}runIndexReadinessMonitor(){let{entityService:e,logger:t}=this.services;return w.tryPromise({try:()=>e.backfillMissingEmbeddings(),catch:(i)=>i}).pipe(w.tap((i)=>w.sync(()=>{t.debug("Queued missing embedding backfill jobs",i)})),w.catch((i)=>w.sync(()=>{t.warn("Embedding backfill failed",i)}))).pipe(w.andThen(w.tryPromise({try:(i)=>e.awaitIndexReady({intervalMs:lf,signal:i}),catch:(i)=>i}).pipe(w.tap((i)=>w.sync(()=>{if(i.degraded)t.warn("Semantic index ready with degraded embeddings",i);else t.debug("Semantic index ready",i)})),w.catch((i)=>w.sync(()=>{t.warn("Semantic index readiness monitor stopped",i)})))))}}var uf=c.object({}),dc=c.string().regex(/^\d{4}-(0[1-9]|1[0-2])$/,"Expected YYYY-MM"),pc=c.array(c.string().min(1)).min(1).optional().describe("Only these entity types"),pf=c.object({entityTypes:pc,from:dc.optional().describe("First month, YYYY-MM"),to:dc.optional().describe("Last month, YYYY-MM")}),mf=c.object({staleDays:c.number().int().min(1).max(3650).default(90).describe("Days without an update before content counts as stale"),entityTypes:pc});function mc(e){let t=new uc;return t.register(er({type:"overview",description:"Entity counts by type, recent activity, and draft and published totals.",params:uf,handler:async(r,{entityService:i,visibilityScope:n})=>ff(i,n)})),t.register(er({type:"publishing-cadence",description:"Pieces per month, by type: counted in the month they were published, or created when never published.",params:pf,handler:async(r,{entityService:i,visibilityScope:n})=>hf(i,n,r)})),t.register(er({type:"content-health",description:"Drafts and content not updated for a long time.",params:mf,handler:async(r,{entityService:i,visibilityScope:n})=>yf(i,n,e,r)})),t}async function ff(e,t){let r=await e.getEntityCounts(t),i={},n=0;for(let{entityType:f,count:g}of r)i[f]=g,n+=g;let o=await Ei(e,t),s=Date.now(),a=s-604800000,l=s-2592000000,d=0,u=0;for(let f of o){let g=new Date(f.created).getTime();if(g>=a)d++;if(g>=l)u++}let p=gc(o),m=o.filter((f)=>f.metadata.status==="published");return{entityCounts:i,totalEntities:n,recentActivity:{last7days:d,last30days:u},contentHealth:{drafts:p.length,published:m.length}}}function gf(e){let t=e.metadata.publishedAt;return new Date(typeof t==="string"&&t?t:e.created)}function fc(e,t){return t?e.filter((r)=>t.includes(r.entityType)):e}async function hf(e,t,r){let i=fc(await Ei(e,t),r.entityTypes),n=new Map;for(let s of i){let a=gf(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 yf(e,t,r,i){let n=fc(await Ei(e,t),i.entityTypes),o=gc(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 gc(e){return e.filter((t)=>t.metadata.status==="draft")}async function Ei(e,t){let r=e.getEntityTypes(),i=[];for(let n of r){let o=await e.listEntities({entityType:n,options:{limit:1000,filter:{visibilityScope:t}}});i.push(...o)}return i}class rt{parse;idOf;items=new Map;constructor(e,t){this.parse=e,this.idOf=t}register(e){let t=this.parse(e);this.items.set(this.keyFor(t.pluginId,this.idOf(t)),t)}unregister(e,t){if(t!==void 0){this.items.delete(this.keyFor(e,t));return}let r=`${e}:`;for(let i of this.items.keys())if(i.startsWith(r))this.items.delete(i)}list(){return Array.from(this.items.values()).sort((e,t)=>e.priority-t.priority||e.label.localeCompare(t.label))}keyFor(e,t){return`${e}:${t}`}}class Ai extends rt{constructor(){super((e)=>hc.parse(e),(e)=>e.url)}}class ki extends rt{constructor(){super((e)=>yc.parse(e),(e)=>e.id)}}function vc(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 vf=["/health","/images"],bf=new Set([Kt]),Sf=new Set(bc),Rf=new Set(["GET","POST","PUT","DELETE"]);function Sc(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 Rc(e){return bf.has(e)||vf.some((t)=>e===t||e.startsWith(`${t}/`))}function ji(e,t,r=!0){let i;try{i=new URL(e,"http://route.invalid").pathname}catch{i=void 0}if(!e.startsWith("/")||e.includes("//")||e.includes("?")||e.includes("#")||e.includes("%")||e.length>1&&e.endsWith("/")||e.trim()!==e||i!==e||r&&Rc(e))throw Error(`Invalid HTTP route path "${e}" declared by plugin "${t}"`)}function wc(e,t,r){if(!e.has(t))throw Error(`Invalid HTTP route method "${t}" declared by plugin "${r}"`)}function wf(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 If(e,t){ji(t.path,e.pluginId);let r=t.method??"GET";wc(Sf,r,e.pluginId);let i=t.match??"exact";wf(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)=>!Rc(o)&&n(o)}:{},handler:t.handler})}function xf(e,t){ji(t.path,e.pluginId,!1);let r=`/api/${e.pluginId}${t.path}`;if(ji(r,e.pluginId),wc(Rf,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 Pf(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 Cf(e){return Object.freeze(e.map((t)=>Object.freeze({ownerPluginId:t.ownerPluginId,kind:t.kind,method:t.method,fullPath:t.fullPath,match:t.match,sharedHostAdmission:t.sharedHostAdmission})))}class tr{routes;manifest;apiRoutes;webRoutes;static createFresh(){return new tr}constructor(){}finalize(e){if(this.routes!==void 0)throw Error("HTTP route registry has already been finalized");let t=[],r=[],i=[];for(let n of e){for(let o of n.webRoutes)t.push(If(n,o)),r.push(Object.freeze({pluginId:n.pluginId,fullPath:o.path,definition:Object.freeze({...o})}));for(let o of n.apiRoutes){let s=xf(n,o);t.push(s),i.push(Object.freeze({pluginId:n.pluginId,fullPath:s.fullPath,definition:s.definition}))}}return Pf(t),this.routes=Object.freeze(t),this.manifest=Cf(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 Ic(e,t){e.addFinalizer(async()=>{let{entityService:r}=t;if(Tf(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 Tf(e){return"releaseDatabaseLease"in e&&typeof e.releaseDatabaseLease==="function"}function xc(e){return Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength)}var Ef=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")]),Cc=c.object({query:c.string().describe("Search term"),scope:Ef.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")}),Tc=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.")}),Ec=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)")}),Ac=c.string().min(1).describe("Upload id from the conversation's upload refs"),kc=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(),jc=c.enum(["extract-markdown","preserve"]).describe("extract-markdown imports upload text into a note-like entity; preserve saves raw uploaded bytes via the registered upload-save handler and derives the durable entity type from media type. Use preserve only for explicit file/document preservation, not for saving an assistant summary response."),nt=c.object({kind:c.literal("uploads").describe("Keep several uploaded files from one request: one call listing every attached file, never one call per file; entityType names the note type for extract-markdown files, or another type such as post."),items:c.array(c.strictObject({id:Ac,transform:jc,title:c.string().optional().describe("Only a title the user named for this file."),fields:c.record(c.string(),c.unknown()).optional().describe("Frontmatter the user stated for this file alone, such as the date and address it was first published at: { publishedAt, canonicalUrl }; facts shared by every file go in the top-level fields.")},{error:(e)=>e.code==="unrecognized_keys"&&e.keys.includes("upload")?"Each file is `{ id, transform }`; its `upload` object was removed.":void 0})).min(2).max(20)}).strict(),Di=c.discriminatedUnion("kind",[c.object({kind:c.literal("text").describe("Store exact/direct user-provided content without generation"),content:c.string().min(1).describe("Literal content for a direct save request without a stored user-message source. For pasted text already in this conversation, prefer source.kind user-message with exact boundaries instead of reproducing the body here.")}).strict(),kc,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:Ac,transform:jc},{error:(e)=>e.code==="unrecognized_keys"&&e.keys.includes("upload")?'The upload id goes in `source.id`: `{ kind: "upload", id, transform }`; `source.upload` was removed.':void 0}),nt,c.object({kind:c.literal("prior-response").describe("Save a previous assistant response as durable content, especially an assistant summary or answer about an upload."),messageId:c.string().min(1).optional().describe("Stored assistant message ID; omit for latest savable")}).strict(),c.object({kind:c.literal("entity").describe("Reuse an existing entity's text verbatim, without its frontmatter, as a new entity of another type ('turn my note X into a post'). For new text written from a source, use system_generate prompt-from-source."),entityType:c.string().min(1).describe("Source entity type, such as note"),entityId:c.string().min(1).describe("Source entity ID, slug, or exact title copied from the user's request or a prior tool result")}).strict()]),Af=c.discriminatedUnion("kind",[c.object({kind:c.literal("prompt").describe("A new non-image entity from a broad prompt; this branch has no source field."),entityType:c.string().min(1).describe("Entity type to generate from the prompt. Do not use image here; use standalone-image or cover-image."),title:c.string().optional().describe("Title for the generated entity"),prompt:c.string().min(1).describe("Prompt for creating new generated content, written from the user's request without added voice, tone or engagement directions; the style guide supplies the voice.")}).strict(),c.object({kind:c.literal("prompt-from-source").describe("A new non-image entity grounded in a resolved existing entity, such as a newsletter from a blog post."),entityType:c.string().min(1).describe("Entity type to generate from the source and prompt. Do not use image here; use standalone-image or cover-image."),title:c.string().optional().describe("Title for the generated entity"),source:c.object({entityType:c.string().min(1).describe("Resolved content source entity type, such as post for a newsletter from a blog post. Do not use brain-character or anchor-profile."),entityId:c.string().min(1).describe("Resolved source entity ID from a prior tool result or typed entity ref.")}).strict().describe("The resolved existing entity that grounds this generation."),additionalSourceIds:c.array(c.string().min(1)).optional().describe("More source IDs of the same type."),prompt:c.string().min(1).optional().describe("Direction from the user's request, without added voice, tone or engagement directions; the style guide supplies the voice. Omit if none is given.")}).strict(),c.object({kind:c.literal("standalone-image").describe("An unattached image; never a substitute for a requested cover."),title:c.string().optional().describe("Title for the generated image"),prompt:c.string().min(1).describe("Prompt for creating an unattached image. Not for cover images requested for a generated post/entity.")}).strict(),c.object({kind:c.literal("cover-image").describe("An image attached as coverImageId to an existing entity whose real id is known."),target:c.object({entityType:c.string().min(1).describe("Existing target entity type. Use the actual type of the entity being covered: social-post for LinkedIn/social posts, post for blog posts, etc."),entityId:c.string().min(1).describe("Existing target entity ID from a prior tool result or typed entity ref")}).strict().describe("Existing entity that should receive the generated coverImageId"),title:c.string().optional().describe("Title for the generated image"),prompt:c.string().min(1).describe("Prompt for creating the cover image")}).strict(),c.object({kind:c.literal("attachment").describe("Generate a deterministic durable artifact from an existing entity attachment provider"),source:c.object({entityType:c.string().min(1).describe("Source entity type"),entityId:c.string().min(1).describe("Canonical source entity ID from a prior tool result or typed entity ref")}).strict().describe("The resolved existing entity whose attachment provider renders the artifact."),attachmentType:c.string().min(1).describe('Source artifact type such as "carousel", "printable", or "og-image"'),title:c.string().optional().describe("Title for the generated artifact"),replace:c.boolean().optional().describe("Set true for regenerate, replace, refresh, or update requests so a deterministic artifact is regenerated instead of reused")}).strict()]),rr=c.object({entityType:c.string().describe("Entity type to create. Use wish for explicitly saved or tracked unmet requested capabilities or outcomes."),title:c.string().optional().describe("Title for a new entity. Leave it out when saving several uploads: each item in source.items takes its own title."),visibility:Pc.optional().describe("Content visibility. Omit for public. Use shared for team/collaborator content readable by Trusted and Admin callers. Use restricted for private/admin-only content."),source:Di.describe("Concrete source selector. Use exactly one source branch. For AI generation or source-derived artifacts, use system_generate instead."),fields:c.record(c.string(),c.unknown()).optional().describe("Frontmatter for facts the user states outside the source text, e.g. a post first published elsewhere: { status: 'published', publishedAt: '2025-03-12', canonicalUrl }; the section a doc goes in, named exactly as the user names it: { section }; the year a project began: { year }. Never copy values from the text or its frontmatter; omit when nothing extra is stated."),replace:c.boolean().optional().describe("Create a new copy intentionally"),confirmed:c.literal(!0).optional().describe("Confirm the creation"),confirmationToken:c.string().optional().describe("Internal confirmation token returned by the confirmation flow")}).strict(),Dc=c.object({operation:Af.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(),kf=c.object({oldText:c.string().min(1).describe("Exact text occurring once in the original stored Markdown. Include enough context to be unique."),newText:c.string().describe("Literal replacement text; empty string deletes oldText.")}).strict(),it="An update operation is exactly one of `fields`, `content`, `edits` or `source`.",Oi=c.strictObject({fields:c.record(c.string(),c.unknown()).optional().describe("Update partial frontmatter or metadata fields. Partial frontmatter fields to update. Use this for status, title, coverImageId, ogImageId, and metadata changes such as approving an agent. To set an existing image as an entity cover, set coverImageId to that image id. To remove or clear a cover image, set coverImageId to null, not an empty string. Do not use fields for anchor-profile; anchor-profile updates require the content operation."),content:c.string().optional().describe("Replace the stored Markdown. Full replacement text you wrote yourself, stored literally. Text without frontmatter replaces the body and keeps the stored frontmatter; text with frontmatter replaces the whole document. When the user supplied the replacement text, use the source operation instead of copying it here. For small changes, use the edits operation instead of regenerating the whole document."),edits:c.array(kf).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:kc.optional().describe("Replace the stored Markdown with user-supplied text. Full replacement taken verbatim from a user message, for large rewrites the user supplied. Select the text with exact boundaries instead of copying it into content. Text without frontmatter replaces the body and keeps the stored frontmatter; text with frontmatter replaces the whole document.")},{error:(e)=>{if(e.code!=="unrecognized_keys")return;if(e.keys.includes("kind"))return ie(e.input)&&e.input.kind==="user-message"?'A user-message source is the source operation: put it under `source`, as in `{ source: { kind: "user-message", ... } }`.':"An update operation has no `kind`: name it by its field, as in `{ edits: [...] }`.";return`Unrecognized key ${e.keys.map((t)=>`"${t}"`).join(", ")}: ${it}`}}).refine((e)=>[e.fields,e.content,e.edits,e.source].filter((t)=>t!==void 0).length===1,{message:it}).describe(it),ir=c.object({entityType:c.string().describe("Entity type"),id:c.string().describe("Entity ID, slug, or title"),operation:Oi.describe("Exactly one update operation"),confirmed:c.literal(!0).optional().describe("Confirm the update"),confirmationToken:c.string().optional().describe("Internal confirmation token returned by the confirmation flow"),contentHash:c.string().optional().describe("Content hash for optimistic concurrency")}).strict(),Oc=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")}),jP=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")}),zc=c.object({batchId:c.string().optional().describe("Specific batch ID to check"),jobTypes:c.array(c.string()).optional().describe("Filter by job types")}),jf=c.object({entityType:c.string().optional(),entityId:c.string().optional(),attachmentType:c.string().optional()}),Df=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:jf.optional()}),DP=c.object({entityId:c.string().optional(),status:c.enum(["created","generating"]),jobId:c.string().optional(),attachment:Df.optional()}),OP=c.object({status:c.literal("extracting"),jobId:c.string(),entityType:c.string(),source:c.string().optional(),mode:c.enum(["derive","rebuild"]).optional()});function Uc(e,t,r){return r==="create"?e.getCreateFieldsSchema(t):e.getEditableFieldsSchema(t)}function Bc(e){if(e instanceof c.ZodOptional||e instanceof c.ZodNullable||e instanceof c.ZodDefault)return Bc(e.unwrap());return e instanceof c.ZodType?e:void 0}function Mc(e){try{let{$schema:t,...r}=c.toJSONSchema(e,{target:"draft-7",io:"input"});return r}catch{return}}function Of(e){return Lc({type:"object",properties:{value:e},required:["value"]})!==void 0}function $c(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=Uc(e,d,t.on);for(let[p,m]of Object.entries(u?.shape??{})){if(t.omit?.includes(p))continue;let f=Bc(m),g=f&&Mc(f);if(!f||!g||!Of(g))continue;let h=r.get(p)??new Map;h.set(JSON.stringify(g),f),r.set(p,h),i.set(p,[...i.get(p)??[],d])}}let o=new Map;for(let[d,u]of r){let[p,...m]=[...u.values()];if(!p)continue;let f=m.length>0?c.union([p,...m]):p,g=JSON.stringify(Mc(f)),h=o.get(g)??{value:f,names:[]};h.names.push(d),o.set(g,h)}let s=[...o.values()].map(({value:d,names:u})=>{let[p,...m]=u,f=u.map((g)=>{let h=i.get(g)??[];return`${g} (${h.length===n.length?"every type":h.join(", ")})`}).join("; ");return c.strictObject({name:(m.length>0&&p!==void 0?c.enum([p,...m]):c.literal(p??"")).describe(`The field, set only on the entity types named: ${f}.`),value:t.on==="update"?d.nullable():d})}),[a,...l]=s;return c.array(a?l.length>0?c.union([a,...l]):a:c.never())}function zf(e){return Object.fromEntries((Array.isArray(e)?e:[]).flatMap((t)=>V(t)&&typeof t.name==="string"?[[t.name,t.value]]:[]))}function nr(e,t,r,i){if(!r)return;let{allow:n}=i,o=new Set(Object.keys(Uc(e,t,i.on)?.shape??{})),s=Object.keys(r).filter((d)=>!o.has(d)&&!n.includes(d));if(s.length===0)return;let a=s.map((d)=>`"${d}"`).join(", "),l=[...o].join(", ")||"none";return`A ${t} has no ${s.length>1?"fields":"field"} ${a} a caller can set; its fields are ${l}.`}function Mi(e){return"fields"in e&&e.fields!==void 0?{...e,fields:zf(e.fields)}:e}function _c(e,t){return{prepare:()=>e.ensureGroupingsCurrent(),inputSchema:()=>{let r=$c(e,{on:"create",omit:["visibility"],...t&&{neverWrites:t}}),i=nt.shape.items.element,n=nt.extend({items:c.array(i.extend({fields:r.optional().describe("Field changes the user stated for this file alone, one { name, value } per field, such as the date and address it was first published at: [{ name: 'publishedAt', value }, { name: 'canonicalUrl', value }]; facts shared by every file go in the top-level fields.")})).min(2).max(20)}),[o,...s]=Di.options.map((a)=>a===nt?n:a);if(!o)throw Error("system_create has no source branches");return{...rr.shape,source:c.discriminatedUnion("kind",[o,...s]).describe("Concrete source selector. Use exactly one source branch. For AI generation or source-derived artifacts, use system_generate instead."),fields:r.optional().describe("Field changes for facts the user states outside the source text, one { name, value } per field, e.g. a post first published elsewhere: [{ name: 'status', value: 'published' }, { name: 'publishedAt', value: '2025-03-12' }, { name: 'canonicalUrl', value }]; the section a doc goes in, named exactly as the user names it: [{ name: 'section', value }]; the year a project began: [{ name: 'year', value }]. Never copy values from the text or its frontmatter; omit when nothing extra is stated.")}},toToolInput:(r)=>{let i=r.source;return Mi({...r,...V(i)&&Array.isArray(i.items)&&{source:{...i,items:i.items.map((n)=>V(n)?Mi(n):n)}}})}}}function zi(e){let t=e.unwrap();return e.description?t.describe(e.description):t}function Fc(e,t){let{content:r,edits:i,source:n}=Oi.shape;return{prepare:()=>e.ensureGroupingsCurrent(),inputSchema:()=>({...ir.shape,operation:c.union([c.strictObject({fields:$c(e,{on:"update",...t&&{neverWrites:t}}).describe("Change frontmatter or metadata fields, one { name, value } per field changed. Use this for status, title, coverImageId, ogImageId, and metadata changes such as approving an agent. To set an existing image as an entity cover, change coverImageId to that image id. To remove a field, such as a cover image, give it the value null, not an empty string. Do not use fields for anchor-profile; anchor-profile updates require the content operation.")}),c.strictObject({content:zi(r)}),c.strictObject({edits:zi(i)}),c.strictObject({source:zi(n)})]).describe("Exactly one update operation")}),toToolInput:(o)=>{let s=o.operation;return V(s)?{...o,operation:Mi(s)}:o}}}function B(e,t,r,i){try{e.permissionService.assertEntityActionAllowed(t,r,i.userPermissionLevel);return}catch(n){if(n instanceof Error)return{success:!1,error:n.message};throw n}}function De(e){return(t,r)=>e.getEntityActionRequiredLevel(t,r)==="never"}var Mf="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:`${Mf}_${e}`,description:t,inputSchema:r.shape,handler:async(a,l)=>{let d=r.safeParse(a);if(!d.success)return{success:!1,error:`Invalid input: ${d.error.issues.map((u)=>`${u.path.join(".")}: ${u.message}`).join(", ")}`};try{return await i(d.data,l)}catch(u){return{success:!1,error:P(u)}}},visibility:o,...s?{sideEffects:s}:{}}}function sr(e){return{interfaceType:e.interfaceType,actor:e.actor,userPermissionLevel:e.userPermissionLevel??"public",...e.channelId&&{channelId:e.channelId},...e.channelName&&{channelName:e.channelName}}}async function Nc(e,t,r,i){let n=await t(r,sr(i));if(n.kind==="handled")return{kind:"handled",result:n.result};let o=n.input;if(o.visibility!==r.visibility)return{kind:"error",result:{success:!1,error:"Create interceptor changed or dropped the requested entity visibility."}};let s=B(e,o.entityType,"create",i);if(s)return{kind:"error",result:s};return{kind:"continue",createInput:o}}function Oe(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 ze(e){let t={...e.conversationId?{conversationId:e.conversationId}:{},...e.channelId?{channelId:e.channelId}:{},...e.runId?{runId:e.runId}:{},...e.toolCallId?{toolCallId:e.toolCallId}:{}};return Object.keys(t).length>0?t:void 0}function Li(e,t){if(t.getEntityTypeConfig(e.entityType).binaryStorage)return{...e,content:`[binary ${e.entityType} data \u2014 use metadata for ${e.entityType} info]`};return e}function ar(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var Lf={base:"note"};function Zc(e){return Lf[e]??e.replaceAll("-"," ")}function Me(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 Hc(e){return!!e&&Object.keys(e.shape).length>0}async function Wc(e,t,r){if(!r)return!1;let i=await e.conversationService.getMessages(r,{limit:100});for(let n of i){let s=or(n.metadata)?.attachments;if(!Array.isArray(s))continue;for(let a of s){if(!ie(a))continue;let l=a.source;if(!ie(l))continue;if(l.kind===t.kind&&l.id===t.id)return!0}}return!1}async function cr(e,t,r){if(t.replace||!t.candidateId)return{kind:"ok",value:void 0};let i=await e.entityService.getEntity({entityType:t.entityType,id:t.candidateId,visibilityScope:A(r.userPermissionLevel)});if(!i)return{kind:"ok",value:void 0};if(i.metadata.status==="failed"&&r.userPermissionLevel==="admin"&&!B(e,t.entityType,"delete",r))return{kind:"ok",value:{entityType:i.entityType,id:i.id}};return T(`A ${t.entityType} already exists for "${t.candidateId}". To change it, use system_update on that ${t.entityType} in this turn, without asking first; pass replace:true to ${t.copyHint}.`)}function qc(e){return`Replaces: failed ${e.entityType} "${e.id}"`}async function Jc(e,t){if(!t)return;try{await e.entityService.deleteEntity(t);return}catch(r){return{success:!1,error:P(r,"Failed to replace the failed entity")}}}function lr(e,t,r){let i=Oe(e,t);if(i)return X(i);let n=B(e,t,"create",r);if(n)return X(n);return{kind:"ok",value:{interceptor:e.entityRegistry.getCreateInterceptor(t)}}}async function dr(e){let{gate:t,input:r,replacesFailed:i}=e;if(r.confirmed){let d=t.validateConfirmed(r.confirmationToken,r);if(d)return d;return e.run()}let{toolName:n,summary:o,completionSummary:s,preview:a,args:l}=e.confirmation();return{needsConfirmation:!0,toolName:n,summary:o,...s!==void 0&&{completionSummary:s},preview:i?`${a}
77
+ </html>`;var Ka=c.strictObject({productionOutputDir:c.string().min(1),previewOutputDir:c.string().min(1),sharedImagesDir:c.string().min(1)});var H="webserver",K=`${H}:${H}`,tf="./dist/site-production",rf="./dist/site-preview",nf="./dist/images";function of(e){return[...e].flatMap((t)=>{let r=t.getStaticSiteOutput?.();return r?[{...Ka.parse(r),ownerPluginId:t.id}]:[]})}function sf(e,t){let[r,i]=t;if(r&&i)throw Error(`Two plugins write the site the HTTP host serves: "${r.ownerPluginId}" and "${i.ownerPluginId}"`);let n=(o,s,a,l)=>{let d=e[o];if(r&&s!==void 0&&d!==void 0&&Va(d)!==Va(s))throw Error(`http.${o} "${d}" is not where "${r.ownerPluginId}" writes the ${a} ("${s}"); remove it or set it to the same directory`);return s??d??l};return{productionDistDir:n("productionDistDir",r?.productionOutputDir,"production site",tf),previewDistDir:n("previewDistDir",r?.previewOutputDir,"preview site",rf),sharedImagesDir:n("sharedImagesDir",r?.sharedImagesDir,"shared images",nf)}}async function af(e,t,r){let i=[e.productionDistDir,...t?[e.previewDistDir]:[]];for(let n of i){if(Vm(n))continue;await Ym(n,{recursive:!0}),await Xm(ef(n,"index.html"),Ci),r.debug(`Created site directory at ${n}`)}}function Xa(e){return e?{siteUrl:`https://${e}`,previewUrl:`https://${Ya(e)}`}:{siteUrl:void 0,previewUrl:void 0}}function ec(e){let{config:t,logger:r}=e,{siteUrl:i,previewUrl:n}=Xa(e.domain),o;return{start:async()=>{let s=sf(t,of(e.getPlugins()));await af(s,t.preview,r),o??=new Vt({logger:r,productionDistDir:s.productionDistDir,sharedImagesDir:s.sharedImagesDir,productionPort:t.port,...t.hostname?{hostname:t.hostname}:{},...t.preview&&{previewDistDir:s.previewDistDir},getOperationalInfo:e.getOperationalInfo,getReadinessData:e.getReadinessData,getRoutes:e.getRoutes,executeTool:Pi(e.messageBus,H)}),await o.start()},stop:async()=>{await o?.stop()},healthCheck:async()=>{let s=o?.getStatus(),a=s?.running??!1,l=i??s?.productionUrl??`http://localhost:${t.port}`,d=n??s?.previewUrl??`http://localhost:${t.port}`,u=[];if(a){if(u.push(`Production: ${l}`),s?.previewUrl)u.push(`Preview: ${d}`)}return{status:a?"healthy":"error",message:a?u.join(", "):"Webserver not running",lastCheck:new Date,details:{preview:!!s?.previewUrl,production:a,previewUrl:s?.previewUrl?d:void 0,productionUrl:a?l:void 0}}}}}function tc(e,t){let{siteUrl:r,previewUrl:i}=Xa(t);if(!r)return{endpoints:[],interactions:[]};let n=e.preview&&i?i:void 0;return{endpoints:[{pluginId:H,label:"Site",url:r,priority:10},...n?[{pluginId:H,label:"Preview",url:n,priority:20,visibility:"admin"}]:[]],interactions:[{pluginId:H,id:"site",label:"Public site",description:"Visit the published public site for this brain.",href:r,kind:"human",priority:10},...n?[{pluginId:H,id:"preview",label:"Preview site",description:"Open the private preview build.",href:n,kind:"admin",priority:20,visibility:"admin"}]:[]]}}var cf=["shell.legacy-binary-content"];async function rc(e,t){for(let r of cf){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 lf=250,df=c.object({projectionBatch:c.object({operationId:c.string().min(1),childKey:c.string().min(1)})});class Ti{config;services;lifecycle;initializer;role;hooks;constructor(e,t,r,i,n,o){this.config=e,this.services=t,this.lifecycle=r,this.initializer=i,this.role=Ce(n),this.hooks=o}async boot(e){this.services.logger.debug("Starting Shell boot");let t=this.initializer;await Xt([()=>this.services.entityService.initialize(),()=>this.services.jobQueueService.initialize?.()??Promise.resolve(),()=>this.services.runtimeStateService.initialize(),()=>this.services.conversationService.initialize?.()??Promise.resolve()]);let r={...this.config.entityDisplay!==void 0&&{entityDisplay:this.config.entityDisplay},...!this.role.serves&&{executionOnly:!0}};if(await t.initializeAll(this.services.templateRegistry,this.services.entityRegistry,this.services.pluginManager,{...e?.mode==="register-only"&&{registerOnly:!0},...Object.keys(r).length>0&&{registrationContext:r}}),this.services.profileKindRegistry.finalize(),this.services.channelRegistry.finalize(),this.services.inboxRegistry.finalize(),this.services.inboxFollowUpRegistry.finalize(),await this.services.pluginManager.finalizePluginRegistrations(),this.hooks.finalizeHttpRoutes(),await this.services.projectionRuntimeSupervisor.initialize(this.services.pluginManager.getProjectionGraphSnapshot()),t.registerJobHandlers(this.services.jobQueueService,this.services.contentService,this.services.entityService),e?.mode===void 0){let n=await ra({store:this.services.entityService.getProjectionStore(),queue:this.services.jobQueueService,setWakeup:(o)=>this.services.entityService.setProjectionWakeup(o),graph:this.services.pluginManager.getProjectionGraphSnapshot(),rules:this.services.pluginManager.getProjectionRulesSnapshot(),inputContext:this.hooks.createProjectionInputContext(),executionContext:this.hooks.createProjectionExecutionContext(),reconcileTargets:(o)=>this.services.entityService.reconcileProjectionTargets(o),beforeWaveCompletion:async(o)=>{let s=await Qe(this.services.messageBus,ic,o,"shell");if(s.status==="unavailable")return;if(s.failures.length>0||s.answers.length===0)throw Error(`Projection wave ${o.waveId} completion was not acknowledged`)},logger:this.services.logger,createWaveId:nc,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=df.safeParse(JSON.parse(l.data));if(!d.success||d.data.projectionBatch.operationId!==s)return[];return[{jobId:l.id,childKey:d.data.projectionBatch.childKey,status:l.status,terminalAt:l.completedAt}]})),activationMode:this.role.projectionActivation});this.services.disposables.push(()=>n.dispose())}if(this.services.jobQueueService.finalizeHandlerRegistrations(),this.hooks.registerCoreDataSources(),this.role.serves)this.hooks.registerSystemCapabilities();if(e?.mode==="register-only"){this.services.logger.debug("Shell boot complete (register-only mode)");return}if(await rc(this.services.runtimeStateService,this.services.logger),await this.loadIdentityServices(),!this.role.serves){this.services.jobProgressMonitor.start(),await this.services.jobQueueWorker.start(),this.services.logger.debug("Shell boot complete (worker process)");return}let i;if(e?.mode!=="startup-check"){await this.startHttpHost(),await this.services.entityService.reprojectRegisteredGroupings();let n=await this.services.entityService.rewriteRetiredFields();if(n.rewritten>0)this.services.logger.info("Rewrote entities carrying retired fields",{rewritten:n.rewritten});let o=await this.services.entityService.reconcileDeclaredMetadata();if(o.reconciled>0)this.services.logger.info("Re-derived declared entity metadata",{reconciled:o.reconciled});let s=lc();if(this.services.disposables.push(this.services.messageBus.subscribe(Ke.initialSyncCompleted,async(l)=>(s.resolve(ac.safeParse(l.payload).data?.success===!0),{success:!0}))),await this.emitPluginsRegistered())i=s.promise.then(async(l)=>{if(l)return this.settleStartupContent();this.services.logger.warn("Initial sync failed; ready-state defaults are not created")}).catch((l)=>{this.services.logger.error("Failed to settle startup content",l)});else await this.settleStartupContent()}else await this.prepareReadyState();if(await this.services.pluginManager.readyPlugins(),e?.mode==="startup-check"){this.services.logger.debug("Shell boot complete (startup-check mode)");return}if(await this.startRuntimeServices(),i)i.then(()=>this.startIndexReadinessMonitor()).catch((n)=>{this.services.logger.warn("Semantic index readiness monitor did not start",n)});else await this.startIndexReadinessMonitor();this.services.logger.debug("Shell boot complete")}async startHttpHost(){if(!this.services.daemonRegistry.has(K))return;await this.services.daemonRegistry.start(K),this.services.logger.debug("Started the HTTP host before initial sync")}async emitPluginsRegistered(){let e=await this.services.messageBus.collect({type:Ke.pluginsRegistered,payload:{timestamp:new Date().toISOString(),pluginCount:this.services.pluginManager.getAllPluginIds().length},sender:"shell"});return this.services.logger.debug("Emitted plugins registered event"),e.some((t)=>("data"in t)&&sc.safeParse(t.data).data?.initialSyncPending===!0)}async settleStartupContent(){await this.prepareReadyState(),await Ee(this.services.messageBus,cc,{timestamp:new Date().toISOString()},"shell"),this.services.logger.debug("Emitted startup content settled event")}async loadIdentityServices(){await Xt([()=>this.services.identityService.refreshCache(),()=>this.services.profileService.refreshCache(),()=>this.services.canonicalIdentityService.refreshCache()]),this.services.logger.debug("Identity services loaded")}async initializeIdentityServices(){await Xt([()=>this.services.identityService.initialize(),()=>this.services.profileService.initialize(),()=>this.services.canonicalIdentityService.refreshCache()]),this.services.logger.debug("Identity services initialized")}async prepareReadyState(){await this.initializeIdentityServices();let{logger:e}=this.services,t=await oc(this.services.templateRegistry,this.services.entityService);if(t.created.length>0)e.debug(`Materialized ${t.created.length} prompt entities`);if(t.refreshed.length>0)e.info("Refreshed untouched prompts to their current defaults",{targets:t.refreshed});if(t.retitled.length>0)e.info("Corrected generated prompt titles",{targets:t.retitled});if(t.staleOverrides.length>0)e.info("Edited prompts are based on an older default",{targets:t.staleOverrides});if(t.unverifiedOverrides.length>0)e.info("Prompts without provenance differ from their default and are kept; delete one to restore its default",{targets:t.unverifiedOverrides});for(let{target:r,error:i}of t.failed)e.warn(`Could not sync prompt ${r}: ${i}`)}async startRuntimeServices(){for(let e of["shell:recurring-checks","shell:guest-retention"])if(this.services.daemonRegistry.has(e))await this.services.daemonRegistry.start(e);if(await this.services.pluginManager.startPluginDaemons(),this.role.executes)await this.services.jobQueueWorker.start();this.services.jobProgressMonitor.start(),await this.services.batchJobManager.start()}async startIndexReadinessMonitor(){await this.lifecycle.fork(this.runIndexReadinessMonitor())}runIndexReadinessMonitor(){let{entityService:e,logger:t}=this.services;return w.tryPromise({try:()=>e.backfillMissingEmbeddings(),catch:(i)=>i}).pipe(w.tap((i)=>w.sync(()=>{t.debug("Queued missing embedding backfill jobs",i)})),w.catch((i)=>w.sync(()=>{t.warn("Embedding backfill failed",i)}))).pipe(w.andThen(w.tryPromise({try:(i)=>e.awaitIndexReady({intervalMs:lf,signal:i}),catch:(i)=>i}).pipe(w.tap((i)=>w.sync(()=>{if(i.degraded)t.warn("Semantic index ready with degraded embeddings",i);else t.debug("Semantic index ready",i)})),w.catch((i)=>w.sync(()=>{t.warn("Semantic index readiness monitor stopped",i)})))))}}var uf=c.object({}),dc=c.string().regex(/^\d{4}-(0[1-9]|1[0-2])$/,"Expected YYYY-MM"),pc=c.array(c.string().min(1)).min(1).optional().describe("Only these entity types"),pf=c.object({entityTypes:pc,from:dc.optional().describe("First month, YYYY-MM"),to:dc.optional().describe("Last month, YYYY-MM")}),mf=c.object({staleDays:c.number().int().min(1).max(3650).default(90).describe("Days without an update before content counts as stale"),entityTypes:pc});function mc(e){let t=new uc;return t.register(er({type:"overview",description:"Entity counts by type, recent activity, and draft and published totals.",params:uf,handler:async(r,{entityService:i,visibilityScope:n})=>ff(i,n)})),t.register(er({type:"publishing-cadence",description:"Pieces per month, by type: counted in the month they were published, or created when never published.",params:pf,handler:async(r,{entityService:i,visibilityScope:n})=>hf(i,n,r)})),t.register(er({type:"content-health",description:"Drafts and content not updated for a long time.",params:mf,handler:async(r,{entityService:i,visibilityScope:n})=>yf(i,n,e,r)})),t}async function ff(e,t){let r=await e.getEntityCounts(t),i={},n=0;for(let{entityType:f,count:g}of r)i[f]=g,n+=g;let o=await Ei(e,t),s=Date.now(),a=s-604800000,l=s-2592000000,d=0,u=0;for(let f of o){let g=new Date(f.created).getTime();if(g>=a)d++;if(g>=l)u++}let p=gc(o),m=o.filter((f)=>f.metadata.status==="published");return{entityCounts:i,totalEntities:n,recentActivity:{last7days:d,last30days:u},contentHealth:{drafts:p.length,published:m.length}}}function gf(e){let t=e.metadata.publishedAt;return new Date(typeof t==="string"&&t?t:e.created)}function fc(e,t){return t?e.filter((r)=>t.includes(r.entityType)):e}async function hf(e,t,r){let i=fc(await Ei(e,t),r.entityTypes),n=new Map;for(let s of i){let a=gf(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 yf(e,t,r,i){let n=fc(await Ei(e,t),i.entityTypes),o=gc(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 gc(e){return e.filter((t)=>t.metadata.status==="draft")}async function Ei(e,t){let r=e.getEntityTypes(),i=[];for(let n of r){let o=await e.listEntities({entityType:n,options:{limit:1000,filter:{visibilityScope:t}}});i.push(...o)}return i}class rt{parse;idOf;items=new Map;constructor(e,t){this.parse=e,this.idOf=t}register(e){let t=this.parse(e);this.items.set(this.keyFor(t.pluginId,this.idOf(t)),t)}unregister(e,t){if(t!==void 0){this.items.delete(this.keyFor(e,t));return}let r=`${e}:`;for(let i of this.items.keys())if(i.startsWith(r))this.items.delete(i)}list(){return Array.from(this.items.values()).sort((e,t)=>e.priority-t.priority||e.label.localeCompare(t.label))}keyFor(e,t){return`${e}:${t}`}}class Ai extends rt{constructor(){super((e)=>hc.parse(e),(e)=>e.url)}}class ki extends rt{constructor(){super((e)=>yc.parse(e),(e)=>e.id)}}function vc(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 vf=["/health","/images"],bf=new Set([Kt]),Sf=new Set(bc),Rf=new Set(["GET","POST","PUT","DELETE"]);function Sc(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 Rc(e){return bf.has(e)||vf.some((t)=>e===t||e.startsWith(`${t}/`))}function ji(e,t,r=!0){let i;try{i=new URL(e,"http://route.invalid").pathname}catch{i=void 0}if(!e.startsWith("/")||e.includes("//")||e.includes("?")||e.includes("#")||e.includes("%")||e.length>1&&e.endsWith("/")||e.trim()!==e||i!==e||r&&Rc(e))throw Error(`Invalid HTTP route path "${e}" declared by plugin "${t}"`)}function wc(e,t,r){if(!e.has(t))throw Error(`Invalid HTTP route method "${t}" declared by plugin "${r}"`)}function wf(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 If(e,t){ji(t.path,e.pluginId);let r=t.method??"GET";wc(Sf,r,e.pluginId);let i=t.match??"exact";wf(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)=>!Rc(o)&&n(o)}:{},handler:t.handler})}function xf(e,t){ji(t.path,e.pluginId,!1);let r=`/api/${e.pluginId}${t.path}`;if(ji(r,e.pluginId),wc(Rf,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 Pf(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 Cf(e){return Object.freeze(e.map((t)=>Object.freeze({ownerPluginId:t.ownerPluginId,kind:t.kind,method:t.method,fullPath:t.fullPath,match:t.match,sharedHostAdmission:t.sharedHostAdmission})))}class tr{routes;manifest;apiRoutes;webRoutes;static createFresh(){return new tr}constructor(){}finalize(e){if(this.routes!==void 0)throw Error("HTTP route registry has already been finalized");let t=[],r=[],i=[];for(let n of e){for(let o of n.webRoutes)t.push(If(n,o)),r.push(Object.freeze({pluginId:n.pluginId,fullPath:o.path,definition:Object.freeze({...o})}));for(let o of n.apiRoutes){let s=xf(n,o);t.push(s),i.push(Object.freeze({pluginId:n.pluginId,fullPath:s.fullPath,definition:s.definition}))}}return Pf(t),this.routes=Object.freeze(t),this.manifest=Cf(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 Ic(e,t){e.addFinalizer(async()=>{let{entityService:r}=t;if(Tf(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 Tf(e){return"releaseDatabaseLease"in e&&typeof e.releaseDatabaseLease==="function"}function xc(e){return Buffer.isBuffer(e)?e:Buffer.from(e.buffer,e.byteOffset,e.byteLength)}var Ef=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")]),Cc=c.object({query:c.string().describe("Search term"),scope:Ef.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")}),Tc=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.")}),Ec=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)")}),Ac=c.string().min(1).describe("Upload id from the conversation's upload refs"),kc=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(),jc=c.enum(["extract-markdown","preserve"]).describe("extract-markdown imports upload text into a note-like entity; preserve saves raw uploaded bytes via the registered upload-save handler and derives the durable entity type from media type. Use preserve only for explicit file/document preservation, not for saving an assistant summary response."),nt=c.object({kind:c.literal("uploads").describe("Keep several uploaded files from one request: one call listing every attached file, never one call per file; entityType names the note type for extract-markdown files, or another type such as post."),items:c.array(c.strictObject({id:Ac,transform:jc,title:c.string().optional().describe("Only a title the user named for this file."),fields:c.record(c.string(),c.unknown()).optional().describe("Frontmatter the user stated for this file alone, such as the date and address it was first published at: { publishedAt, canonicalUrl }; facts shared by every file go in the top-level fields.")},{error:(e)=>e.code==="unrecognized_keys"&&e.keys.includes("upload")?"Each file is `{ id, transform }`; its `upload` object was removed.":void 0})).min(2).max(20)}).strict(),Di=c.discriminatedUnion("kind",[c.object({kind:c.literal("text").describe("Store exact/direct user-provided content without generation"),content:c.string().min(1).describe("Literal content for a direct save request without a stored user-message source. For pasted text already in this conversation, prefer source.kind user-message with exact boundaries instead of reproducing the body here.")}).strict(),kc,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:Ac,transform:jc},{error:(e)=>e.code==="unrecognized_keys"&&e.keys.includes("upload")?'The upload id goes in `source.id`: `{ kind: "upload", id, transform }`; `source.upload` was removed.':void 0}),nt,c.object({kind:c.literal("prior-response").describe("Save a previous assistant response as durable content, especially an assistant summary or answer about an upload."),messageId:c.string().min(1).optional().describe("Stored assistant message ID; omit for latest savable")}).strict(),c.object({kind:c.literal("entity").describe("Reuse an existing entity's text verbatim, without its frontmatter, as a new entity of another type ('turn my note X into a post'). For new text written from a source, use system_generate prompt-from-source."),entityType:c.string().min(1).describe("Source entity type, such as note"),entityId:c.string().min(1).describe("Source entity ID, slug, or exact title copied from the user's request or a prior tool result")}).strict()]),Af=c.discriminatedUnion("kind",[c.object({kind:c.literal("prompt").describe("A new non-image entity from a broad prompt; this branch has no source field."),entityType:c.string().min(1).describe("Entity type to generate from the prompt. Do not use image here; use standalone-image or cover-image."),title:c.string().optional().describe("Title for the generated entity"),prompt:c.string().min(1).describe("Prompt for creating new generated content, written from the user's request without added voice, tone or engagement directions; the style guide supplies the voice.")}).strict(),c.object({kind:c.literal("prompt-from-source").describe("A new non-image entity grounded in a resolved existing entity, such as a newsletter from a blog post."),entityType:c.string().min(1).describe("Entity type to generate from the source and prompt. Do not use image here; use standalone-image or cover-image."),title:c.string().optional().describe("Title for the generated entity"),source:c.object({entityType:c.string().min(1).describe("Resolved content source entity type, such as post for a newsletter from a blog post. Do not use brain-character or anchor-profile."),entityId:c.string().min(1).describe("Resolved source entity ID from a prior tool result or typed entity ref.")}).strict().describe("The resolved existing entity that grounds this generation."),additionalSourceIds:c.array(c.string().min(1)).optional().describe("More source IDs of the same type."),prompt:c.string().min(1).optional().describe("Direction from the user's request, without added voice, tone or engagement directions; the style guide supplies the voice. Omit if none is given.")}).strict(),c.object({kind:c.literal("standalone-image").describe("An unattached image; never a substitute for a requested cover."),title:c.string().optional().describe("Title for the generated image"),prompt:c.string().min(1).describe("Prompt for creating an unattached image. Not for cover images requested for a generated post/entity.")}).strict(),c.object({kind:c.literal("cover-image").describe("An image attached as coverImageId to an existing entity whose real id is known."),target:c.object({entityType:c.string().min(1).describe("Existing target entity type. Use the actual type of the entity being covered: social-post for LinkedIn/social posts, post for blog posts, etc."),entityId:c.string().min(1).describe("Existing target entity ID from a prior tool result or typed entity ref")}).strict().describe("Existing entity that should receive the generated coverImageId"),title:c.string().optional().describe("Title for the generated image"),prompt:c.string().min(1).describe("Prompt for creating the cover image")}).strict(),c.object({kind:c.literal("attachment").describe("Generate a deterministic durable artifact from an existing entity attachment provider"),source:c.object({entityType:c.string().min(1).describe("Source entity type"),entityId:c.string().min(1).describe("Canonical source entity ID from a prior tool result or typed entity ref")}).strict().describe("The resolved existing entity whose attachment provider renders the artifact."),attachmentType:c.string().min(1).describe('Source artifact type such as "carousel", "printable", or "og-image"'),title:c.string().optional().describe("Title for the generated artifact"),replace:c.boolean().optional().describe("Set true for regenerate, replace, refresh, or update requests so a deterministic artifact is regenerated instead of reused")}).strict()]),rr=c.object({entityType:c.string().describe("Entity type to create. Use wish for explicitly saved or tracked unmet requested capabilities or outcomes."),title:c.string().optional().describe("Title for a new entity. For an upload, give only a title the user named; otherwise leave it out, so the first heading of the file titles it. Leave it out when saving several uploads: each item in source.items takes its own title."),visibility:Pc.optional().describe("Content visibility. Omit for public. Use shared for team/collaborator content readable by Trusted and Admin callers. Use restricted for private/admin-only content."),source:Di.describe("Concrete source selector. Use exactly one source branch. For AI generation or source-derived artifacts, use system_generate instead."),fields:c.record(c.string(),c.unknown()).optional().describe("Frontmatter for facts the user states outside the source text, e.g. a post first published elsewhere: { status: 'published', publishedAt: '2025-03-12', canonicalUrl }; the section a doc goes in, named exactly as the user names it: { section }; the year a project began: { year }. Never copy values from the text or its frontmatter; omit when nothing extra is stated."),replace:c.boolean().optional().describe("Create a new copy intentionally"),confirmed:c.literal(!0).optional().describe("Confirm the creation"),confirmationToken:c.string().optional().describe("Internal confirmation token returned by the confirmation flow")}).strict(),Dc=c.object({operation:Af.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(),kf=c.object({oldText:c.string().min(1).describe("Exact text occurring once in the original stored Markdown. Include enough context to be unique."),newText:c.string().describe("Literal replacement text; empty string deletes oldText.")}).strict(),it="An update operation is exactly one of `fields`, `content`, `edits` or `source`.",Oi=c.strictObject({fields:c.record(c.string(),c.unknown()).optional().describe("Update partial frontmatter or metadata fields. Partial frontmatter fields to update. Use this for status, title, coverImageId, ogImageId, and metadata changes such as approving an agent. To set an existing image as an entity cover, set coverImageId to that image id. To remove or clear a cover image, set coverImageId to null, not an empty string. Do not use fields for anchor-profile; anchor-profile updates require the content operation."),content:c.string().optional().describe("Replace the stored Markdown. Full replacement text you wrote yourself, stored literally. Text without frontmatter replaces the body and keeps the stored frontmatter; text with frontmatter replaces the whole document. When the user supplied the replacement text, use the source operation instead of copying it here. For small changes, use the edits operation instead of regenerating the whole document."),edits:c.array(kf).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:kc.optional().describe("Replace the stored Markdown with user-supplied text. Full replacement taken verbatim from a user message, for large rewrites the user supplied. Select the text with exact boundaries instead of copying it into content. Text without frontmatter replaces the body and keeps the stored frontmatter; text with frontmatter replaces the whole document.")},{error:(e)=>{if(e.code!=="unrecognized_keys")return;if(e.keys.includes("kind"))return ie(e.input)&&e.input.kind==="user-message"?'A user-message source is the source operation: put it under `source`, as in `{ source: { kind: "user-message", ... } }`.':"An update operation has no `kind`: name it by its field, as in `{ edits: [...] }`.";return`Unrecognized key ${e.keys.map((t)=>`"${t}"`).join(", ")}: ${it}`}}).refine((e)=>[e.fields,e.content,e.edits,e.source].filter((t)=>t!==void 0).length===1,{message:it}).describe(it),ir=c.object({entityType:c.string().describe("Entity type"),id:c.string().describe("Entity ID, slug, or title"),operation:Oi.describe("Exactly one update operation"),confirmed:c.literal(!0).optional().describe("Confirm the update"),confirmationToken:c.string().optional().describe("Internal confirmation token returned by the confirmation flow"),contentHash:c.string().optional().describe("Content hash for optimistic concurrency")}).strict(),Oc=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")}),jP=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")}),zc=c.object({batchId:c.string().optional().describe("Specific batch ID to check"),jobTypes:c.array(c.string()).optional().describe("Filter by job types")}),jf=c.object({entityType:c.string().optional(),entityId:c.string().optional(),attachmentType:c.string().optional()}),Df=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:jf.optional()}),DP=c.object({entityId:c.string().optional(),status:c.enum(["created","generating"]),jobId:c.string().optional(),attachment:Df.optional()}),OP=c.object({status:c.literal("extracting"),jobId:c.string(),entityType:c.string(),source:c.string().optional(),mode:c.enum(["derive","rebuild"]).optional()});function Uc(e,t,r){return r==="create"?e.getCreateFieldsSchema(t):e.getEditableFieldsSchema(t)}function Bc(e){if(e instanceof c.ZodOptional||e instanceof c.ZodNullable||e instanceof c.ZodDefault)return Bc(e.unwrap());return e instanceof c.ZodType?e:void 0}function Mc(e){try{let{$schema:t,...r}=c.toJSONSchema(e,{target:"draft-7",io:"input"});return r}catch{return}}function Of(e){return Lc({type:"object",properties:{value:e},required:["value"]})!==void 0}function $c(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=Uc(e,d,t.on);for(let[p,m]of Object.entries(u?.shape??{})){if(t.omit?.includes(p))continue;let f=Bc(m),g=f&&Mc(f);if(!f||!g||!Of(g))continue;let h=r.get(p)??new Map;h.set(JSON.stringify(g),f),r.set(p,h),i.set(p,[...i.get(p)??[],d])}}let o=new Map;for(let[d,u]of r){let[p,...m]=[...u.values()];if(!p)continue;let f=m.length>0?c.union([p,...m]):p,g=JSON.stringify(Mc(f)),h=o.get(g)??{value:f,names:[]};h.names.push(d),o.set(g,h)}let s=[...o.values()].map(({value:d,names:u})=>{let[p,...m]=u,f=u.map((g)=>{let h=i.get(g)??[];return`${g} (${h.length===n.length?"every type":h.join(", ")})`}).join("; ");return c.strictObject({name:(m.length>0&&p!==void 0?c.enum([p,...m]):c.literal(p??"")).describe(`The field, set only on the entity types named: ${f}.`),value:t.on==="update"?d.nullable():d})}),[a,...l]=s;return c.array(a?l.length>0?c.union([a,...l]):a:c.never())}function zf(e){return Object.fromEntries((Array.isArray(e)?e:[]).flatMap((t)=>V(t)&&typeof t.name==="string"?[[t.name,t.value]]:[]))}function nr(e,t,r,i){if(!r)return;let{allow:n}=i,o=new Set(Object.keys(Uc(e,t,i.on)?.shape??{})),s=Object.keys(r).filter((d)=>!o.has(d)&&!n.includes(d));if(s.length===0)return;let a=s.map((d)=>`"${d}"`).join(", "),l=[...o].join(", ")||"none";return`A ${t} has no ${s.length>1?"fields":"field"} ${a} a caller can set; its fields are ${l}.`}function Mi(e){return"fields"in e&&e.fields!==void 0?{...e,fields:zf(e.fields)}:e}function _c(e,t){return{prepare:()=>e.ensureGroupingsCurrent(),inputSchema:()=>{let r=$c(e,{on:"create",omit:["visibility"],...t&&{neverWrites:t}}),i=nt.shape.items.element,n=nt.extend({items:c.array(i.extend({fields:r.optional().describe("Field changes the user stated for this file alone, one { name, value } per field, such as the date and address it was first published at: [{ name: 'publishedAt', value }, { name: 'canonicalUrl', value }]; facts shared by every file go in the top-level fields.")})).min(2).max(20)}),[o,...s]=Di.options.map((a)=>a===nt?n:a);if(!o)throw Error("system_create has no source branches");return{...rr.shape,source:c.discriminatedUnion("kind",[o,...s]).describe("Concrete source selector. Use exactly one source branch. For AI generation or source-derived artifacts, use system_generate instead."),fields:r.optional().describe("Field changes for facts the user states outside the source text, one { name, value } per field, e.g. a post first published elsewhere: [{ name: 'status', value: 'published' }, { name: 'publishedAt', value: '2025-03-12' }, { name: 'canonicalUrl', value }]; the section a doc goes in, named exactly as the user names it: [{ name: 'section', value }]; the year a project began: [{ name: 'year', value }]. Never copy values from the text or its frontmatter; omit when nothing extra is stated, and never fill in one the user did not state, such as a default section: leave it out, and the tool asks for it.")}},toToolInput:(r)=>{let i=r.source;return Mi({...r,...V(i)&&Array.isArray(i.items)&&{source:{...i,items:i.items.map((n)=>V(n)?Mi(n):n)}}})}}}function zi(e){let t=e.unwrap();return e.description?t.describe(e.description):t}function Fc(e,t){let{content:r,edits:i,source:n}=Oi.shape;return{prepare:()=>e.ensureGroupingsCurrent(),inputSchema:()=>({...ir.shape,operation:c.union([c.strictObject({fields:$c(e,{on:"update",...t&&{neverWrites:t}}).describe("Change frontmatter or metadata fields, one { name, value } per field changed. Use this for status, title, coverImageId, ogImageId, and metadata changes such as approving an agent. To set an existing image as an entity cover, change coverImageId to that image id. To remove a field, such as a cover image, give it the value null, not an empty string. Do not use fields for anchor-profile; anchor-profile updates require the content operation.")}),c.strictObject({content:zi(r)}),c.strictObject({edits:zi(i)}),c.strictObject({source:zi(n)})]).describe("Exactly one update operation")}),toToolInput:(o)=>{let s=o.operation;return V(s)?{...o,operation:Mi(s)}:o}}}function B(e,t,r,i){try{e.permissionService.assertEntityActionAllowed(t,r,i.userPermissionLevel);return}catch(n){if(n instanceof Error)return{success:!1,error:n.message};throw n}}function De(e){return(t,r)=>e.getEntityActionRequiredLevel(t,r)==="never"}var Mf="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:`${Mf}_${e}`,description:t,inputSchema:r.shape,handler:async(a,l)=>{let d=r.safeParse(a);if(!d.success)return{success:!1,error:`Invalid input: ${d.error.issues.map((u)=>`${u.path.join(".")}: ${u.message}`).join(", ")}`};try{return await i(d.data,l)}catch(u){return{success:!1,error:P(u)}}},visibility:o,...s?{sideEffects:s}:{}}}function sr(e){return{interfaceType:e.interfaceType,actor:e.actor,userPermissionLevel:e.userPermissionLevel??"public",...e.channelId&&{channelId:e.channelId},...e.channelName&&{channelName:e.channelName}}}async function Nc(e,t,r,i){let n=await t(r,sr(i));if(n.kind==="handled")return{kind:"handled",result:n.result};let o=n.input;if(o.visibility!==r.visibility)return{kind:"error",result:{success:!1,error:"Create interceptor changed or dropped the requested entity visibility."}};let s=B(e,o.entityType,"create",i);if(s)return{kind:"error",result:s};return{kind:"continue",createInput:o}}function Oe(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 ze(e){let t={...e.conversationId?{conversationId:e.conversationId}:{},...e.channelId?{channelId:e.channelId}:{},...e.runId?{runId:e.runId}:{},...e.toolCallId?{toolCallId:e.toolCallId}:{}};return Object.keys(t).length>0?t:void 0}function Li(e,t){if(t.getEntityTypeConfig(e.entityType).binaryStorage)return{...e,content:`[binary ${e.entityType} data \u2014 use metadata for ${e.entityType} info]`};return e}function ar(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var Lf={base:"note"};function Zc(e){return Lf[e]??e.replaceAll("-"," ")}function Me(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 Hc(e){return!!e&&Object.keys(e.shape).length>0}async function Wc(e,t,r){if(!r)return!1;let i=await e.conversationService.getMessages(r,{limit:100});for(let n of i){let s=or(n.metadata)?.attachments;if(!Array.isArray(s))continue;for(let a of s){if(!ie(a))continue;let l=a.source;if(!ie(l))continue;if(l.kind===t.kind&&l.id===t.id)return!0}}return!1}async function cr(e,t,r){if(t.replace||!t.candidateId)return{kind:"ok",value:void 0};let i=await e.entityService.getEntity({entityType:t.entityType,id:t.candidateId,visibilityScope:A(r.userPermissionLevel)});if(!i)return{kind:"ok",value:void 0};if(i.metadata.status==="failed"&&r.userPermissionLevel==="admin"&&!B(e,t.entityType,"delete",r))return{kind:"ok",value:{entityType:i.entityType,id:i.id}};return T(`A ${t.entityType} already exists for "${t.candidateId}". To change it, use system_update on that ${t.entityType} in this turn, without asking first; pass replace:true to ${t.copyHint}.`)}function qc(e){return`Replaces: failed ${e.entityType} "${e.id}"`}async function Jc(e,t){if(!t)return;try{await e.entityService.deleteEntity(t);return}catch(r){return{success:!1,error:P(r,"Failed to replace the failed entity")}}}function lr(e,t,r){let i=Oe(e,t);if(i)return X(i);let n=B(e,t,"create",r);if(n)return X(n);return{kind:"ok",value:{interceptor:e.entityRegistry.getCreateInterceptor(t)}}}async function dr(e){let{gate:t,input:r,replacesFailed:i}=e;if(r.confirmed){let d=t.validateConfirmed(r.confirmationToken,r);if(d)return d;return e.run()}let{toolName:n,summary:o,completionSummary:s,preview:a,args:l}=e.confirmation();return{needsConfirmation:!0,toolName:n,summary:o,...s!==void 0&&{completionSummary:s},preview:i?`${a}
78
78
  ${qc(i)}`:a,args:t.buildArgs((d)=>({...l,confirmed:!0,confirmationToken:d}))}}async function ot(e,t,r){let i=await Jc(e,r.replacesFailed);if(i)return i;if(!r.interceptor)return r.persist(r.createInput);let n=await Nc(e,r.interceptor,r.createInput,t);if(n.kind!=="continue")return n.result;return r.persist(n.createInput)}async function ur(e,t,r,{confirmed:i}){let n=r.conversationId??r.channelId;if(!n)return{success:!1,error:"Conversation message is not accessible in this conversation or does not exist."};let o=await e.conversationService.getMessages(n,{limit:100}),s=t.kind==="user-message",a=s?o.filter((y)=>{if(y.role!=="user")return!1;let S=r.userPermissionLevel??"public";if(S==="admin")return!0;let b=or(y.metadata)?.userPermissionLevel;return(b==="public"||b==="trusted"||b==="admin")&&e.permissionService.hasPermission(S,b)}):o.filter(Qc),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=_f($f(t,l.content),l.content),u=(y,S,b,R)=>{if(!S)return{offset:b};let I=`${y} ${JSON.stringify(S)}`;if(d.boundaryMode==="lines"&&/[\r\n]/.test(S))return{problem:`${I} contains a newline; in lines mode give the marker line's text only`};let E=Uf(l.content,S,d.boundaryMode==="lines"?"lines":"literal",R),[z]=E;if(E.length===1&&z!==void 0)return{offset:z};return{problem:E.length===0?`${I} does not occur in the message`:`${I} occurs ${E.length} times in the message`}},p=u("startAfter",d.startAfter,0,!0),m=d.boundaryMode==="frontmatter"&&"offset"in p?Nf(l.content,p.offset):p,f=u("endBefore",d.endBefore,l.content.length,!1),g=[m,f].flatMap((y)=>("problem"in y)?[y.problem]:[]);if(g.length===0&&"offset"in m&&"offset"in f&&m.offset>=f.offset)g.push("startAfter must come before endBefore with content between them");if(!("offset"in m)||!("offset"in f)||g.length>0)return{success:!1,error:`User-message boundary ${g.join("; ")}; each boundary must occur exactly once. ${Ff(l.content)}`};let h=l.content.slice(m.offset,f.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 pr(e,t){let{startAfter:r,endBefore:i,...n}=t.source??e;return{...n,...r?{startAfter:r}:{},...i?{endBefore:i}:{},messageId:t.messageId,contentHash:G(t.content)}}function Uf(e,t,r,i){if(r==="lines"){let o=Ui(e,t,i);return o.length>0||!t.trim()?o:Ui(e,t,i,Bf)}let n=Kc(e,t,i);return n.length>0?n:Zf(e,t,i)}function Bf(e){return e.trim().replace(/\s+/g," ")}function $f(e,t){let r=(a)=>a?.trim()==="---";if(!r(e.startAfter)&&!r(e.endBefore))return e;if((t.match(/^---\r?$/gm)?.length??0)!==2||Bi(t,0).length!==1)return e;let{startAfter:n,endBefore:o,...s}=e;return{...s,boundaryMode:"frontmatter",...r(n)?{}:{startAfter:n},...r(o)?{}:{endBefore:o}}}function _f(e,t){let{startAfter:r,endBefore:i}=e;if(e.boundaryMode!==void 0||!r||!i)return e;let n=(o)=>!/[\r\n]/.test(o)&&Ui(t,o,!0).length===1;return n(r)&&n(i)?{...e,boundaryMode:"lines"}:e}function Ff(e){return Bi(e,0).length===1?'--- fences frontmatter, which is part of the content: retry with boundaryMode "frontmatter" and no startAfter or endBefore.':"To select everything after an instruction, use boundaryMode literal with startAfter set to the instruction's exact text and omit endBefore."}function Nf(e,t){let r=Bi(e,t),[i]=r;if(r.length===1&&i!==void 0)return{offset:i};return{problem:r.length===0?"boundaryMode frontmatter finds no --- frontmatter block":`boundaryMode frontmatter finds ${r.length} --- frontmatter blocks`}}function Bi(e,t){return Array.from(e.slice(t).matchAll(/^---\r?\n["']?[A-Za-z_][\w-]*["']?[ \t]*:.*\r?\n(?:.*\r?\n)*?---\r?$/gm),(r)=>t+r.index)}function Ui(e,t,r,i=(n)=>n){let n=i(t);return e.split(/(?<=\n)/).reduce((o,s)=>({offset:o.offset+s.length,matches:i(s.replace(/\r?\n$/,""))===n?[...o.matches,o.offset+(r?s.length:0)]:o.matches}),{offset:0,matches:[]}).matches}function Zf(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(Gc).join("\\s+")+n(/\s$/.test(t)),"g");return Array.from(e.matchAll(o),(s)=>s.index+(r?s[0].length:0))}function Kc(e,t,r,i=0){let n=e.indexOf(t,i);if(n<0)return[];return[n+(r?t.length:0),...Kc(e,t,r,n+1)]}var Hf=/^[ \t]*---[ \t]*$/gm;function Vc(e){return e.replace(/\s+/g," ").trim()}function Wf(e){return e.kind==="user-message"?e.messageId:void 0}class $i{pins=new Map;now;constructor(e=Date.now){this.now=e}pin(e,t){this.pins.set(e,{...t,expiresAt:this.now()+1800000})}clear(e){this.pins.delete(e)}live(e){let t=this.pins.get(e);if(t&&t.expiresAt<this.now()){this.pins.delete(e);return}return t}resolveUnresolvable(e,t){let r=this.live(e);if(!r||t.kind!=="user-message"||t.messageId)return;return{kind:"pinned",source:r.source,content:r.content}}resolve(e,t){let r=this.live(e);if(!r)return{kind:"as-given"};let i=Wf(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&&Vc(t.content.replace(Hf,""))===Vc(r.content))return{kind:"as-given"};if(t.source.kind==="text")return n;if(t.source.kind==="user-message"&&t.resolvedMessageId!==i){if(t.content.length*2<r.content.length)return n;this.pins.delete(e)}return{kind:"as-given"}}}function _i(e,t){return e?`${e}\x00${t}`:void 0}function Yc(e){if(e.kind!=="user-message")return e;let{contentHash:t,...r}=e;return r}function Fi(e){return`${e.entityType} "${e.title}"`}function qf(e){return Object.entries(e).map(([t,r])=>`${t}: ${typeof r==="string"?r:JSON.stringify(r)}`).join(", ")}function Xc(e){return"error"in e?e.error:"the save was not completed"}function Jf(e){let t=new Map;for(let r of e){let i=`${r.entityType}:${ee(r.title)}`,n=t.get(i);if(n)return`${n.filename} and ${r.filename} would both be saved as ${Fi(r)}. Give them different titles in source.items.`;t.set(i,r)}return}function Gf(e,t){return{summary:`Save ${e.length} uploaded files?`,completionSummary:`Saved ${e.length} uploaded files: ${e.map(Fi).join(", ")}.`,preview:[...e.map((r,i)=>[`${i+1}. ${r.filename} \u2192 ${Fi(r)}`,...r.fields?[` ${qf(r.fields)}`]:[],...r.replacesFailed?[` Replaces failed ${r.replacesFailed}`]:[]].join(`
79
79
  `)),`Visibility: ${t??"public"}`].join(`
80
80
  `)}}async function Qf(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}: ${Xc(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 el(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}): ${Xc(d.result)}`};i.push(d.value)}let n=Jf(i);if(n)return{success:!1,error:n};if(t.confirmed){let a=r.validateConfirmed(t.confirmationToken,t);if(a)return a;return Qf(i)}let o=Gf(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 Kf(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 Vf(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
82
  `)}}function Yf(e){let t=e.title?` "${e.title}"`:"";return`Saved ${e.entityType}${t}.`}function Xf(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 eg(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=Le(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 tg(e,{source:t,retry:r},i){if(r.kind==="pinned")return r.source;if(e.kind==="user-message"){if(!t.resolvedMessageId||i===void 0)throw Error("User-message source was not resolved before confirmation");return pr(e,{messageId:t.resolvedMessageId,content:i,...t.resolvedUserSource&&{source:t.resolvedUserSource}})}if(e.kind==="prior-response"){let n=e.messageId??t.resolvedMessageId;return{kind:"prior-response",...n?{messageId:n}:{}}}if(e.kind==="entity"&&t.entitySource)return{kind:"entity",...t.entitySource.ref};return e}async function rg(e,t){let r=sr(t);return e.handler({upload:e.upload,...e.title&&{title:e.title},...e.visibility!==void 0?{visibility:e.visibility}:{}},r)}function ig(e,t,r){let i=Ue(t),n=i.content.match(/^#\s+(.+)$/m)?.[1]?.trim(),o=e.fields?.title!==void 0||i.frontmatter.title!==void 0||n!==void 0&&n===e.title?.trim(),s=r&&!o?e.title:void 0,a={...s!==void 0&&{title:s},...e.fields};return Object.keys(a).length>0?mr(a,t):t}async function ng(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&&Hc(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:ig(t,t.content,"title"in(s?.shape??{})),...t.visibility!==void 0?{visibility:t.visibility}:{}},options:l}):await i.createEntity({entity:{id:o,entityType:t.entityType,content:t.content??"",metadata:{title:t.title??o},...t.visibility!==void 0?{visibility:t.visibility}:{},created:new Date().toISOString(),updated:new Date().toISOString()},options:l})).entityId,status:"created"}}}catch(l){return{success:!1,error:P(l,"Failed to create entity")}}}async function og(e,t,r){let{content:i,url:n,from:o,uploadRef:s,conversationMessageRef:a,entityRef:l,transform:d}=Xf(t.source),u=l?await eg(e,l,r):void 0;if(u?.kind==="error")return u;let p=a?await ur(e,a,r,{confirmed:t.confirmed===!0}):void 0;if(p&&!p.success)return X(p);let m=p?.success===!0?p.content:u?.value.content??i;if(d==="extract-markdown"&&!s)return T('Transform "extract-markdown" requires an upload ref.');if(!m&&!n&&!o)return T('Provide `source` with kind "user-message", "text", "url", "prior-response", "upload", or "entity". Use system_generate for generated content or artifacts.');return{kind:"ok",value:{content:m,url:n,from:o,uploadRef:s,transform:d,resolvedMessageId:p?.success===!0?p.messageId:void 0,resolvedUserSource:p?.success===!0?p.source:void 0,entitySource:u?.value}}}async function sg(e,t){if(!Ni(t.mediaType))return;let{content:r}=await e.runtimeUploads.scoped(Te).read(t.id);return xc(r).toString("utf8")}async function ag(e,t,r){if(!await Wc(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(Te).readRecord(t.uploadRef.id),o=t.transform==="extract-markdown"?await sg(e,{id:t.uploadRef.id,mediaType:n.mediaType}):void 0}catch{return T("Upload ref not found")}let s=rl({filename:n.filename,markdown:o});if(t.transform!=="preserve")return{kind:"ok",value:{entityType:t.entityType,title:s,filename:n.filename,mediaType:n.mediaType,markdown:o,uploadPreserve:void 0}};let a=e.entityRegistry.getUploadSaveHandler(n.mediaType);if(!a){let l=Ni(n.mediaType)?' Keep a text upload as a note: entityType "note" with transform "extract-markdown".':"";return T(`No installed plugin can save uploads with media type "${n.mediaType}".${l}`)}return{kind:"ok",value:{entityType:a.entityType,title:s,filename:n.filename,mediaType:n.mediaType,markdown:o,uploadPreserve:{upload:t.uploadRef,filename:n.filename,mediaType:n.mediaType,handler:a.handler}}}}function cg(e,t,r){let i=t?gr(t):void 0;if(e!==void 0&&i!==void 0&&e!==i)return T(`Conflicting entity visibility: system_create requested "${e}" but the source frontmatter declares "${i}".`);let n=e??i,o=n??"public";if(!fr(r.userPermissionLevel,o))return T(`Cannot create entity with visibility "${o}" \u2014 caller permission "${r.userPermissionLevel??"public"}" is not allowed to write at that level.`);return{kind:"ok",value:n}}function lg(e,t,r){return cr(e,{entityType:t.entityType,candidateId:t.title?ee(t.title):void 0,replace:t.replace===!0,copyHint:"create a new copy intentionally"},r)}function dg(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 ug(e,t,r){let i=e.entityRegistry.getCreateCheck(t.entityType);if(!i)return{kind:"ready"};try{return await i(t,sr(r))}catch(n){return{kind:"error",error:P(n,`Could not check the ${t.entityType}`)}}}function pg(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(Yc(t))}.`,e.answerWith].join(" ")}function mg(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 il='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 fg(e,t,r,i,n){let o=await og(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 gg(e,t,{source:r,retry:i},n){let o=r.uploadRef?await ag(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=dg(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 hg(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=cg(e.visibility??d,n,l);if(u.kind==="error")return u;if(e.fields&&"visibility"in e.fields)return T("Set visibility with the typed `visibility` input, not in `fields`.");let p=e.fields&&Object.keys(e.fields).length>0?e.fields:void 0,m=ar(e.title),f=(a&&tl(m,a.filename)?void 0:m)??r?.title??a?.title,g=e.replace===!0;return{kind:"ok",value:{entityType:i,...f&&{title:f},...u.value!==void 0?{visibility:u.value}:{},...n&&{content:n},...t&&{url:t},...o&&{from:o},...s&&{transform:s},...p&&{fields:p},...g&&{replace:g}}}}async function yg(e,t,r,i){let n=await ug(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(pg(n,i.source,i.several))}return{kind:"ok",value:mg(t,n)}}async function nl(e,t,r,i,n){if(!(t.source.kind==="upload"&&t.source.transform==="preserve")){let I=Oe(e,t.entityType);if(I)return X(I)}let s=_i(r.conversationId??r.channelId,t.entityType),a=await fg(e,t,r,i,s);if(a.kind==="error")return a;let{source:l}=a.value,d=await gg(e,t,a.value,r);if(d.kind==="error")return d;let{content:u,upload:p}=d.value,m=p?.uploadPreserve,f=hg(t,l,d.value,r);if(f.kind==="error")return f;let g=f.value,h=lr(e,g.entityType,r);if(h.kind==="error")return h;let{interceptor:v}=h.value;if(!g.content&&!v&&!m)return T(il);let y=tg(t.source,a.value,u),S=t.confirmed||m?{kind:"ok",value:g}:await yg(e,g,r,{source:y,several:n,pinnable:l.uploadRef?void 0:u,pending:i,pendingKey:s});if(S.kind==="error")return S;let b=S.value,R=await lg(e,b,r);if(R.kind==="error")return R;return{kind:"ok",value:{createInput:b,confirmationSource:y,interceptor:v,eventContext:ze(r),...p&&{uploadFilename:p.filename},...l.uploadRef&&{uploadId:l.uploadRef.id},...R.value&&{replacesFailed:R.value},...m&&{uploadPreserve:m}}}}async function ol(e,t,r,i){let n=await vg(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 vg(e,t,r,i){let{createInput:n,eventContext:o,uploadPreserve:s,replacesFailed:a}=t;if(s)return ot(e,r,{createInput:n,interceptor:void 0,replacesFailed:a,persist:()=>rg({upload:s.upload,...n.title&&{title:n.title},...n.visibility!==void 0?{visibility:n.visibility}:{},handler:s.handler},r)});let l=await ot(e,r,{createInput:n,interceptor:t.interceptor,replacesFailed:a,persist:async(u)=>u.content?ng(e,u,o):{success:!1,error:il}}),d=_i(r.conversationId??r.channelId,n.entityType);if(d&&"success"in l&&l.success)i.clear(d);return l}async function bg(e,t,r,i,n){let o={...t.fields,...r.fields},s=await nl(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:()=>ol(e,a,i,n)}}}function Sg(e){let{createInput:t,uploadPreserve:r}=e,{summary:i,preview:n}=r?Kf({...t.title&&{title:t.title},filename:r.filename,mediaType:r.mediaType,entityType:t.entityType,visibility:t.visibility}):Vf(t);return{toolName:"system_create",summary:i,completionSummary:Yf(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 sl(e){let t=Y({label:"create",requestNoun:"creation"}),r=new $i;return{...W("create","Create a new entity from existing material. Never create a duplicate to save edits: use system_update for entities already created or imported in this conversation, even while an upload import is generating. Requires confirmation; call this tool without confirmed to request that confirmation instead of asking for plain-text approval. Use visibility shared for team/collaborator content such as a team note, restricted for private/admin-only content, and omit it for public content; keep visibility separate from exact source text. Public callers may write only public content, Trusted callers public or shared, and Admin callers all three. If the user only says 'not public' without saying team/shared or private/admin-only, ask which scope they mean. Entity-specific instructions may direct proactive capture of the user's request itself; in that case the request is concrete text and no separate save verb is required. Use system_generate for AI generation, generated images, cover images, and source-derived artifacts such as carousel/printable PDFs or OG images. If the user includes content in the same direct save request, use source.kind user-message, omitting messageId for the latest user message; that content is sufficient even when it is a short sentence or fragment after a colon or embedded in the request phrase (for example, 'Save this memo about the launch timeline'), so never ask the user to paste it again. For standalone delimiter lines, use boundaryMode lines with startAfter/endBefore set to the exact marker line text WITHOUT newline characters; the server preserves all intervening bytes, including final newlines. To save a pasted document that opens with --- frontmatter, use boundaryMode frontmatter without startAfter or endBefore: the server selects it from its opening fence, and the fences are content, never boundaries. For inline content, use literal startAfter/endBefore boundaries to exclude the save instruction. Omit boundaries only when saving the whole message. Never retype, shorten, correct, or include delimiter text in pasted source material, and never ask for a smaller copy just because it is long. For 'Save this as a note: ...', startAfter can be the exact 'Save this as a note: ' prefix. If boundaries are ambiguous, ask for clarification. If the user says save it/that/this after your immediately preceding upload summary/answer, use entityType note with source.kind prior-response unless they explicitly ask to save the uploaded file/document itself; do this even when the prior answer says there was limited readable content, and do not ask whether they meant the summary or the file after you just summarized/answered about the upload. A bare upload receipt like 'I got filename. What would you like me to do?' is not a summary/answer: for a following 'save it', preserve the latest uploaded file itself with upload transform preserve (image uploads as entityType image). Only use source.kind upload when the runtime supplies an actual upload reference/attachment, and then use it even though the file text also appears in the message; only a pasted uploaded-file transcript (for example, User uploaded a file \"name.md\": ...) with no listed upload ref is saved with source.kind user-message boundaries.",rr,async(n,o)=>{await e.entityRegistry.ensureGroupingsCurrent(n.entityType);let s=[n.fields,...n.source.kind==="uploads"?n.source.items.map((d)=>d.fields):[]].map((d)=>nr(e.entityRegistry,n.entityType,d,{on:"create",allow:["visibility"]})).find((d)=>d!==void 0);if(s)return{success:!1,error:s};if(n.source.kind==="uploads")return el({input:{...n,source:n.source},gate:t,prepare:(d)=>bg(e,n,d,o,r)});let a=await nl(e,n,o,r);if(a.kind==="error")return a.result;let l=a.value;return dr({gate:t,input:n,replacesFailed:l.replacesFailed,confirmation:()=>Sg(l),run:()=>ol(e,l,o,r)})},{visibility:"trusted",sideEffects:"writes"}),modelInput:_c(e.entityRegistry,De(e.permissionService))}}function Rg(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 Rg(e.entries.map(({label:t})=>t))}function wg(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 Ig(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:Me(a.entity)}]:[]);return{kind:"ok",value:s.filter(({entityId:a},l)=>s.findIndex((d)=>d.entityId===a)===l)}}function cl(e,t){return e.entityRegistry.getEntityTypeConfig(t).consumesSources??[]}function xg(e,t,r){if(t.kind!=="prompt"&&t.kind!=="prompt-from-source")return;let i=cl(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 ll(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 Pg(e,t,r,i){let n=await ll(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 Cg(e,t,r,i,n,o){let{entityService:s,jobs:a}=e,l=Hi(ee(dl(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=al(e.entityRegistry,{entityType:t.entityType,id:l,title:d});if(!u)return{success:!1,error:`Entity type '${t.entityType}' does not support queued generation. Provide an exact source to system_create instead.`};let p;try{p=(await s.createEntity({entity:u,options:{deduplicateId:!0,...n?{eventContext:n}:{}}})).entityId}catch(g){return{success:!1,error:P(g,"Failed to persist generation stub")}}let m={entityId:p,prompt:r,...t.title&&{title:t.title},...t.sourceEntityType&&{sourceEntityType:t.sourceEntityType},...t.sourceEntityId&&{sourceEntityId:t.sourceEntityId},...t.sourceEntityIds&&{sourceEntityIds:t.sourceEntityIds},...t.targetEntityType&&{targetEntityType:t.targetEntityType},...t.targetEntityId&&{targetEntityId:t.targetEntityId}},f=e.entityRegistry.getGenerationEnqueuer(t.entityType);try{let g=f?await f(m,o):await a.enqueue({type:`${t.entityType}:generation`,data:m,toolContext:o});return{success:!0,data:{entityId:p,status:"generating",jobId:g}}}catch(g){return await s.deleteEntity({entityType:t.entityType,id:p}).catch((h)=>{e.logger.warn("Failed to remove unqueued generation stub",{entityType:t.entityType,entityId:p,error:h})}),{success:!1,error:P(g,"Failed to queue generation job")}}}function dl(e,t,r){return e.title??t??r}async function Tg(e,t,r){let i=ar(t.title);if(t.kind==="prompt"||t.kind==="prompt-from-source"){if(e.entityRegistry.getEntityTypeConfig(t.entityType).binaryStorage)return T(`Prompt generation does not support binary entity type '${t.entityType}'. Use operation.kind 'attachment' for source-derived artifacts, or 'standalone-image' or 'cover-image' for generated images.`,"unsupported-generation");let l=t.kind==="prompt-from-source"?await Ig(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:cl(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 ll(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 Pg(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 Eg(e,t,r){let i=t.operation,n=A(r.userPermissionLevel),o=xg(e,i,r);if(o)return X(o);let s=await Tg(e,i,n);if(s.kind==="error")return s;let{createInput:a,sourceAttachment:l,writtenFrom:d}=s.value,p="prompt"in i&&i.prompt!==void 0&&!d?.usedUp?void 0:d?.entries[0]?.entityId,m=lr(e,a.entityType,r);if(m.kind==="error")return m;let{interceptor:f}=m.value;if(!a.prompt&&!a.from)return T("Provide a generation source.");if(a.from&&!f)return T(`Entity type '${a.entityType}' does not support attachment-based generation. Use operation.kind prompt-from-source for AI-generated content based on referenced source material, or choose an entity type with an attachment provider.`,"unsupported-generation");let g=i.kind==="prompt"||i.kind==="prompt-from-source",h=f&&!g?void 0:await cr(e,{entityType:a.entityType,candidateId:a.prompt?Hi(ee(dl(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:Ag(i,a,l),interceptor:f,eventContext:ze(r),...h?.value&&{replacesFailed:h.value},writtenFrom:d,sourceName:p}}}function Ag(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 ul(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.",Dc,async(r,i)=>{let n=await Eg(e,r,i);if(n.kind==="error")return n.result;let{createInput:o,operation:s,interceptor:a,eventContext:l,replacesFailed:d,writtenFrom:u,sourceName:p}=n.value;return dr({gate:t,input:r,replacesFailed:d,confirmation:()=>({toolName:"system_generate",...wg(o,u,"prompt"in s?s.prompt:void 0),args:{operation:s}}),run:()=>ot(e,i,{createInput:o,interceptor:a,replacesFailed:d,persist:async(m)=>{if(!m.prompt)return{success:!1,error:"Attachment generation is supported only for entity types that explicitly handle source-derived artifacts."};return Cg(e,m,m.prompt,p,l,i)}})})},{visibility:"trusted",sideEffects:"writes"})}function pl(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.",Oc,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=Oe(e,o.entityType);if(l)return l;if(r.getAdapter(o.entityType).isSingleton===!0)return{success:!1,error:`${o.entityType} is a singleton entity and cannot be deleted through system tools. Update it instead.`};let d=A(s.userPermissionLevel),u=await _(t,{entityType:o.entityType,identifier:o.id},{visibilityScope:d,logger:i});if(!u.ok)return{success:!1,error:u.error};let{entity:p}=u;if(o.confirmed){let g=n.validateConfirmed(o.confirmationToken,o);if(g)return g;try{await t.deleteEntity({entityType:o.entityType,id:p.id})}catch(h){return{success:!1,error:P(h,"Failed to delete entity")}}return{success:!0,data:{deleted:p.id}}}let m=Me(p),f=n.buildArgs((g)=>({...o,id:p.id,confirmed:!0,confirmationToken:g}));return{needsConfirmation:!0,toolName:"system_delete",summary:`Delete "${m}"?`,preview:p.content.slice(0,200),args:f}},{visibility:"admin",sideEffects:"writes"})}function ml(e,t){let r=t.map(({oldText:o,newText:s},a)=>{let l=e.indexOf(o);if(!o||l<0)throw Error(`Edit ${a+1}: oldText was not found. Fetch the entity again and provide exact text.`);if(e.indexOf(o,l+1)!==-1)throw Error(`Edit ${a+1}: oldText is ambiguous. Include more surrounding text to match exactly once.`);return{start:l,end:l+o.length,newText:s}}).sort((o,s)=>o.start-s.start),i=0,n=[];for(let o of r){if(o.start<i)throw Error("Edits overlap in the original content. Provide non-overlapping replacements.");n.push(e.slice(i,o.start),o.newText),i=o.end}return n.push(e.slice(i)),n.join("")}import{isDeepStrictEqual as an}from"util";class Be{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}],f=this.extractCommon(m[0],t,e,0,r);if(m[0].oldPos+1>=a&&f+1>=s)return o(this.buildValues(m[0].lastComponent,t,e));let g=-1/0,h=1/0,v=()=>{for(let y=Math.max(g,-l);y<=Math.min(h,l);y+=2){let S,b=m[y-1],R=m[y+1];if(b)m[y-1]=void 0;let I=!1;if(R){let z=R.oldPos-y;I=R&&0<=z&&z<s}let E=b&&b.oldPos+1<a;if(!I&&!E){m[y]=void 0;continue}if(!E||I&&b.oldPos<R.oldPos)S=this.addToPath(R,!0,!1,0,r);else S=this.addToPath(b,!1,!0,1,r);if(f=this.extractCommon(S,t,e,y,r),S.oldPos+1>=a&&f+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(f+1>=s)g=Math.max(g,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 f=r[l+m];return f.length>p.length?f:p}),d.value=this.join(u)}else d.value=this.join(t.slice(a,a+d.count));if(a+=d.count,!d.added)l+=d.count}else d.value=this.join(r.slice(l,l+d.count)),l+=d.count}return i}}class fl extends Be{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}}var gl=new fl;function hr(e,t,r){return gl.diff(e,t,r)}class hl extends Be{constructor(){super(...arguments);this.tokenize=jg}equals(e,t,r){if(r.ignoreWhitespace){if(!r.newlineIsToken||!e.includes(`
83
+ `)}}async function Ig(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:Me(a.entity)}]:[]);return{kind:"ok",value:s.filter(({entityId:a},l)=>s.findIndex((d)=>d.entityId===a)===l)}}function cl(e,t){return e.entityRegistry.getEntityTypeConfig(t).consumesSources??[]}function xg(e,t,r){if(t.kind!=="prompt"&&t.kind!=="prompt-from-source")return;let i=cl(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 ll(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 Pg(e,t,r,i){let n=await ll(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 Cg(e,t,r,i,n,o){let{entityService:s,jobs:a}=e,l=Hi(ee(dl(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=al(e.entityRegistry,{entityType:t.entityType,id:l,title:d});if(!u)return{success:!1,error:`Entity type '${t.entityType}' does not support queued generation. Provide an exact source to system_create instead.`};let p;try{p=(await s.createEntity({entity:u,options:{deduplicateId:!0,...n?{eventContext:n}:{}}})).entityId}catch(g){return{success:!1,error:P(g,"Failed to persist generation stub")}}let m={entityId:p,prompt:r,...t.title&&{title:t.title},...t.sourceEntityType&&{sourceEntityType:t.sourceEntityType},...t.sourceEntityId&&{sourceEntityId:t.sourceEntityId},...t.sourceEntityIds&&{sourceEntityIds:t.sourceEntityIds},...t.targetEntityType&&{targetEntityType:t.targetEntityType},...t.targetEntityId&&{targetEntityId:t.targetEntityId}},f=e.entityRegistry.getGenerationEnqueuer(t.entityType);try{let g=f?await f(m,o):await a.enqueue({type:`${t.entityType}:generation`,data:m,toolContext:o});return{success:!0,data:{entityId:p,status:"generating",jobId:g}}}catch(g){return await s.deleteEntity({entityType:t.entityType,id:p}).catch((h)=>{e.logger.warn("Failed to remove unqueued generation stub",{entityType:t.entityType,entityId:p,error:h})}),{success:!1,error:P(g,"Failed to queue generation job")}}}function dl(e,t,r){return e.title??t??r}async function Tg(e,t,r){let i=ar(t.title);if(t.kind==="prompt"||t.kind==="prompt-from-source"){if(e.entityRegistry.getEntityTypeConfig(t.entityType).binaryStorage)return T(`Prompt generation does not support binary entity type '${t.entityType}'. Use operation.kind 'attachment' for source-derived artifacts, or 'standalone-image' or 'cover-image' for generated images.`,"unsupported-generation");let l=t.kind==="prompt-from-source"?await Ig(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:cl(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 ll(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 Pg(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 Eg(e,t,r){let i=t.operation,n=A(r.userPermissionLevel),o=xg(e,i,r);if(o)return X(o);let s=await Tg(e,i,n);if(s.kind==="error")return s;let{createInput:a,sourceAttachment:l,writtenFrom:d}=s.value,p="prompt"in i&&i.prompt!==void 0&&!d?.usedUp?void 0:d?.entries[0]?.entityId,m=lr(e,a.entityType,r);if(m.kind==="error")return m;let{interceptor:f}=m.value;if(!a.prompt&&!a.from)return T("Provide a generation source.");if(a.from&&!f)return T(`Entity type '${a.entityType}' does not support attachment-based generation. Use operation.kind prompt-from-source for AI-generated content based on referenced source material, or choose an entity type with an attachment provider.`,"unsupported-generation");let g=i.kind==="prompt"||i.kind==="prompt-from-source",h=f&&!g?void 0:await cr(e,{entityType:a.entityType,candidateId:a.prompt?Hi(ee(dl(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:Ag(i,a,l),interceptor:f,eventContext:ze(r),...h?.value&&{replacesFailed:h.value},writtenFrom:d,sourceName:p}}}function Ag(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 ul(e){let t=Y({label:"generate",requestNoun:"generation"});return W("generate","Generate durable content or artifacts. Requires confirmation: calling this tool without confirmed is how you request it, so when the user asks to create, write, draft, or generate new durable content without supplying final exact content, call it instead of drafting the content in chat, asking for separate prose approval, or saying 'I can generate it if you want' or 'I need to queue it first'. Critical: broad or underspecified topical generation uses operation.kind prompt with no source field, also in the same turn after an optional search finds no source; preserve the user's wording as the prompt and do not stop to ask what details to highlight. Critical: to generate from an existing source such as 'my latest blog post', resolve it with read/search/list tools unless the user gives an exact entity id in quotes, then call operation.kind prompt-from-source right away, for example { kind: 'prompt-from-source', entityType: 'newsletter', source: { entityType: 'post', entityId: '...' }, prompt: '...' }. For the latest published/blog source, use system_list on that type (blog posts: entityType post) and choose the newest candidate by publishedAt, not updated/created or semantic search order; do not stop with prose like 'I found it and can generate it' or 'if that is the one you mean.' Never invent source IDs, use brain-character/profile, uploads, filenames, guessed ids, or placeholders as source refs. Turning an existing entity into another type ('turn my note X into a post') keeps its text and is not generation: call system_create with source.kind entity, also after a search resolves it. Turning an uploaded file into a note is extraction too: system_create on the upload with transform extract-markdown, never generation, however little text it holds. Use system_create as well for saving/importing existing text, URLs, uploads, prior assistant responses, or raw uploaded files. Critical: for a request to generate a post/social-post/newsletter/etc. with a cover image, call only the prompt generation first; call cover-image only once the target entity exists after confirmation, never guess its future id, and never use standalone-image as a substitute for a requested cover. When a cover-image request names the target's exact id in quotes or a search/get resolves a clear target, call cover-image in the same turn; do not stop after saying you found the entity. Use attachment for source-derived artifacts: attachmentType og-image for OG/social preview renders (the provider updates ogImageId), carousel for deck carousel PDFs, printable for post/project PDFs. Call it immediately for save/render requests, with replace:true for regenerate/replace/refresh, instead of saying you can queue it later. To attach a generated artifact to another entity, generate the artifact first in the same turn \u2014 do not ask whether they mean an existing artifact when the source entity is explicit or given as a quoted id such as deck `distributed-systems-primer` \u2014 and update the target only after the real artifact ID exists.",Dc,async(r,i)=>{let n=await Eg(e,r,i);if(n.kind==="error")return n.result;let{createInput:o,operation:s,interceptor:a,eventContext:l,replacesFailed:d,writtenFrom:u,sourceName:p}=n.value;return dr({gate:t,input:r,replacesFailed:d,confirmation:()=>({toolName:"system_generate",...wg(o,u,"prompt"in s?s.prompt:void 0),args:{operation:s}}),run:()=>ot(e,i,{createInput:o,interceptor:a,replacesFailed:d,persist:async(m)=>{if(!m.prompt)return{success:!1,error:"Attachment generation is supported only for entity types that explicitly handle source-derived artifacts."};return Cg(e,m,m.prompt,p,l,i)}})})},{visibility:"trusted",sideEffects:"writes"})}function pl(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.",Oc,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=Oe(e,o.entityType);if(l)return l;if(r.getAdapter(o.entityType).isSingleton===!0)return{success:!1,error:`${o.entityType} is a singleton entity and cannot be deleted through system tools. Update it instead.`};let d=A(s.userPermissionLevel),u=await _(t,{entityType:o.entityType,identifier:o.id},{visibilityScope:d,logger:i});if(!u.ok)return{success:!1,error:u.error};let{entity:p}=u;if(o.confirmed){let g=n.validateConfirmed(o.confirmationToken,o);if(g)return g;try{await t.deleteEntity({entityType:o.entityType,id:p.id})}catch(h){return{success:!1,error:P(h,"Failed to delete entity")}}return{success:!0,data:{deleted:p.id}}}let m=Me(p),f=n.buildArgs((g)=>({...o,id:p.id,confirmed:!0,confirmationToken:g}));return{needsConfirmation:!0,toolName:"system_delete",summary:`Delete "${m}"?`,preview:p.content.slice(0,200),args:f}},{visibility:"admin",sideEffects:"writes"})}function ml(e,t){let r=t.map(({oldText:o,newText:s},a)=>{let l=e.indexOf(o);if(!o||l<0)throw Error(`Edit ${a+1}: oldText was not found. Fetch the entity again and provide exact text.`);if(e.indexOf(o,l+1)!==-1)throw Error(`Edit ${a+1}: oldText is ambiguous. Include more surrounding text to match exactly once.`);return{start:l,end:l+o.length,newText:s}}).sort((o,s)=>o.start-s.start),i=0,n=[];for(let o of r){if(o.start<i)throw Error("Edits overlap in the original content. Provide non-overlapping replacements.");n.push(e.slice(i,o.start),o.newText),i=o.end}return n.push(e.slice(i)),n.join("")}import{isDeepStrictEqual as an}from"util";class Be{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}],f=this.extractCommon(m[0],t,e,0,r);if(m[0].oldPos+1>=a&&f+1>=s)return o(this.buildValues(m[0].lastComponent,t,e));let g=-1/0,h=1/0,v=()=>{for(let y=Math.max(g,-l);y<=Math.min(h,l);y+=2){let S,b=m[y-1],R=m[y+1];if(b)m[y-1]=void 0;let I=!1;if(R){let z=R.oldPos-y;I=R&&0<=z&&z<s}let E=b&&b.oldPos+1<a;if(!I&&!E){m[y]=void 0;continue}if(!E||I&&b.oldPos<R.oldPos)S=this.addToPath(R,!0,!1,0,r);else S=this.addToPath(b,!1,!0,1,r);if(f=this.extractCommon(S,t,e,y,r),S.oldPos+1>=a&&f+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(f+1>=s)g=Math.max(g,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 f=r[l+m];return f.length>p.length?f:p}),d.value=this.join(u)}else d.value=this.join(t.slice(a,a+d.count));if(a+=d.count,!d.added)l+=d.count}else d.value=this.join(r.slice(l,l+d.count)),l+=d.count}return i}}class fl extends Be{tokenize(e){return e.slice()}join(e){return e}removeEmpty(e){return e}}var gl=new fl;function hr(e,t,r){return gl.diff(e,t,r)}class hl extends Be{constructor(){super(...arguments);this.tokenize=jg}equals(e,t,r){if(r.ignoreWhitespace){if(!r.newlineIsToken||!e.includes(`
84
84
  `))e=e.trim();if(!r.newlineIsToken||!t.includes(`
85
85
  `))t=t.trim()}else if(r.ignoreNewlineAtEof&&!r.newlineIsToken){if(e.endsWith(`
86
86
  `))e=e.slice(0,-1);if(t.endsWith(`
@@ -108,10 +108,10 @@ ${qc(i)}`:a,args:t.buildArgs((d)=>({...l,confirmed:!0,confirmationToken:d}))}}as
108
108
  `).trim()).filter((n)=>n.length>0).map((n,o)=>({index:o,heading:Xl.test(n)?n.split(`
109
109
  `)[0]??"":"",text:n}))}function Rh(e,t){let r=cn(t.heading),i=cn(t.text);return Array.from(e).reduce((n,o)=>n+(i.has(o)?1:0)+(r.has(o)?1:0),0)}function ed(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 id(e,t,r=td){if(e.length<=r)return e;let i=cn(t),n=Sh(e).map((a)=>({section:a,score:Rh(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 ed(e.trim(),r);if(o.text.length>r)return ed(o.text,r);let{kept:s}=n.reduce((a,l)=>{let d=l.text.length+(a.kept.length>0?Yl.length:0);return a.used+d<=r?{used:a.used+d,kept:[...a.kept,l]}:a},{used:0,kept:[]});return s.sort((a,l)=>a.index-l.index).map((a,l,d)=>{let u=d[l-1];if(!u)return a.text;return`${a.index===u.index+1?`
110
110
 
111
- `:Yl}${a.text}`}).join("")}var wh=0.5;function nd(e,t){let r=e??t.limit;return t.maxLimit===void 0?r:Math.min(r,t.maxLimit)}function od(e,t,r,i){let n=Li(e.entity,r);if(n!==e.entity)return{...e,entity:n,excerpt:n.content};let o=Le(n.content);if(o.length<=i)return{...e,entity:n};let{content:s,...a}=n;return{...e,entity:a,excerpt:id(o,t,i),excerpted:!0}}var wr=(e)=>e==="public"?{publishedOnly:!0}:{};function Ih(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 sd(e){let{entityService:t,logger:r}=e;return[de("system","search","Search entities using semantic search. For broad search, make one system_search call with scope.kind all. Use scope.kind type only when the user asks for a specific entity type. When the user names entity types, search each with scope.kind type in the same step, without a broad search first. Applies a default minScore of 0.5 to reduce weak matches; lower minScore only for exploratory or loose recall. An empty result with belowThreshold means weaker matches exist: search again with a lower minScore before concluding that nothing relevant exists. When the question is in a different language from the saved content, also search with the query translated into the content's language before concluding that little exists; the content's language is the language of the search results and of the brain's profile, and matches across languages score lower. Search results include each matched entity's content; a long one's is excerpted to its best-matching sections, which system_get reads whole. When relevant results already contain the complete evidence needed, answer from those results instead of redundantly listing or getting the same entities. When a typed search's results hold that type's entities but not a detail the user asked about, the detail is not saved there: answer from what the results say and name what is missing, rather than searching the same type again with added words. 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?'.",Cc,async(i,n)=>{Rr(n);let o=A(n.userPermissionLevel);if(i.scope.kind==="type"&&e.entityRegistry.getEntityTypeConfig(i.scope.entityType).embeddable===!1){let{entityType:u}=i.scope;return{success:!0,data:{results:(await t.listEntities({entityType:u,options:{limit:nd(i.limit,e.searchBudget),filter:{visibilityScope:o},...wr(o)}})).map((m)=>od({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??wh,a=await t.search({query:i.query,options:{limit:nd(i.limit,e.searchBudget),...i.scope.kind==="type"&&{types:[i.scope.entityType]},...i.includeUngenerated!==void 0&&{includeUngenerated:i.includeUngenerated},visibilityScope:o,...wr(o)}}),l=a.filter((u)=>u.score>=s),d=l.length===0?Ih(a,s):void 0;return{success:!0,data:{results:l.map((u)=>od(u,i.query,e.entityRegistry,e.searchBudget.excerptChars)),...d&&{belowThreshold:d}}}},{visibility:"public",sideEffects:"none",cli:{name:"search"}}),de("system","get","Retrieve a specific entity by type and identifier (ID, slug, or title). When the user asks to read, show or verify an entity, call system_get in that turn instead of answering from earlier results in this conversation: stored content can change outside this conversation. If retrieval fails, report the entity as not found rather than describing related generation work as pending.",Tc,async(i,n)=>{if(Rr(n),!t.getEntityTypes().includes(i.entityType))return{success:!1,error:`Unknown entity type: ${i.entityType}. Available: ${t.getEntityTypes().join(", ")}`};let o=A(n.userPermissionLevel),s=await _(t,{entityType:i.entityType,identifier:i.id},{visibilityScope:o,logger:r,read:{...wr(o),source:!0}});if(!s.ok)return{success:!1,error:s.error};let a=Li(s.entity,e.entityRegistry);return{success:!0,data:{entity:i.part==="body"?{...a,content:Le(a.content)}:a}}},{visibility:"public",sideEffects:"none",cli:{name:"get"}}),de("system","list","List entities by a known entity type. Returns metadata only; it answers a request to show or list items of a type, such as titles, dates and descriptions, so answer from it and use system_get only when the user asks about an item's full content. Use system_search, not system_list, for broad or vague lookup requests. For list/show-all requests that name or browse a known type or synonym (essays/articles/blog posts => post), list that type instead of searching; for a whole-type summary such as 'summarize my blog posts', list it first, then summarize the returned entities. Use system_list to inspect metadata dates such as publishedAt when the user asks for the latest item of a known type, such as latest blog post.",Ec,async(i,n)=>{if(Rr(n),!t.getEntityTypes().includes(i.entityType))return{success:!1,error:`Unknown entity type: ${i.entityType}. Available: ${t.getEntityTypes().join(", ")}`};let o=A(n.userPermissionLevel),s={visibilityScope:o};if(i.status&&i.status!=="any")s.metadata={status:i.status};let{defaultSort:a}=e.entityRegistry.getEntityTypeConfig(i.entityType),d=(await t.listEntities({entityType:i.entityType,options:{limit:i.limit??20,filter:s,...wr(o),...a?{sortFields:a}:{}}})).map(({content:u,contentHash:p,...m})=>m);return{success:!0,data:{entities:d,count:d.length}}},{visibility:"public",sideEffects:"none",cli:{name:"list"}})]}function xh(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 Ph(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(xh),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 ad(e){let{entityService:t,analytics:r}=e,i=r.getDefinitions(),n=i.map((o)=>`${o.type} (${o.description})`).join("; ");return[de("system","analytics",`Aggregate metrics and reports over the brain, not its content: for actual content use system_list, system_get or system_search. Reports: ${n}.`,Ph(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 cd(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.",zc,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 Ch(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 ld(e){return[de("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:Ch(await e.getAppInfo(),(i)=>e.permissionService.hasPermission(r.userPermissionLevel??"public",i))}),{visibility:"public",sideEffects:"none",cli:{name:"status"}})]}function dd(e){return[...sd(e),...cd(e),...ld(e),...Kl(e),...ad(e)]}function ud(e){return[{uri:"entity://types",name:"Entity Types",description:"List of registered entity types",mimeType:"text/plain",handler:async()=>({contents:[{uri:"entity://types",mimeType:"text/plain",text:e.entityService.getEntityTypes().join(`
111
+ `:Yl}${a.text}`}).join("")}var wh=0.5;function nd(e,t){let r=e??t.limit;return t.maxLimit===void 0?r:Math.min(r,t.maxLimit)}function od(e,t,r,i){let n=Li(e.entity,r);if(n!==e.entity)return{...e,entity:n,excerpt:n.content};let o=Le(n.content);if(o.length<=i)return{...e,entity:n};let{content:s,...a}=n;return{...e,entity:a,excerpt:id(o,t,i),excerpted:!0}}var wr=(e)=>e==="public"?{publishedOnly:!0}:{};function Ih(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 sd(e){let{entityService:t,logger:r}=e;return[de("system","search","Search entities using semantic search. For broad search, make one system_search call with scope.kind all. Use scope.kind type only when the user asks for a specific entity type. When the user names entity types, search each with scope.kind type in the same step, without a broad search first. Applies a default minScore of 0.5 to reduce weak matches; lower minScore only for exploratory or loose recall. An empty result with belowThreshold means weaker matches exist: search again with a lower minScore before concluding that nothing relevant exists. When the question is in a different language from the saved content, also search with the query translated into the content's language before concluding that little exists; the content's language is the language of the search results and of the brain's profile, and matches across languages score lower. Search results include each matched entity's content; a long one's is excerpted to its best-matching sections, which system_get reads whole. When relevant results already contain the complete evidence needed, answer from those results instead of redundantly listing or getting the same entities. When a typed search's results hold that type's entities but not a detail the user asked about, the detail is not saved there: answer from what the results say and name what is missing, rather than searching the same type again with added words or a lower minScore. Search results are candidates; do not present weak or unrelated candidates as exact matches. For each new user question about what they have written, mentioned, discussed, or saved, run a fresh search for that turn instead of answering from prior-turn results or memory, including analysis phrasing such as 'How do I discuss X in my writing?'.",Cc,async(i,n)=>{Rr(n);let o=A(n.userPermissionLevel);if(i.scope.kind==="type"&&e.entityRegistry.getEntityTypeConfig(i.scope.entityType).embeddable===!1){let{entityType:u}=i.scope;return{success:!0,data:{results:(await t.listEntities({entityType:u,options:{limit:nd(i.limit,e.searchBudget),filter:{visibilityScope:o},...wr(o)}})).map((m)=>od({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??wh,a=await t.search({query:i.query,options:{limit:nd(i.limit,e.searchBudget),...i.scope.kind==="type"&&{types:[i.scope.entityType]},...i.includeUngenerated!==void 0&&{includeUngenerated:i.includeUngenerated},visibilityScope:o,...wr(o)}}),l=a.filter((u)=>u.score>=s),d=l.length===0?Ih(a,s):void 0;return{success:!0,data:{results:l.map((u)=>od(u,i.query,e.entityRegistry,e.searchBudget.excerptChars)),...d&&{belowThreshold:d}}}},{visibility:"public",sideEffects:"none",cli:{name:"search"}}),de("system","get","Retrieve a specific entity by type and identifier (ID, slug, or title). When the user asks to read, show or verify an entity, call system_get in that turn instead of answering from earlier results in this conversation: stored content can change outside this conversation. If retrieval fails, report the entity as not found rather than describing related generation work as pending.",Tc,async(i,n)=>{if(Rr(n),!t.getEntityTypes().includes(i.entityType))return{success:!1,error:`Unknown entity type: ${i.entityType}. Available: ${t.getEntityTypes().join(", ")}`};let o=A(n.userPermissionLevel),s=await _(t,{entityType:i.entityType,identifier:i.id},{visibilityScope:o,logger:r,read:{...wr(o),source:!0}});if(!s.ok)return{success:!1,error:s.error};let a=Li(s.entity,e.entityRegistry);return{success:!0,data:{entity:i.part==="body"?{...a,content:Le(a.content)}:a}}},{visibility:"public",sideEffects:"none",cli:{name:"get"}}),de("system","list","List entities by a known entity type. Returns metadata only; it answers a request to show or list items of a type, such as titles, dates and descriptions, so answer from it and use system_get only when the user asks about an item's full content. Use system_search, not system_list, for broad or vague lookup requests. For list/show-all requests that name or browse a known type or synonym (essays/articles/blog posts => post), list that type instead of searching; for a whole-type summary such as 'summarize my blog posts', list it first, then summarize the returned entities. Use system_list to inspect metadata dates such as publishedAt when the user asks for the latest item of a known type, such as latest blog post.",Ec,async(i,n)=>{if(Rr(n),!t.getEntityTypes().includes(i.entityType))return{success:!1,error:`Unknown entity type: ${i.entityType}. Available: ${t.getEntityTypes().join(", ")}`};let o=A(n.userPermissionLevel),s={visibilityScope:o};if(i.status&&i.status!=="any")s.metadata={status:i.status};let{defaultSort:a}=e.entityRegistry.getEntityTypeConfig(i.entityType),d=(await t.listEntities({entityType:i.entityType,options:{limit:i.limit??20,filter:s,...wr(o),...a?{sortFields:a}:{}}})).map(({content:u,contentHash:p,...m})=>m);return{success:!0,data:{entities:d,count:d.length}}},{visibility:"public",sideEffects:"none",cli:{name:"list"}})]}function xh(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 Ph(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(xh),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 ad(e){let{entityService:t,analytics:r}=e,i=r.getDefinitions(),n=i.map((o)=>`${o.type} (${o.description})`).join("; ");return[de("system","analytics",`Aggregate metrics and reports over the brain, not its content: for actual content use system_list, system_get or system_search. Reports: ${n}.`,Ph(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 cd(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.",zc,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 Ch(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 ld(e){return[de("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:Ch(await e.getAppInfo(),(i)=>e.permissionService.hasPermission(r.userPermissionLevel??"public",i))}),{visibility:"public",sideEffects:"none",cli:{name:"status"}})]}function dd(e){return[...sd(e),...cd(e),...ld(e),...Kl(e),...ad(e)]}function ud(e){return[{uri:"entity://types",name:"Entity Types",description:"List of registered entity types",mimeType:"text/plain",handler:async()=>({contents:[{uri:"entity://types",mimeType:"text/plain",text:e.entityService.getEntityTypes().join(`
112
112
  `)}]})},{uri:"brain://identity",name:"Brain Identity",description:"Brain character \u2014 name, role, purpose, values",mimeType:"application/json",handler:async()=>({contents:[{uri:"brain://identity",mimeType:"application/json",text:JSON.stringify(e.getIdentity(),null,2)}]})},{uri:"brain://profile",name:"Anchor Profile",description:"Brain owner profile \u2014 name, bio, expertise",mimeType:"application/json",handler:async()=>({contents:[{uri:"brain://profile",mimeType:"application/json",text:JSON.stringify(e.getProfile(),null,2)}]})},{uri:"brain://status",name:"Brain Status",description:"System status \u2014 version, model, interfaces, tools",mimeType:"application/json",handler:async()=>({contents:[{uri:"brain://status",mimeType:"application/json",text:JSON.stringify(await e.getAppInfo(),null,2)}]})}]}function md(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 pd(t,n.content,n.metadata):n.content;return{contents:[{uri:`entity://${r}/${i}`,mimeType:"text/markdown",text:o}]}}}]}function fd(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 Th(e,t){let r=De(e.permissionService),i=e.entityRegistry.getEntityTypeConfig(t);return["create","update","delete"].every((n)=>r(t,n))&&i.embeddable===!1&&i.fullTextSearchable===!1}function gd(e){return["## Entity CRUD","","Use the system tools for ALL entity operations; each tool's description is its contract.","","Treat explicit verbs such as save, create, capture, remember, import, add/connect an agent, approve/archive an agent, update, delete, generate, publish, or sync as mutation requests. Entity-specific instructions may require proactively recording the user's request itself for demand or workflow tracking; follow those instructions even when the user did not use a separate save/create verb. Ordinary status questions like 'what is the status', 'is it ready', 'did that finish', or 'what happened' are not capture requests; answer them by using the relevant status/read tool for the prior operation. Never call system_create for a status follow-up.","","Do not ask for prose confirmation instead of calling the applicable mutating tool; for create, update, delete, generate, publish, sync, and similar state-changing requests, the initial tool call without `confirmed` is how you create the pending confirmation. Never pass `confirmed: true` on the initial user request. Deletion is Admin-only: if system_delete is not available in the current tool surface, say deletion requires Admin access without calling any tool to find or read the target; do not imply a confirmation flow is available. Never claim a durable create/update/delete change was saved, created, done, or completed unless the relevant tool call succeeded or returned a pending confirmation. If a create/update/delete tool is unavailable, unauthorized, or intentionally not called, say you can't make that durable change from the current context; never say saved/created/done. For an explicit write request from an unauthorized/currently unwritable context, refuse directly; do not call system_status or system_search to check permission or look up related content. Entity type descriptions may mark projection-owned or system-maintained types read-only; refuse mutation requests for those types directly without calling read or write tools, searching for a target, or asking which record to mutate.","","Entity types \u2014 select `entityType` by what the type is for:",...e.entityService.getEntityTypes().filter((i)=>!Th(e,i)).map((i)=>`- ${i}: ${e.entityRegistry.getAdapter(i).purpose}`)].join(`
113
113
  `)}var Eh=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 vd(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 Ah=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 kh(e,t){let r=Ah.safeParse(e);if(!r.success)return!1;let{operation:i}=r.data,n=vd(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 bd(e,t,r){return yd(t,hd,async(i)=>{let n=e.find(({name:a})=>a==="system_generate");if(!n)return{status:"refused",error:"Generation is unavailable."};if(i.approval&&!kh(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=Eh.parse(await n.handler(i.approval??{operation:vd(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 Fe="system",jh=c.object({toolName:c.string(),args:c.unknown(),...Sd.partial().shape});function Ir(e,t,r,i,n){for(let o of e)try{t(o)}catch{n.debug(`System ${i} ${r(o)} already registered, skipping`)}}function Rd(e,t,r,i){let n=dd(e);Ir(n,(p)=>t.registerTool(Fe,p),(p)=>p.name,"tool",i);let o=r.subscribe(Yt.toolExecute(Fe),async(p)=>{let m=jh.safeParse(p.payload);if(!m.success)return{success:!1,error:"Invalid system tool execute payload"};let{toolName:f,args:g,interfaceType:h,actor:v,conversationId:y,channelId:S,userPermissionLevel:b}=m.data,R=n.find((z)=>z.name===f);if(!R)return{success:!1,error:`System tool not found: ${f}`};let I={interfaceType:h??"system",actor:v??{kind:"service",serviceId:"system"}};if(y)I.conversationId=y;if(S)I.channelId=S;if(b)I.userPermissionLevel=b;return{success:!0,data:await R.handler(g,I)}});i.debug(`Registered ${n.length} system tools`);let s=ud(e);Ir(s,(p)=>t.registerResource(Fe,p),(p)=>p.uri,"resource",i),i.debug(`Registered ${s.length} system resources`);let a=md(e);Ir(a,(p)=>t.registerResourceTemplate(Fe,p),(p)=>p.uriTemplate,"resource template",i),i.debug(`Registered ${a.length} system resource templates`);let l=fd(e);Ir(l,(p)=>t.registerPrompt(Fe,p),(p)=>p.name,"prompt",i),i.debug(`Registered ${l.length} system prompts`);let d=gd(e);try{t.registerInstructions(Fe,d)}catch{i.debug("System instructions already registered, skipping")}i.debug("Registered system instructions");let u=bd(n,r,i);return()=>{o(),u()}}function Cd(e){let{services:t,jobs:r,analytics:i,query:n,getAppInfo:o}=e,s=t.jobQueueService,a=t.logger.child("system"),l=Rd({entityService:t.entityService,entityRegistry:t.entityRegistry,jobs:{...r,enqueue:wd(s,"system",!1),enqueueBatch:xd(r,"system"),registerHandler:Pd(s,"system"),has:Id(s)},conversationService:t.conversationService,runtimeUploads:t.runtimeUploadRegistry,attachments:xr(t.attachmentRegistry),logger:a,query:n,getIdentity:()=>t.identityService.getCharacter(),getProfile:()=>t.profileService.getProfile(),getAppInfo:o,searchBudget:rd(t.aiService.getConfig().model),analytics:i,permissionService:t.permissionService},t.mcpService,t.messageBus,a);t.disposables.push(l)}class ln{scope;closePromise=null;closed=!1;constructor(){this.scope=w.runSync(D.make())}buildLayer(e){this.assertOpen();let t=w.runSyncExit(Q.buildWithScope(e,this.scope));if(j.isFailure(t))throw oe.squash(t.cause);return t.value}addFinalizer(e){this.assertOpen(),w.runSync(D.addFinalizer(this.scope,w.promise(async()=>{await e()})))}addSyncFinalizer(e){this.assertOpen(),w.runSync(D.addFinalizer(this.scope,w.sync(()=>{e()})))}async fork(e){if(this.closed)throw Error("Cannot start background work after shell shutdown");await w.runPromise(w.forkIn(e,this.scope))}close(e=j.void){if(this.closePromise)return this.closePromise;if(this.closed)return Promise.resolve();return this.closed=!0,this.closePromise=w.runPromise(D.close(this.scope,e)),this.closePromise}closeSync(e){if(this.closed)return;this.closed=!0,w.runSync(D.close(this.scope,e))}assertOpen(){if(this.closed)throw Error("Cannot register cleanup after shell shutdown")}}class dn{config;services;lifecycle;bootloader;initialized=!1;lifecycleState="constructed";bootMode;bootPromise=null;shutdownPromise=null;analyticsRegistry;bootTime=Date.now();endpointRegistry=new Ai;interactionRegistry=new ki;httpRouteRegistry=tr.createFresh();httpServed;jobs;static createFresh(e,t,r){return new dn(gt(e),t,r)}constructor(e,t,r){this.config=e,this.httpServed=e.http.enabled&&Ce(r?.processRole).serves,this.lifecycle=new ln,zd(this,()=>this.httpRouteRegistry.getSnapshot());let i=t?.logger??Pe.getInstance(),n=Ut.createFresh(i,this.config,r?.processRole,r?.peerChannel);try{if(this.services=n.initializeServices(this.lifecycle,t),this.jobs=vc(this.services.batchJobManager,this.services.jobQueueService),this.analyticsRegistry=mc(this.services.entityRegistry),this.bootloader=new Ti(this.config,this.services,this.lifecycle,n,r?.processRole,{registerCoreDataSources:()=>Dn(this.services,this.config),finalizeHttpRoutes:()=>{this.httpRouteRegistry.finalize(Sc(this.services.pluginManager))},registerSystemCapabilities:()=>Cd({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();Ic(this.lifecycle,this.services)}catch(o){try{this.lifecycle.closeSync(j.fail(o))}catch(s){i.error("Failed to roll back Shell service construction",s)}throw o}}createProjectionInputContext(){return{entities:this.services.entityService,resolvePrompt:(e,t)=>ht(this.services.entityService,e,t),appInfo:()=>this.getAppInfo(),identityInput:()=>{let e=this.getIdentity(),t=this.getProfile();return Ed.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:kd(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 Ee(this.services.messageBus,jd,{timestamp:new Date().toISOString()},"shell"),this.services.logger.debug("Emitted shell ready event")}}catch(t){if(this.initialized=!1,this.services.logger.error("Failed to initialize Shell",t),this.lifecycleState!=="closing")this.lifecycleState="failed";try{await this.lifecycle.close(j.fail(t))}catch(r){this.services.logger.error("Failed to clean up Shell after initialization failure",r)}throw t}}registerTemplates(e,t){this.services.logger.debug("Registering templates",{pluginId:t,count:Object.keys(e).length});for(let[r,i]of Object.entries(e))this.registerTemplate(r,i,t)}shutdown(){return this.shutdownPromise??=this.shutdownShell(),this.shutdownPromise}async shutdownShell(){if(this.services.logger.debug("Shutting down Shell"),this.lifecycleState==="closed")return;let e=this.bootPromise;if(this.lifecycleState="closing",this.initialized=!1,e)try{await e}catch{}await this.lifecycle.close(),this.lifecycleState="closed",this.services.logger.debug("Shell shutdown complete")}async generateContent(e,t){return this.requireInitialized("Shell content generation"),On(this.services,e,t)}async query(e,t){this.requireInitialized("Shell query");let r=await this.getAppInfo(),i={...t,appInfo:r,timestamp:new Date().toISOString()},{conversationHistory:n,...o}=i;return Td.parse(await this.generateContent({prompt:e,templateName:qe.KNOWLEDGE_QUERY,...n&&{conversationHistory:n},data:o,interfacePermissionGrant:"public"}))}registerPlugin(e){this.requireInitialized("Plugin registration"),this.services.pluginManager.registerPlugin(e)}isInitialized(){return this.initialized}requireInitialized(e){if(!this.initialized)throw Error(`${e} attempted before initialization`)}getEntityService(){return this.services.entityService}getConversationService(){return this.services.conversationService}getEntityRegistry(){return this.services.entityRegistry}async generateObject(e,t,r){this.requireInitialized("Shell generateObject");let{object:i}=await this.services.aiService.generateObject("You are a helpful assistant. Respond with the requested structured data.",e,t,r);return{object:i}}async judge(e){return this.requireInitialized("Shell judge"),this.services.aiService.judge(e)}getAIService(){return this.services.aiService}generateImage(e,t){return this.services.aiService.generateImage(e,t)}canGenerateImages(){return this.services.aiService.canGenerateImages()}canDescribeImages(){return this.services.aiService.canDescribeImages?.()??!1}async describeImage(e,t){return this.services.aiService.describeImage?.(e,t)}getPluginManager(){return this.services.pluginManager}getContentService(){return this.services.contentService}getCallerAuthorizer(){return this.services.callerAuthorizer}getRenderService(){return this.services.renderService}getAttachmentRegistry(){return xr(this.services.attachmentRegistry)}getRuntimeUploadRegistry(){return Dd(this.services.runtimeUploadRegistry)}getRuntimeState(){return this.services.runtimeStateService}getRecurringChecks(e){return this.services.recurringCheckService.namespace(e)}isJobQueueWorkerRunning(){return this.services.jobQueueWorker.isWorkerRunning()}getMessageBus(){return this.services.messageBus}getLogger(){return this.services.logger}getJobQueueService(){return this.services.jobQueueService}getMCPService(){return this.services.mcpService}listToolsForPermissionLevel(e){return this.services.mcpService.listToolsForPermissionLevel(e).map(({pluginId:t,tool:r})=>({name:r.name,description:r.description,pluginId:t}))}getPermissionService(){return this.services.permissionService}getAgentService(){return this.services.agentService}registerTools(e,t){for(let r of t)this.services.mcpService.registerTool(e,r)}registerResources(e,t){for(let r of t)this.services.mcpService.registerResource(e,r)}registerResourceTemplate(e,t){this.services.mcpService.registerResourceTemplate(e,t)}registerPrompt(e,t){this.services.mcpService.registerPrompt(e,t)}registerInstructions(e,t){if(this.services.mcpService.registerInstructions(e,t),this.initialized)this.services.agentService.invalidateAgent()}async unregisterPluginCapabilities(e){this.services.mcpService.unregisterPlugin?.(e),this.services.jobQueueService.unregisterPluginHandlers(e),this.endpointRegistry.unregister(e),this.interactionRegistry.unregister(e);for(let r of this.services.templateRegistry.getNames())if(r.startsWith(`${e}:`))this.services.templateRegistry.unregister(r);let t=this.config.evalHandlerRegistry;if(t){for(let r of t.list())if(r.pluginId===e)t.unregister(e,r.handlerId)}this.services.agentService.invalidateAgent(),await this.services.recurringCheckService.unregisterPlugin(e)}getPluginPackageName(e){return this.services.pluginManager.getPluginPackageName(e)}hasPlugin(e){return this.services.pluginManager.hasPlugin(e)}getPluginHttpRouteManifest(){return this.httpRouteRegistry.getManifest()}getPluginApiRoutes(){return this.httpRouteRegistry.getApiRoutes()}getPluginWebRoutes(){return this.httpRouteRegistry.getWebRoutes()}registerDaemon(e,t,r){this.services.daemonRegistry.register(e,t,r)}registerEndpoint(e){this.endpointRegistry.register(e)}listEndpoints(){return this.endpointRegistry.list()}registerInteraction(e){this.interactionRegistry.register(e)}listInteractions(){return this.interactionRegistry.list()}registerTemplate(e,t,r){let i=r?`${r}:${e}`:`shell:${e}`;this.services.templateRegistry.register(i,t),this.services.logger.debug(`Registered template: ${i}`)}getTemplate(e){return this.services.templateRegistry.get(e)}getDataSourceRegistry(){return this.services.dataSourceRegistry}getIdentity(){return this.services.identityService.getCharacter()}getProfile(){return this.services.profileService.getProfile()}getProfileKindRegistry(){return this.services.profileKindRegistry}getChannelRegistry(){return this.services.channelRegistry}getInboxRegistry(){return this.services.inboxRegistry}getInboxFollowUpRegistry(){return this.services.inboxFollowUpRegistry}getOperationalHealthRegistry(){return this.services.operationalHealthRegistry}getAccountSettingsRegistry(){return this.services.accountSettingsRegistry}getAuthRegistry(){return this.services.authRegistry}getAtprotoProjectionRegistry(){return this.services.atprotoProjectionRegistry}getDomain(){return this.config.siteBaseUrl}getLocalSiteUrl(){return this.config.localSiteUrl}shouldPreferLocalUrls(){return this.config.preferLocalUrls}isProduction(){return this.config.production}servesHttp(){return this.httpServed}registerHttpHost(){let{daemonRegistry:e,logger:t,messageBus:r,pluginManager:i}=this.services;e.register(K,ec({config:this.config.http,domain:this.config.siteBaseUrl,logger:t.child(H),messageBus:r,getRoutes:()=>this.httpRouteRegistry.getSnapshot(),getPlugins:()=>[...i.getAllPlugins().values()].map(({plugin:s})=>s),getOperationalInfo:async()=>Od(Ad(await this.getAppInfo())),getReadinessData:()=>this.getRuntimeReadiness()}),H),this.lifecycle.addSyncFinalizer(()=>e.abandon(K));let{endpoints:n,interactions:o}=tc(this.config.http,this.config.siteBaseUrl);for(let s of n)this.endpointRegistry.register(s);for(let s of o)this.interactionRegistry.register(s)}getThemeCSS(){return this.config.themeCSS}getSpaces(){return this.config.spaces}getDataDir(){return this.config.dataDir}getGitBrokerSocket(){return this.config.gitBrokerSocket}getGitBrokerCheckout(){return this.config.gitBrokerCheckout}registerEvalHandler(e,t,r){this.config.evalHandlerRegistry?.register(e,t,r)}async getAppInfo(){return Rn({config:this.config,services:this.services,bootTime:this.bootTime,endpoints:()=>this.listEndpoints(),interactions:()=>this.listInteractions()})}getRuntimeReadiness(){return xn(this.services)}}async function Wd(e,t){await ue({label:"entity",config:e,schema:{assets:Ld,entities:Md,entityMutationReceipts:Ud,projectionDirtyInputs:Bd,projectionWaves:$d,projectionIncidents:_d,projectionWaveInputs:Fd,projectionWaveRules:Nd,projectionRuleMemos:Zd},migrationsFolder:pe(import.meta.url,"entity-service"),authTokenEnv:"DATABASE_AUTH_TOKEN",logger:t,afterMigrate:Hd})}async function Gd(e,t){await ue({label:"job-queue",config:e,schema:{jobQueue:qd,jobWorkerSessions:Jd},migrationsFolder:pe(import.meta.url,"job-queue"),authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",logger:t})}async function Yd(e,t){await ue({label:"conversation",config:e,schema:{conversations:Qd,messages:Kd,summaryTracking:Vd},migrationsFolder:pe(import.meta.url,"conversation-service"),authTokenEnv:"CONVERSATION_DATABASE_AUTH_TOKEN",logger:t})}async function Xd(e,t){await ue({label:"runtime-state",config:e,schema:{runtimeStateRecords:x},migrationsFolder:pe(import.meta.url,"runtime-state"),authTokenEnv:"RUNTIME_STATE_DATABASE_AUTH_TOKEN",logger:t})}import{mkdir as pn}from"fs/promises";import{isAbsolute as Dh}from"path";function eu(e=process.env){return{dataDir:e.XDG_DATA_HOME??"./data",cacheDir:e.XDG_CACHE_HOME??"./cache",distDir:"./dist"}}function tu(e=process.env){let t=e.BRAIN_GIT_BROKER_CHECKOUT;if(!t)return;if(!Dh(t))throw Error(`Git broker checkout path must be absolute: ${t}`);return t}function ru(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 iu(e=process.env){return fe(eu(e))}async function nu(e=process.env){let t=eu(e);try{await pn(t.dataDir,{recursive:!0}),await pn(t.cacheDir,{recursive:!0}),await pn(t.distDir,{recursive:!0})}catch(r){let i=r instanceof Error&&r.message.includes("EACCES")?`Cannot create data directories \u2014 permission denied. Run from a writable directory or check permissions on ${t.dataDir}`:`Cannot create data directories: ${P(r)}`;throw Error(i,{cause:r})}return fe(t)}class Oh{logger;migrations;constructor(e,t){this.logger=e,this.migrations=t??{getStandardConfigWithDirectories:()=>nu(),migrateEntities:Wd,migrateJobQueue:Gd,migrateConversations:Yd,migrateRuntimeState:Xd}}async runAllMigrations(e){this.logger.debug("Running database migrations...");let t=await this.migrations.getStandardConfigWithDirectories();if(e?.database)t.database.url=e.database;if(e?.jobQueueDatabase)t.jobQueueDatabase.url=e.jobQueueDatabase;if(e?.conversationDatabase)t.conversationDatabase.url=e.conversationDatabase;if(e?.runtimeStateDatabase)t.runtimeStateDatabase.url=e.runtimeStateDatabase;await this.migrateEntityDatabase(t),await this.migrateJobQueueDatabase(t),await this.migrateConversationDatabase(t),await this.migrateRuntimeStateDatabase(t),this.logger.debug("All database migrations completed successfully")}async migrateEntityDatabase(e){this.logger.debug("Running entity database migrations..."),await this.migrations.migrateEntities({url:e.database.url,...e.database.authToken&&{authToken:e.database.authToken}},this.logger)}async migrateJobQueueDatabase(e){this.logger.debug("Running job queue database migrations..."),await this.migrations.migrateJobQueue({url:e.jobQueueDatabase.url,...e.jobQueueDatabase.authToken&&{authToken:e.jobQueueDatabase.authToken}},this.logger)}async migrateConversationDatabase(e){this.logger.debug("Running conversation database migrations..."),await this.migrations.migrateConversations({url:e.conversationDatabase.url,...e.conversationDatabase.authToken&&{authToken:e.conversationDatabase.authToken}},this.logger)}async migrateRuntimeStateDatabase(e){this.logger.debug("Running runtime state database migrations..."),await this.migrations.migrateRuntimeState({url:e.runtimeStateDatabase.url,...e.runtimeStateDatabase.authToken&&{authToken:e.runtimeStateDatabase.authToken}},this.logger)}}var mn={kind:"service",serviceId:"brain-cli"},fn=`${mn.kind}:${mn.serviceId}`;function Pj(e="admin"){return{interfaceType:"cli",actor:mn,userPermissionLevel:e}}var Ej=c.enum(["eval"]),Aj=c.enum(["person","team","organization"]),gn=c.object({provider:c.enum(["hetzner","docker"]).default("hetzner"),serverSize:c.string().default("cx33"),location:c.string().default("fsn1"),domain:c.string().optional(),docker:c.object({enabled:c.boolean().default(!0),image:c.string().optional()}).prefault({}),ports:c.object({default:c.number().default(3333),preview:c.number().default(4321),production:c.number().default(8080)}).prefault({}),cdn:c.object({enabled:c.boolean().default(!1),provider:c.enum(["bunny","none"]).default("none")}).prefault({}),dns:c.object({enabled:c.boolean().default(!1),provider:c.enum(["bunny","none"]).default("none")}).prefault({}),paths:c.object({install:c.string().optional(),data:c.string().optional()}).prefault({})});var zh=c.object({providerKeys:We.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()}),su=c.object({name:c.string().default("brain-app"),version:c.string().default("1.0.0"),database:c.string().optional(),ai:zh.optional(),logLevel:xe.optional(),logFile:c.string().optional(),profileKind:c.string().trim().min(1).optional(),plugins:c.array(ft).default([]),spaces:c.array(c.string()).default([]),identity:ou.optional(),agentInstructions:c.array(c.string()).optional(),deployment:gn.prefault({}),http:He.prefault({})});var Mh="NODE_ENV";function Lh(){return process.env[Mh]}function hn(){return Lh()==="production"}function au(){return!hn()}var Uh="startup-check";function Bh(){return Object.fromEntries(un.map((e)=>[e,Uh]))}function qj(e){let r={...su.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 $h(r),_h(e,r),Fh(e,r,t),Nh(e,r),Zh(e,r),Hh(e,r),Wh(e,r),qh(e,r),Gh(e,r),Jh(e,r),r}function $h(e){let t=iu();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??=ru(),e.gitBrokerCheckout??=tu()}function _h(e,t){if(e.database)t.database={url:e.database};if(e.profileKind)t.profileKind=e.profileKind;t.features={}}function Fh(e,t,r){let i=r?.mode==="startup-check",{providerKeys:n,...o}=F(e.ai??{});if(!n&&Object.keys(o).length===0&&!i)return;t.ai={...t.ai,providerKeys:{...i&&Bh(),...t.ai?.providerKeys,...n},...o}}function Nh(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 Zh(e,t){let r=e.permissions?.rules??[];t.permissions={...e.permissions,rules:r.some((i)=>i.pattern===fn)?r:[{pattern:fn,level:"admin"},...r]}}function Hh(e,t){if(e.spaces)t.spaces=e.spaces}function Wh(e,t){if(e.identity)t.identity=e.identity}function qh(e,t){if(e.agentInstructions)t.agentInstructions=e.agentInstructions}function Jh(e,t){t.http??={...F(e.http),port:e.deployment.ports.production}}function Gh(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=au(),t.production=hn()}
114
114
  export{fe as P,He as Q,xe as R,gt as S,O as T,rp as U,ip as V,np as W,dp as X,eo as Y,pp as Z,mp as _,fp as $,gp as aa,hp as ba,yp as ca,vp as da,Yr as ea,oa as fa,Si as ga,xc as ha,Og as ia,Sl as ja,Ug as ka,wl as la,at as ma,Bg as na,Se as oa,Gi as pa,Qi as qa,Ki as ra,_g as sa,Hg as ta,Wg as ua,KT as va,kl as wa,jl as xa,Gg as ya,Qg as za,Kg as Aa,Vg as Ba,on as Ca,Yg as Da,Xg as Ea,ih as Fa,dn as Ga,Wd as Ha,Gd as Ia,Yd as Ja,Xd as Ka,Oh as La,Pj as Ma,Aj as Na,qj as Oa,Jj as Pa};
115
115
 
116
- //# debugId=A4877A080856B3B964756E2164756E21
117
- //# sourceMappingURL=index-dz05sh35.js.map
116
+ //# debugId=E45F3738710E4E8C64756E2164756E21
117
+ //# sourceMappingURL=index-68ge01gj.js.map