@rizom/brain 0.2.0-alpha.452 → 0.2.0-alpha.453

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 (33) hide show
  1. package/dist/brain.js +42 -42
  2. package/dist/chunks/{app-915n1gg7.js → app-bg53pvhx.js} +2 -2
  3. package/dist/chunks/{blog-post-adapter-5avah6v2.js → blog-post-adapter-hw4caebb.js} +2 -2
  4. package/dist/chunks/{index-sycvw55k.js → index-7exeb57a.js} +2 -2
  5. package/dist/chunks/{index-41yt4dm7.js → index-b3dbc07e.js} +3 -3
  6. package/dist/chunks/{index-41yt4dm7.js.map → index-b3dbc07e.js.map} +1 -1
  7. package/dist/chunks/{index-9xmz7sjy.js → index-jv41j8zg.js} +4 -4
  8. package/dist/chunks/{index-9xmz7sjy.js.map → index-jv41j8zg.js.map} +5 -5
  9. package/dist/chunks/{index-mrq4qv61.js → index-pm6wtjx7.js} +2 -2
  10. package/dist/chunks/{index-15rn9szm.js → index-tf2k5d73.js} +3 -3
  11. package/dist/chunks/{index-z43k2rmc.js → index-vasegzfn.js} +2 -2
  12. package/dist/chunks/linkedin-template-pg5cwy3q.js +5 -0
  13. package/dist/chunks/{rss-datasource-sgznwzkm.js → rss-datasource-g6sg1kbk.js} +2 -2
  14. package/dist/entities.js +1 -1
  15. package/dist/index.d.ts +4 -2
  16. package/dist/index.js +1 -1
  17. package/dist/interfaces.js +1 -1
  18. package/dist/model.d.ts +4 -2
  19. package/dist/model.js +40 -40
  20. package/dist/model.js.map +1 -1
  21. package/dist/plugins.js +1 -1
  22. package/dist/services.js +1 -1
  23. package/dist/ui/studio-chunks/main-gg87r17k.js.map +2 -2
  24. package/package.json +1 -1
  25. package/dist/chunks/linkedin-template-js7cztmp.js +0 -5
  26. /package/dist/chunks/{app-915n1gg7.js.map → app-bg53pvhx.js.map} +0 -0
  27. /package/dist/chunks/{blog-post-adapter-5avah6v2.js.map → blog-post-adapter-hw4caebb.js.map} +0 -0
  28. /package/dist/chunks/{index-sycvw55k.js.map → index-7exeb57a.js.map} +0 -0
  29. /package/dist/chunks/{index-mrq4qv61.js.map → index-pm6wtjx7.js.map} +0 -0
  30. /package/dist/chunks/{index-15rn9szm.js.map → index-tf2k5d73.js.map} +0 -0
  31. /package/dist/chunks/{index-z43k2rmc.js.map → index-vasegzfn.js.map} +0 -0
  32. /package/dist/chunks/{linkedin-template-js7cztmp.js.map → linkedin-template-pg5cwy3q.js.map} +0 -0
  33. /package/dist/chunks/{rss-datasource-sgznwzkm.js.map → rss-datasource-g6sg1kbk.js.map} +0 -0
@@ -112,7 +112,7 @@ params: ${t}`);if(this.query=e,this.params=t,this.cause=n,Error.captureStackTrac
112
112
  `).slice(1).join(`
113
113
  `).trim()}if(o){let s=o.replace(/\s+/g," ").trim(),c=s.length>500?s.substring(0,500)+"...":s;t.push(c)}}return t.join(`
114
114
 
115
- `)}parse(e){throw Error("BaseEntityFormatter is for display only. Use BaseEntityAdapter for parsing operations.")}}class yw{cache=null;cacheParseError=null;logger;entityService;entityType;defaultBody;readScope;constructor(e,t,n,r,o="public"){this.entityService=e,this.logger=t.child(this.constructor.name),this.entityType=n,this.defaultBody=r,this.readScope=o}async initialize(){if(await this.load())return;if(await this.load())return;this.logger.info(`No ${this.entityType} found, creating default ${this.entityType}`);try{let e=this.createContent(this.defaultBody);await this.entityService.createEntity({entity:{id:this.entityType,entityType:this.entityType,content:e,metadata:{}}}),await this.load(),this.logger.info(`Default ${this.entityType} created successfully`)}catch(e){this.logger.error(`Failed to create default ${this.entityType}`,{error:e})}}get(){if(this.cache&&!this.cacheParseError)return this.parseBody(this.cache.content);return this.defaultBody}getContent(){if(this.cache)return this.cache.content;return this.createContent(this.defaultBody)}async refreshCache(){await this.load()}async load(){try{let e=await this.entityService.getEntity({entityType:this.entityType,id:this.entityType,visibilityScope:this.readScope});if(this.cache=e,this.cacheParseError=null,e)try{return this.parseBody(e.content),this.logger.debug(`${this.entityType} loaded`),!0}catch(t){return this.cacheParseError=t instanceof Error?t:Error(String(t)),this.logger.error(`Failed to parse ${this.entityType} \u2014 using default. Fix the entity content to clear this error.`,{error:this.cacheParseError.message}),!0}else this.logger.debug(`No ${this.entityType} found in database`)}catch(e){this.logger.warn(`Failed to load ${this.entityType}`,{error:e}),this.cache=null,this.cacheParseError=null}return!1}}function MCe(e,t){let n=e.getAdapter(t.entityType);if(!n.buildStub)return;let r=n.buildStub({id:t.id,title:t.title}),o=new Date().toISOString();return{id:t.id,entityType:t.entityType,content:r.content,metadata:r.metadata,visibility:"public",created:o,updated:o,contentHash:""}}function pM(e,t){let{publishedOnly:n,visibilityScope:r}=t;if(!n&&!r)return e;let o=(s)=>r?{...s,visibilityScope:r}:s,i=(s)=>{let c=s?.filter?.metadata?.status!==void 0,l=o(s?.filter);return{...s,...n&&!c&&{publishedOnly:!0},...l&&{filter:l}}};return new Proxy(e,{get(s,c,l){if(c==="listEntities")return(p)=>s.listEntities({entityType:p.entityType,options:i(p.options)});if(c==="countEntities")return(p)=>s.countEntities({entityType:p.entityType,options:i(p.options)});if(c==="getEntity")return(p)=>s.getEntity({...p,visibilityScope:r,...n&&{publishedOnly:!0}});if(c==="search")return(p)=>s.search({...p,options:{...p.options,...r&&{visibilityScope:r},...n&&{publishedOnly:!0}}});if(c==="getEntityCounts")return async(p)=>{let d=r??p;if(!n)return s.getEntityCounts(d);return(await Promise.all(s.getEntityTypes().map(async(f)=>({entityType:f,count:await s.countEntities({entityType:f,options:{publishedOnly:!0,...d&&{filter:{visibilityScope:d}}}})})))).filter(({count:f})=>f>0)};let u=Reflect.get(s,c,l);return typeof u==="function"?u.bind(s):u}})}function S6(e,t){return t==="public"?e:`${e}-${t}`}function bw(e,t,n,r){let o=r.getEntityTypeConfig(e).publish?.publishStatuses;if(!o?.length||typeof n!=="string")return"non-publish";let i=typeof t==="string"&&o.includes(t);if(!o.includes(n))return"non-publish";return i?"within-publish-set":"boundary"}class dM{dataSources=new Map;logger;static createFresh(e){return new dM(e)}constructor(e){this.logger=e.child("DataSourceRegistry")}register(e){let t=e.id.includes(":")?e.id:`shell:${e.id}`;this.registerWithId(t,e)}registerWithId(e,t){if(this.dataSources.has(e)){let n=Error(`DataSource with id "${e}" already exists`);throw this.logger.error("DataSource registration failed",{error:n,id:e}),n}this.dataSources.set(e,t),this.logger.debug("DataSource registered",{id:e,name:t.name})}unregister(e){if(this.dataSources.delete(e))this.logger.debug("DataSource unregistered",{id:e});else this.logger.warn("Attempted to unregister non-existent DataSource",{id:e})}get(e){return this.dataSources.get(e)}has(e){return this.dataSources.has(e)}list(){return Array.from(this.dataSources.values())}getIds(){return Array.from(this.dataSources.keys())}getByCapability(e){return this.list().filter((t)=>{switch(e){case"canFetch":return!!t.fetch;case"canGenerate":return!!(t.generate??t.generateScoped);case"canTransform":return!!t.transform;default:return!1}})}find(e){return this.list().filter(e)}clear(){let e=this.dataSources.size;this.dataSources.clear(),this.logger.debug("DataSource registry cleared",{count:e})}}var v6=a.object({currentPage:a.number(),totalPages:a.number(),totalItems:a.number(),pageSize:a.number(),hasNextPage:a.boolean(),hasPrevPage:a.boolean()});function mM(e,t,n){let r=Math.max(1,Math.ceil(e/n));return{currentPage:t,totalPages:r,totalItems:e,pageSize:n,hasNextPage:t<r,hasPrevPage:t>1}}async function fM(e,t,n,r,o="public",i={}){let s={...i.signal&&{signal:i.signal},...i.publishedOnly&&{publishedOnly:!0}};try{s.signal?.throwIfAborted();let c=await e.getEntity({entityType:t,id:n,visibilityScope:o,...s});if(s.signal?.throwIfAborted(),c)return c;let l=await e.listEntities({entityType:t,options:{limit:1,filter:{metadata:{slug:n},visibilityScope:o},...s}});if(s.signal?.throwIfAborted(),l[0])return l[0];let u=await e.listEntities({entityType:t,options:{limit:1,filter:{metadata:{title:n},visibilityScope:o},...s}});if(s.signal?.throwIfAborted(),u[0])return u[0];let p=await e.listEntities({entityType:t,options:{limit:1,filter:{metadata:{title:Th(n)},visibilityScope:o},...s}});if(s.signal?.throwIfAborted(),p[0])return p[0];let d=await e.listEntities({entityType:t,options:{limit:200,filter:{visibilityScope:o},...s}});s.signal?.throwIfAborted();let g=Th(n);return d.find((f)=>typeof f.metadata.title==="string"&&Th(f.metadata.title)===g)??null}catch(c){if(r)r.error(`Failed to find entity ${t}:${n}`,{error:c});throw c}}async function T6(e,t,n,r,o="Entity",i="public",s={}){let c=await fM(e,t,n,r,i,s);if(!c)return{ok:!1,error:`${o} not found: ${t}/${n}`};return{ok:!0,entity:c}}var gM=a.record(a.string(),a.unknown());var _Ce=a.object({id:a.string(),sessionId:a.string(),interfaceType:a.string(),channelId:a.string(),personId:a.string().optional(),channelName:a.string().optional(),startedAt:a.string(),lastActiveAt:a.string(),createdAt:a.string(),updatedAt:a.string(),metadata:gM}),zCe=a.object({id:a.string(),conversationId:a.string(),role:Tm,content:a.string(),timestamp:a.string(),metadata:gM});var hM=a.object({name:a.string(),role:a.string(),purpose:a.string(),values:a.array(a.string())}),yM=a.object({name:a.string(),organization:a.string().optional(),description:a.string().optional(),avatar:a.string().optional(),website:a.string().optional(),email:a.string().optional(),socialLinks:a.array(a.object({platform:a.enum(["github","instagram","linkedin","email","website"]),url:a.string(),label:a.string().optional()})).optional()});var ey=256,bM=1048576,xM=32;class zs extends Error{constructor(e){super(e);this.name="GenerationLimitError"}}var FCe=`"\\\b\f
115
+ `)}parse(e){throw Error("BaseEntityFormatter is for display only. Use BaseEntityAdapter for parsing operations.")}}class yw{cache=null;cacheParseError=null;logger;entityService;entityType;defaultBody;readScope;constructor(e,t,n,r,o="public"){this.entityService=e,this.logger=t.child(this.constructor.name),this.entityType=n,this.defaultBody=r,this.readScope=o}async initialize(){if(await this.load())return;if(await this.load())return;this.logger.info(`No ${this.entityType} found, creating default ${this.entityType}`);try{let e=this.createContent(this.defaultBody);await this.entityService.createEntity({entity:{id:this.entityType,entityType:this.entityType,content:e,metadata:{}}}),await this.load(),this.logger.info(`Default ${this.entityType} created successfully`)}catch(e){this.logger.error(`Failed to create default ${this.entityType}`,{error:e})}}get(){if(this.cache&&!this.cacheParseError)return this.parseBody(this.cache.content);return this.defaultBody}getContent(){if(this.cache)return this.cache.content;return this.createContent(this.defaultBody)}async refreshCache(){await this.load()}async load(){try{let e=await this.entityService.getEntity({entityType:this.entityType,id:this.entityType,visibilityScope:this.readScope});if(this.cache=e,this.cacheParseError=null,e)try{return this.parseBody(e.content),this.logger.debug(`${this.entityType} loaded`),!0}catch(t){return this.cacheParseError=t instanceof Error?t:Error(String(t)),this.logger.error(`Failed to parse ${this.entityType} \u2014 using default. Fix the entity content to clear this error.`,{error:this.cacheParseError.message}),!0}else this.logger.debug(`No ${this.entityType} found in database`)}catch(e){this.logger.warn(`Failed to load ${this.entityType}`,{error:e}),this.cache=null,this.cacheParseError=null}return!1}}function MCe(e,t){let n=e.getAdapter(t.entityType);if(!n.buildStub)return;let r=n.buildStub({id:t.id,title:t.title}),o=new Date().toISOString();return{id:t.id,entityType:t.entityType,content:r.content,metadata:r.metadata,visibility:"public",created:o,updated:o,contentHash:""}}function pM(e,t){let{publishedOnly:n,visibilityScope:r}=t;if(!n&&!r)return e;let o=(s)=>r?{...s,visibilityScope:r}:s,i=(s)=>{let c=o(s?.filter);return{...s,...n&&{publishedOnly:!0},...c&&{filter:c}}};return new Proxy(e,{get(s,c,l){if(c==="listEntities")return(p)=>s.listEntities({entityType:p.entityType,options:i(p.options)});if(c==="countEntities")return(p)=>s.countEntities({entityType:p.entityType,options:i(p.options)});if(c==="getEntity")return(p)=>s.getEntity({...p,visibilityScope:r,...n&&{publishedOnly:!0}});if(c==="search")return(p)=>s.search({...p,options:{...p.options,...r&&{visibilityScope:r},...n&&{publishedOnly:!0}}});if(c==="getEntityCounts")return async(p)=>{let d=r??p;if(!n)return s.getEntityCounts(d);return(await Promise.all(s.getEntityTypes().map(async(f)=>({entityType:f,count:await s.countEntities({entityType:f,options:{publishedOnly:!0,...d&&{filter:{visibilityScope:d}}}})})))).filter(({count:f})=>f>0)};let u=Reflect.get(s,c,l);return typeof u==="function"?u.bind(s):u}})}function S6(e,t){return t==="public"?e:`${e}-${t}`}function bw(e,t,n,r){let o=r.getEntityTypeConfig(e).publish?.publishStatuses;if(!o?.length||typeof n!=="string")return"non-publish";let i=typeof t==="string"&&o.includes(t);if(!o.includes(n))return"non-publish";return i?"within-publish-set":"boundary"}class dM{dataSources=new Map;logger;static createFresh(e){return new dM(e)}constructor(e){this.logger=e.child("DataSourceRegistry")}register(e){let t=e.id.includes(":")?e.id:`shell:${e.id}`;this.registerWithId(t,e)}registerWithId(e,t){if(this.dataSources.has(e)){let n=Error(`DataSource with id "${e}" already exists`);throw this.logger.error("DataSource registration failed",{error:n,id:e}),n}this.dataSources.set(e,t),this.logger.debug("DataSource registered",{id:e,name:t.name})}unregister(e){if(this.dataSources.delete(e))this.logger.debug("DataSource unregistered",{id:e});else this.logger.warn("Attempted to unregister non-existent DataSource",{id:e})}get(e){return this.dataSources.get(e)}has(e){return this.dataSources.has(e)}list(){return Array.from(this.dataSources.values())}getIds(){return Array.from(this.dataSources.keys())}getByCapability(e){return this.list().filter((t)=>{switch(e){case"canFetch":return!!t.fetch;case"canGenerate":return!!(t.generate??t.generateScoped);case"canTransform":return!!t.transform;default:return!1}})}find(e){return this.list().filter(e)}clear(){let e=this.dataSources.size;this.dataSources.clear(),this.logger.debug("DataSource registry cleared",{count:e})}}var v6=a.object({currentPage:a.number(),totalPages:a.number(),totalItems:a.number(),pageSize:a.number(),hasNextPage:a.boolean(),hasPrevPage:a.boolean()});function mM(e,t,n){let r=Math.max(1,Math.ceil(e/n));return{currentPage:t,totalPages:r,totalItems:e,pageSize:n,hasNextPage:t<r,hasPrevPage:t>1}}async function fM(e,t,n,r,o="public",i={}){let s={...i.signal&&{signal:i.signal},...i.publishedOnly&&{publishedOnly:!0}};try{s.signal?.throwIfAborted();let c=await e.getEntity({entityType:t,id:n,visibilityScope:o,...s});if(s.signal?.throwIfAborted(),c)return c;let l=await e.listEntities({entityType:t,options:{limit:1,filter:{metadata:{slug:n},visibilityScope:o},...s}});if(s.signal?.throwIfAborted(),l[0])return l[0];let u=await e.listEntities({entityType:t,options:{limit:1,filter:{metadata:{title:n},visibilityScope:o},...s}});if(s.signal?.throwIfAborted(),u[0])return u[0];let p=await e.listEntities({entityType:t,options:{limit:1,filter:{metadata:{title:Th(n)},visibilityScope:o},...s}});if(s.signal?.throwIfAborted(),p[0])return p[0];let d=await e.listEntities({entityType:t,options:{limit:200,filter:{visibilityScope:o},...s}});s.signal?.throwIfAborted();let g=Th(n);return d.find((f)=>typeof f.metadata.title==="string"&&Th(f.metadata.title)===g)??null}catch(c){if(r)r.error(`Failed to find entity ${t}:${n}`,{error:c});throw c}}async function T6(e,t,n,r,o="Entity",i="public",s={}){let c=await fM(e,t,n,r,i,s);if(!c)return{ok:!1,error:`${o} not found: ${t}/${n}`};return{ok:!0,entity:c}}var gM=a.record(a.string(),a.unknown());var _Ce=a.object({id:a.string(),sessionId:a.string(),interfaceType:a.string(),channelId:a.string(),personId:a.string().optional(),channelName:a.string().optional(),startedAt:a.string(),lastActiveAt:a.string(),createdAt:a.string(),updatedAt:a.string(),metadata:gM}),zCe=a.object({id:a.string(),conversationId:a.string(),role:Tm,content:a.string(),timestamp:a.string(),metadata:gM});var hM=a.object({name:a.string(),role:a.string(),purpose:a.string(),values:a.array(a.string())}),yM=a.object({name:a.string(),organization:a.string().optional(),description:a.string().optional(),avatar:a.string().optional(),website:a.string().optional(),email:a.string().optional(),socialLinks:a.array(a.object({platform:a.enum(["github","instagram","linkedin","email","website"]),url:a.string(),label:a.string().optional()})).optional()});var ey=256,bM=1048576,xM=32;class zs extends Error{constructor(e){super(e);this.name="GenerationLimitError"}}var FCe=`"\\\b\f
116
116
  \r `;function jCe(e){let t=e.codePointAt(0)??0;if(FCe.includes(e))return 1;if(t<32)return 5;if(t>=55296&&t<=57343)return 3;return 0}function C6(e){let t=0;for(let n of e)t+=jCe(n);return Buffer.byteLength(e,"utf8")+2+t}function SM(e){let t=0,n=new WeakSet,r=(i)=>{if(t+=i,t>bM)throw new zs(`Content generation exceeds ${bM} UTF-8 JSON bytes`)},o=(i,s)=>{if(s>xM)throw new zs(`Content generation exceeds JSON depth ${xM}`);if(typeof i==="string"){r(C6(i));return}if(i===null){r(4);return}if(typeof i==="boolean"){r(i?4:5);return}if(typeof i==="number"){r(JSON.stringify(i).length);return}if(typeof i!=="object")return;if(n.has(i))throw new zs("Content generation cannot contain circular data");n.add(i),r(2);let c=0;if(Array.isArray(i))for(let l of i){if(c++>0)r(1);if(l===void 0)r(4);else o(l,s+1)}else for(let l of Object.keys(i)){let u=Reflect.get(i,l);if(u===void 0)continue;if(c++>0)r(1);r(C6(l)+1),o(u,s+1)}n.delete(i)};o(e,0)}function E6(e){if(!Vi(e))return;let t=e.targets;if(Array.isArray(t)&&t.length>ey)throw new zs(`Content generation exceeds ${ey} targets`);SM({targets:t,options:e.options})}var I6="generationLimit";function vM(e){return(t,n)=>{try{e(t)}catch(r){if(!(r instanceof zs))throw r;return n.addIssue({code:"custom",message:r.message,params:{[I6]:!0}}),a.NEVER}return t}}function TM(e){let t=e.issues.find((n)=>n.code==="custom"&&n.params?.[I6]===!0);if(t)throw new zs(t.message);throw e}var NCe=a.object({actor:Fs,permissionLevel:wm}),wM=a.object({actor:Fs,permissionCeiling:wm,principalId:a.string().min(1).optional()}).superRefine((e,t)=>{let{actor:n,principalId:r}=e,o=n.kind==="user"||n.kind==="external";if(o&&!r||!o&&r!==void 0||n.kind==="user"&&n.userId!==r)t.addIssue({code:"custom",message:"Invalid generation account binding"})});class gi extends Error{constructor(){super("Content generation is not permitted");this.name="GenerationAuthorizationError"}}function R6(e,t){return op.hasPermission(e,t)?t:e}function k6(e,t){let n=R6(e.permissionLevel,t.permissionCeiling);return{permissionLevel:n,visibilityScope:ks(n)}}class P6{permissions;resolvePrincipal;constructor(e,t){this.permissions=e,this.resolvePrincipal=t}async current(e){if(e.kind==="service"||e.kind==="agent")return{permissionLevel:this.permissions.determineUserLevel(e.kind,e.kind==="service"?e.serviceId:e.agentId)};let t=await this.resolvePrincipal(e);if(!t||e.kind==="user"&&e.userId!==t.userId)throw new gi;return{permissionLevel:t.permissionLevel,principalId:t.userId}}async admit(e){let{actor:t,permissionLevel:n}=NCe.parse(e),r=await this.current(t),o={actor:t,permissionCeiling:R6(r.permissionLevel,n),...r.principalId&&{principalId:r.principalId}};return{authority:o,access:k6(r,o)}}async resolve(e){let t=await this.current(e.actor);if(t.principalId!==e.principalId)throw new gi;return k6(t,e)}assertTarget(e,t,n,r,o){let i=r?["create","update","publish"]:["create"];if(t&&!this.permissions.hasPermission(e.permissionLevel,t.requiredPermission)||!i.some((s)=>this.permissions.canPerformEntityAction(e.permissionLevel,n,s))||o&&!Kd(e.permissionLevel,o))throw new gi}assertWrite(e,t,n,r){let o=bw(t.entityType,void 0,t.metadata.status,r)!=="non-publish",i=n?o?"publish":"update":"create";if(!Kd(e.permissionLevel,t.visibility)||!this.permissions.canPerformEntityAction(e.permissionLevel,t.entityType,i)||!n&&o&&!this.permissions.canPerformEntityAction(e.permissionLevel,t.entityType,"publish"))throw new gi}}var CM=a.object({prompt:a.string().optional(),conversationHistory:a.string().optional(),data:a.record(a.string(),a.unknown()).optional(),representedIdentity:a.enum(["brain","anchor","none"]).optional(),styleGuide:a.object({voice:a.string().optional(),visual:a.string().optional()}).optional()});var A6=CM.extend({data:ll.optional()}),O6=a.object({entityType:a.string().min(1),idPath:cm,metadata:ll,visibility:Cs.optional()}),xw=a.object({templateName:a.string().min(1),context:A6.default(()=>({})),destination:O6}),D6=a.object({dryRun:a.boolean().optional().default(!1),force:a.boolean().optional().default(!1)}),EM=a.preprocess(vM(E6),a.object({targets:a.array(xw),options:D6.default(()=>({dryRun:!1,force:!1}))})),M6=a.object({entityType:a.string().min(1),entityId:a.string().min(1),metadata:ll,visibility:Cs}),ty=a.preprocess(vM(SM),a.object({authority:wM,templateName:a.string().min(1,"Template name is required"),context:A6,destination:M6,expectedRevision:a.string().min(1).nullable()})),_6=["content-exists","template-not-found","template-cannot-generate"];function ny(e){return`${e.entityType}/${Ua(e.idPath)}`}var LCe=a.strictObject({entityType:a.string().min(1),idPath:cm,entityId:a.string().min(1)}),IM={destination:LCe,template:a.string().min(1)},BCe=a.strictObject({...IM,status:a.literal("planned")}),qCe=a.strictObject({...IM,status:a.literal("queued"),jobId:a.string().min(1)}),ZCe=a.strictObject({...IM,status:a.literal("skipped"),reason:a.enum(_6)}),$Ce=a.discriminatedUnion("status",[BCe,qCe,ZCe]),kM=a.strictObject({items:a.array($Ce).max(ey),totalTargets:a.number().int().nonnegative(),plannedTargets:a.number().int().nonnegative(),queuedTargets:a.number().int().nonnegative(),skippedTargets:a.number().int().nonnegative(),batchId:a.string().min(1).optional()}).superRefine((e,t)=>{let n=e.items.filter((s)=>s.status==="planned"),r=e.items.filter((s)=>s.status==="queued"),o=e.items.filter((s)=>s.status==="skipped"),i=e.items.map((s)=>ny(s.destination));if(e.items.some((s)=>Ua(s.destination.idPath)!==s.destination.entityId)||e.totalTargets!==e.items.length||e.plannedTargets!==n.length+r.length||e.queuedTargets!==r.length||e.skippedTargets!==o.length||r.length>0!==(e.batchId!==void 0)||n.length>0&&r.length>0||new Set(r.map((s)=>s.jobId)).size!==r.length||new Set(i).size!==i.length)t.addIssue({code:"custom",message:"Invalid generation admission counts or references"})});async function RM(e,t,n,r){let o=await e.planGeneration(t,r);r?.throwIfAborted();let s=o.planned.length>0&&!t.options?.dryRun?n.batchId??Pt():void 0,c=s?await Promise.all(o.planned.map(({jobData:u})=>n.enqueue(u,s))):[],l=Array.from({length:o.totalTargets});for(let{index:u,target:p,entityId:d,reason:g}of o.skipped)l[u]={destination:{...p.destination,entityId:d},templateName:p.templateName,status:"skipped",reason:g};return o.planned.forEach(({index:u,target:p,entityId:d},g)=>{let f=c[g],v={destination:{...p.destination,entityId:d},templateName:p.templateName};l[u]=f?{...v,status:"queued",jobId:f}:{...v,status:"planned"}}),{items:l.flatMap((u)=>u?[u]:[]),totalTargets:o.totalTargets,plannedTargets:o.planned.length,queuedTargets:c.length,skippedTargets:o.skipped.length,...s&&{batchId:s}}}function js(e,t){return!t||e.includes(":")?e:`${t}:${e}`}function PM(e,t){let n=`${t}:`;return e.startsWith(n)?e.slice(n.length):e}var AM=(e)=>e!==void 0&&Cm.canGenerate(e);async function OM(e,t,n){n?.throwIfAborted();let r=EM.safeParse({targets:t.targets.map((v)=>({...v,templateName:js(v.templateName,t.pluginId)})),options:t.options});if(!r.success)TM(r.error);let{targets:o,options:i}=r.data,s=new Set,c=o.map((v,T)=>{let E=ny(v.destination);if(s.has(E))throw Error(`Duplicate content generation destination: ${E}`);if(s.add(E),!e.entityService.hasEntityType(v.destination.entityType))throw Error(`Unknown generation destination entity type: ${v.destination.entityType}`);let A=e.templateRegistry.get(v.templateName);if(AM(A)&&!A.formatter)throw Error(`Generation template ${v.templateName} requires a formatter`);return{index:T,target:v,template:A,entityId:Ua(v.destination.idPath)}}),{authority:l,access:u}=await e.authorizer.admit(t.caller);n?.throwIfAborted();for(let{target:v,template:T}of c)e.authorizer.assertTarget(u,T,v.destination.entityType,i.force,v.destination.visibility);let p=new Map(await Promise.all(c.filter(({template:v})=>AM(v)).map(async({index:v,target:T,entityId:E})=>[v,await e.entityService.getEntityWriteSnapshot({entityType:T.destination.entityType,id:E,visibilityScope:u.visibilityScope})])));n?.throwIfAborted();let d=[],g=[];for(let{index:v,target:T,template:E,entityId:A}of c){if(!E){g.push({index:v,target:T,entityId:A,reason:"template-not-found"});continue}if(!AM(E)){g.push({index:v,target:T,entityId:A,reason:"template-cannot-generate"});continue}let L=p.get(v)??null;if(L&&T.destination.visibility!==void 0&&T.destination.visibility!==L.entity.visibility)throw new gi;let j={entityType:T.destination.entityType,entityId:A,metadata:T.destination.metadata,visibility:L?.entity.visibility??T.destination.visibility??"public"};if(L&&!i.force){g.push({index:v,target:T,entityId:A,reason:"content-exists"});continue}e.authorizer.assertWrite(u,j,L!==null,e.entityService);let ie={authority:l,templateName:T.templateName,context:T.context,destination:j,expectedRevision:L?.revision??null},Ee=ty.safeParse(ie);if(!Ee.success)TM(Ee.error);d.push({index:v,target:T,entityId:A,jobData:Ee.data})}let f=await e.authorizer.resolve(l);if(n?.throwIfAborted(),f.permissionLevel!==u.permissionLevel)throw new gi;return{planned:d,skipped:g,totalTargets:o.length}}function z6(e,t,n){let r=Cs.parse(t.visibilityScope);return{visibilityScope:r,...n&&{signal:n},async getEntity(o,i){n?.throwIfAborted();let s=await e.getEntity({entityType:o,id:i,visibilityScope:r,...n&&{signal:n}});return n?.throwIfAborted(),s},async search(o,i){if(n?.throwIfAborted(),o.length>qh)throw new zs(`Content generation search query exceeds ${qh} characters`);let s=await e.search({query:o,options:{...i,visibilityScope:r,...n&&{signal:n}}});return n?.throwIfAborted(),s}}}async function DM(e,t,n){if(n&&(n.id!==t.destination.entityId||n.entityType!==t.destination.entityType||n.visibility!==t.destination.visibility))throw new gi;let{authorizer:r}=e,o=t.expectedRevision!==null,i=await r.resolve(t.authority),s=e.templateRegistry.get(t.templateName);if(!s)throw new gi;return r.assertTarget(i,s,t.destination.entityType,o,t.destination.visibility),r.assertWrite(i,n??t.destination,o,e.entityService),i}class F6{dependencies;constructor(e){this.dependencies=e}async planGeneration(e,t){return OM({...this.dependencies,authorizer:this.dependencies.generationAuthorizer},e,t)}submitGeneration(e,t,n){return RM(this,e,t,n)}authorizeGenerationWrite(e,t){return DM({...this.dependencies,authorizer:this.dependencies.generationAuthorizer},e,t)}toContentTemplate(e){let t={name:e.name,description:e.description,schema:e.schema,requiredPermission:e.requiredPermission};if(e.basePrompt)t.basePrompt=e.basePrompt;if(e.formatter)t.formatter=e.formatter;if(e.dataSourceId)t.dataSourceId=e.dataSourceId;return t}getTemplate(e){let t=this.dependencies.templateRegistry.get(e);if(!t)return null;return this.toContentTemplate(t)}listTemplates(){return this.dependencies.templateRegistry.list().filter((e)=>e.basePrompt??e.formatter).map((e)=>this.toContentTemplate(e))}async resolveContent(e,t,n){let r=js(e,n),o=this.dependencies.templateRegistry.get(r);if(!o)return this.dependencies.logger.debug(`Template not found: ${r}`),null;let i=pM(this.dependencies.entityService,{publishedOnly:t?.publishedOnly,visibilityScope:t?.visibilityScope});if(o.dataSourceId&&Cm.canFetch(o)){let s=this.dependencies.dataSourceRegistry.get(o.dataSourceId);if(s)try{if(s.fetch){let c={...t?.publishedOnly!==void 0&&{publishedOnly:t.publishedOnly},entityService:i},l=await s.fetch(t?.dataParams,o.schema,c);if(l!==void 0){if(this.dependencies.logger.debug(`Resolved content via DataSource fetch for ${r}`),o.overlayFormatter&&t?.savedContent)return await this.applyContentOverlay(r,o,l,t.savedContent,i);return l}}}catch(c){this.dependencies.logger.debug(`DataSource operation failed for ${r}`,{error:c})}}if(t?.savedContent)if(!o.formatter)this.dependencies.logger.debug(`Template ${r} has no formatter; skipping saved content`);else try{let s=await i.getEntity({entityType:t.savedContent.entityType,id:t.savedContent.entityId});if(s?.content)return this.dependencies.logger.debug(`Resolved content from saved entity for ${r}`),this.parseContent(r,s.content)}catch(s){this.dependencies.logger.debug(`No saved content found for ${r}: ${t.savedContent.entityType}/${t.savedContent.entityId}`,{error:s})}if(t?.fallback!==void 0)try{let s=o.schema.parse(t.fallback);return this.dependencies.logger.debug(`Using fallback content for ${r}`),s}catch(s){this.dependencies.logger.debug(`Fallback content validation failed for ${r}`,{error:s})}return this.dependencies.logger.debug(`No content could be resolved for ${r}`),null}async applyContentOverlay(e,t,n,r,o){try{let i=await o.getEntity({entityType:r.entityType,id:r.entityId});if(!i?.content)return n;let s=t.overlayFormatter?.parse(i.content);if(s===void 0||s===null)return n;if(!Vi(n)||!Vi(s))return n;let c={...n,...s},l=t.schema.parse(c);return this.dependencies.logger.debug(`Applied authored content overlay for ${e}`),l}catch(i){return this.dependencies.logger.debug(`Content overlay skipped for ${e}, using datasource base`,{error:i}),n}}async generateContent(e,t={},n={}){let{pluginId:r,signal:o,visibilityScope:i}=n;o?.throwIfAborted();let s=js(e,r),c=this.getTemplate(s);if(!c)throw Error(`Template not found: ${s}`);if(!c.dataSourceId)throw Error(`Template ${s} doesn't support content generation. Add dataSourceId to enable generation through DataSource pattern.`);let l=this.dependencies.dataSourceRegistry.get(c.dataSourceId);if(!l)throw Error(`DataSource ${c.dataSourceId} not found`);let u={...t,templateName:s};if(i){if(!l.generateScoped)throw Error(`DataSource ${c.dataSourceId} does not support visibility-scoped generation`);let d=await l.generateScoped(u,c.schema,z6(this.dependencies.entityService,{visibilityScope:i},o));return o?.throwIfAborted(),d}if(!l.generate)throw Error(`Template ${s} uses DataSource ${c.dataSourceId} which doesn't support content generation. This template is for data fetching only.`);let p=await l.generate(u,c.schema,o);return o?.throwIfAborted(),p}parseContent(e,t,n){let r=js(e,n),o=this.getTemplate(r);if(!o)throw Error(`Template not found: ${r}`);if(!o.formatter)throw Error(`Template ${r} does not have a formatter for parsing`);return o.formatter.parse(t)}formatContent(e,t,n){let r=js(e,n?.pluginId),o=this.getTemplate(r);if(!o)throw Error(`Template not found: ${r}`);if(!o.formatter)throw Error(`Template ${r} does not have a formatter`);let i=o.formatter.format(t);if(n?.truncate&&i.length>n.truncate)i=i.substring(0,n.truncate)+"...";return i}}var UCe=a.object({name:a.string(),description:a.string(),schema:a.unknown(),basePrompt:a.string().optional(),requiredPermission:a.enum(["admin","trusted","public"]),formatter:a.unknown().optional(),dataSourceId:a.string().optional(),layout:a.object({component:a.unknown(),description:a.string().optional(),packageName:a.string().optional()}).optional()});class MM{logger;contentService;entityService;static createFresh(e,t){return new MM(e,t)}constructor(e,t){this.logger=di.getInstance().child("ContentGenerationJobHandler"),this.contentService=e,this.entityService=t}async process(e,t,n,r){try{r?.throwIfAborted();let{destination:o}=e;await this.contentService.authorizeGenerationWrite(e),r?.throwIfAborted();let i=await this.entityService.getEntityWriteSnapshot({entityType:o.entityType,id:o.entityId,visibilityScope:o.visibility});if(r?.throwIfAborted(),(i?.revision??null)!==e.expectedRevision||i&&i.entity.visibility!==o.visibility)throw new Ms(o.entityType,o.entityId);let s=this.contentService.getTemplate(e.templateName);if(!s?.dataSourceId||!s.formatter)throw Error(`Generation template is unavailable or incomplete: ${e.templateName}`);await n.report({progress:0,total:3,message:`Generating content with template: ${e.templateName}`}),r?.throwIfAborted();let c=await this.contentService.generateContent(e.templateName,e.context,{...r&&{signal:r},visibilityScope:o.visibility});r?.throwIfAborted(),await n.report({progress:1,total:3,message:`Formatting content for template: ${e.templateName}`}),r?.throwIfAborted();let l;try{l=this.contentService.formatContent(e.templateName,c)}catch(p){throw Error(Ke(p,"Content formatting failed"),{cause:p})}r?.throwIfAborted();let u={beforeWrite:async(p)=>{r?.throwIfAborted(),await this.contentService.authorizeGenerationWrite(e,p)},...r&&{signal:r},conditionalWrite:{expectedRevision:e.expectedRevision}};if(i)await this.entityService.updateEntity({entity:{...i.entity,content:l,metadata:o.metadata},options:u});else await this.entityService.createEntity({entity:{id:o.entityId,entityType:o.entityType,content:l,metadata:o.metadata,visibility:o.visibility},options:u});try{await n.report({progress:3,total:3,message:`Completed content generation for: ${e.templateName}`})}catch(p){this.logger.warn("Completion report failed after commit",{jobId:t,error:p})}return{entityType:o.entityType,entityId:o.entityId}}catch(o){throw r?.throwIfAborted(),this.logger.error("Content generation job failed",{jobId:t,templateName:e.templateName,error:o}),o}}validateAndParse(e){let t=ty.safeParse(e);if(!t.success)return this.logger.warn("Invalid content generation job data",{validationError:t.error.issues}),null;return t.data}}var WCe=a.record(a.string(),a.unknown());function _M(e,t){let n=WCe.safeParse(e);return n.success&&t.every((r)=>(r in n.data))}class Em{parse(e){throw Error("This response format is read-only and cannot be parsed back to data")}formatKeyValue(e,t){if(t===void 0||t===null)return"";return`**${e}:** ${String(t)}`}formatList(e){return e.map((t)=>`- ${String(t)}`).join(`
117
117
  `)}formatTable(e,t){let n=`| ${e.join(" | ")} |`,r=`| ${e.map(()=>"---").join(" | ")} |`,o=t.map((i)=>`| ${i.map((s)=>String(s??"")).join(" | ")} |`).join(`
118
118
  `);return`${n}
@@ -163,7 +163,7 @@ Instructions:
163
163
  2. Search through available entities for relevant information
164
164
  3. Provide accurate, contextual responses based on the data
165
165
  4. If information is missing, clearly state what additional data might be helpful
166
- 5. Structure your response clearly and concisely`,dataSourceId:"shell:ai-content",requiredPermission:"public",useKnowledgeContext:!0,schema:vw,formatter:new iy};var pEe=a.object({type:a.string().describe("Type of source (e.g., note, article)"),title:a.string().describe("Title or identifier of the source"),relevance:a.number().min(0).max(1).describe("Relevance score")}),R5=a.object({answer:a.string().describe("The answer to the user's query"),sources:a.array(pEe).optional().describe("Sources used to generate the answer"),confidence:a.enum(["high","medium","low"]).optional().describe("Confidence level of the answer"),suggestions:a.array(a.string()).optional().describe("Related topics or follow-up questions")});function Va(e,t){return e.parse(t)}class Qa{callback;heartbeatInterval;constructor(e){this.callback=e}static from(e){if(!e)return;return new Qa(e)}static noop(){return new Qa(async()=>{})}createSub(e){let{scale:t}=e??{};if(t){let{start:n,end:r}=t,o=r-n;return new Qa(async(i)=>{let s=n+i.progress/(i.total??100)*o;await this.callback({...i,progress:s,total:100})})}return new Qa(this.callback)}async report(e){await this.callback(e)}startHeartbeat(e,t=5000){this.stopHeartbeat(),this.heartbeatInterval=setInterval(()=>{this.report({message:e,progress:0}).catch(()=>{})},t)}stopHeartbeat(){if(this.heartbeatInterval)clearInterval(this.heartbeatInterval),this.heartbeatInterval=void 0}toCallback(){return this.callback}}var mEe=a.object({enabled:a.boolean().describe("Whether the plugin is enabled"),debug:a.boolean().describe("Enable debug logging for this plugin")});function fEe(e,t){return t.reduce((n,r)=>typeof n==="object"&&n!==null?Reflect.get(n,r):void 0,e)}function gEe(e){return e.map((t)=>`${t.path||"<root>"}: ${t.message}`).join("; ")}class km extends Error{pluginId;issues;constructor(e,t){super(`Invalid plugin config for ${e} at ${gEe(t)}; correct the listed fields in brain.yaml or the package's use() configuration`);this.name="PluginConfigValidationError",this.pluginId=e,this.issues=t}static fromZod(e,t,n){return new km(e,t.issues.map((r)=>({path:r.path.map(String).join("."),code:r.code,message:r.message,missing:r.code==="custom"&&r.params?.missing===!0||(r.code==="invalid_type"||r.code==="custom")&&fEe(n,r.path)===void 0})))}}var hEe=a.object({toolName:a.string(),args:a.unknown(),progressToken:a.union([a.string(),a.number()]).optional(),hasProgress:a.boolean().optional(),interfaceType:a.string(),actor:Fs,displayName:a.string().optional(),conversationId:a.string().optional(),channelId:a.string().optional(),channelName:a.string().optional(),runId:a.string().optional(),toolCallId:a.string().optional(),userPermissionLevel:a.enum(["admin","trusted","public"]).optional(),isAnchor:a.boolean().optional(),signal:a.custom((e)=>e instanceof AbortSignal).optional()}),yEe=a.object({resourceUri:a.string()});class ip{id;version;description;packageName;config;context;get logger(){return this.context?.logger??di.createFresh({context:this.id})}constructor(e,t,n,r){this.id=e,this.packageName=t.name,this.version=t.version,this.description=t.description??`${t.name} plugin`;let o=r.safeParse(n);if(!o.success)throw km.fromZod(e,o.error,n);this.config=o.data}setupMessageHandlers(e){e.messaging.subscribe(sy.toolExecute(this.id),async(t)=>{try{let n=hEe.safeParse(t.payload);if(!n.success)return{success:!1,error:"Invalid tool execution request format"};let{toolName:r,args:o,progressToken:i,hasProgress:s,interfaceType:c,actor:l,displayName:u,conversationId:p,channelId:d,channelName:g,runId:f,toolCallId:v,userPermissionLevel:T,isAnchor:E,signal:A}=n.data,j=(await this.getTools()).find((D)=>D.name===r);if(!j)return{success:!1,error:`Tool not found: ${r}`};let ie={interfaceType:c,actor:l,...u&&{displayName:u},...p&&{conversationId:p},...d&&{channelId:d},...g&&{channelName:g},...f&&{runId:f},...v&&{toolCallId:v},...T&&{userPermissionLevel:T},...E!==void 0&&{isAnchor:E},...A&&{signal:A},...s&&i!==void 0&&{progressToken:i,sendProgress:async(D)=>{await e.messaging.send({type:sy.progress(this.id),payload:{progressToken:i,notification:D}})}}};return{success:!0,data:await j.handler(o,ie)}}catch(n){return this.logger.error("Tool execution error",n),{success:!1,error:Ke(n)}}}),e.messaging.subscribe(sy.resourceGet(this.id),async(t)=>{try{let n=yEe.safeParse(t.payload);if(!n.success)return{success:!1,error:"Invalid resource get request format"};let{resourceUri:r}=n.data,i=(await this.getResources()).find((c)=>c.uri===r);if(!i)return{success:!1,error:`Resource not found: ${r}`};return{success:!0,data:await i.handler()}}catch(n){return this.logger.error("Resource fetch error",n),{success:!1,error:Ke(n)}}})}async onRegister(e){}async onRegistrationComplete(e){}async finalizeRegistration(){await this.onRegistrationComplete(this.getContext())}async onReady(e){}async ready(){await this.onReady(this.getContext())}async getCapabilities(){let e=await this.getInstructions();return{tools:await this.getTools(),resources:await this.getResources(),...e&&{instructions:e}}}async getTools(){return[]}async getResources(){return[]}async getInstructions(){return}async shutdown(){await this.onShutdown()}async onShutdown(){}getContext(){if(!this.context)throw Error(`Plugin ${this.id}: Plugin not registered yet`);return this.context}determineUserPermissionLevel(e){return"public"}createProgressBridge(e){if(!e)return;let t=this.context;if(!t)return;let n=this.id;return Qa.from(async(r)=>{await t.messaging.send({type:sy.progress(n),payload:{progressToken:e,notification:{progress:r.progress,total:r.total,message:r.message}}})})}}var P5=a.object({id:a.string(),template:a.string(),content:a.unknown().optional(),dataQuery:a.looseObject({entityType:a.string().optional(),template:a.string().optional(),query:a.looseObject({id:a.string().optional(),limit:a.number().optional(),offset:a.number().optional()}).optional()}).optional(),order:a.number().optional()}),o_=["primary","secondary"],A5=a.object({show:a.boolean().default(!1),label:a.string().optional(),slot:a.enum(o_).default("primary"),priority:a.number().min(0).max(100).default(50)}).optional(),i_=a.object({id:a.string(),path:a.string(),title:a.string().default(""),pageLabel:a.string().optional(),description:a.string().default(""),sections:a.array(P5).default([]),layout:a.string().default("default"),fullscreen:a.boolean().optional(),pluginId:a.string().optional(),sourceEntityType:a.string().optional(),external:a.boolean().optional(),navigation:A5}),O5=a.object({routes:a.array(i_),pluginId:a.string()}),D5=a.object({paths:a.array(a.string()).optional(),pluginId:a.string().optional()}),M5=a.object({pluginId:a.string().optional()}),_5=a.object({path:a.string()}),Tw=a.object({label:a.string(),href:a.string(),priority:a.number()});var bEe="site:metadata:get",xEe="site:metadata:updated",s_=a.object({heading:a.string().describe("Main CTA heading text"),buttonText:a.string().describe("Call-to-action button text"),buttonLink:a.string().describe("URL or anchor for the CTA button")}),z5=a.object({blurb:a.string().optional().describe("Short italic subtitle under the section title")}),ww=a.object({represents:a.enum(["brain","anchor"]).default("anchor").describe("Identity represented by the site"),title:a.string().describe("The site's title"),description:a.string().describe("The site's description"),url:a.string().optional().describe("Canonical site URL"),copyright:a.string().optional().describe("Copyright notice text"),logo:a.boolean().optional().describe("Whether to display logo instead of title text in header"),themeMode:a.enum(["light","dark"]).optional().describe("Default theme mode"),analyticsScript:a.string().optional().describe("Analytics script HTML"),cta:s_.optional().describe("Call-to-action configuration"),sections:a.record(a.string(),z5).optional().describe("Optional per-section blurbs, keyed by section id (e.g. 'essays', 'presentations', 'about'). Used by homepage templates that render editorial section headers.")});var SEe=a.object({platform:a.enum(["github","instagram","linkedin","email","website"]).describe("Social media platform"),url:a.string().describe("Profile or contact URL"),label:a.string().optional().describe("Optional display label")}),vEe=ww.extend({copyright:a.string(),navigation:a.object({primary:a.array(Tw),secondary:a.array(Tw)}),socialLinks:a.array(SEe).optional().describe("Social media links from profile metadata")});function ay(e,t){return t?e.nullable().default(null):e}function c_(e){switch(e.type){case"string":return ay(a.string(),e.optional);case"number":return ay(a.number(),e.optional);case"enum":return ay(a.enum(e.options),e.optional);case"object":{let t={};for(let[n,r]of Object.entries(e.fields))t[n]=c_(r);return ay(a.object(t),e.optional)}case"array":{let t=a.array(TEe(e));if(e.minItems!==void 0)t=t.min(e.minItems);if(e.length!==void 0)t=t.length(e.length);return ay(t,e.optional)}}}function TEe(e){let{items:t}=e;switch(t.type){case"string":return a.string();case"number":return a.number();case"enum":return a.enum(t.options);case"object":{let n={};for(let[r,o]of Object.entries(t.fields))n[r]=c_(o);return a.object(n)}}}function a_(e,t){switch(t.type){case"string":case"enum":return{key:e,label:t.label,type:"string"};case"number":return{key:e,label:t.label,type:"number"};case"object":return{key:e,label:t.label,type:"object",children:Object.entries(t.fields).map(([n,r])=>a_(n,r))};case"array":{let n={key:e,label:t.label,type:"array"};switch(t.items.type){case"string":case"enum":return n.itemType="string",n;case"number":return n.itemType="number",n;case"object":return n.itemType="object",n.itemMappings=Object.entries(t.items.fields).map(([r,o])=>a_(r,o)),n}}}}function F5(e,t){let n={};for(let[i,s]of Object.entries(t.fields))n[i]=c_(s);let r=a.object(n),o=new Im(r,{title:t.title,mappings:Object.entries(t.fields).map(([i,s])=>a_(i,s))});return{name:e,description:t.description,schema:r,formatter:o,requiredPermission:t.requiredPermission??"public",layout:{component:t.layout,...t.fullscreen!==void 0?{fullscreen:t.fullscreen}:{}},...t.runtimeScripts?{runtimeScripts:t.runtimeScripts}:{}}}function wEe(e){let t={};for(let[n,r]of Object.entries(e.sections))t[n]=F5(n,r);return t}var CEe=ww.omit({url:!0,analyticsScript:!0}),j5=CEe.extend({title:a.string().optional().describe("Optional site title override"),description:a.string().optional().describe("Optional site description override")});function N5(e){return j5.parse(vm(e).frontmatter)}async function EEe(e){let n=(await e.listEntities({entityType:"site-info",options:{limit:1}}))[0];if(!n)throw Error("Site info not found \u2014 create a site-info entity");return N5(n.content)}function l_(e,t={}){let n=L5(e),r=L5(t.sharedDomain??"rizom.ai").replace(/^\./,""),o=`.${r}`;if(n.endsWith(o)){let i=n.slice(0,-o.length);if(i.length>0&&!i.includes("."))return`${i}-preview.${r}`}return`preview.${n}`}function L5(e){return e.trim().replace(/^https?:\/\//i,"").replace(/\/$/,"").toLowerCase()}class Rm{static instance=null;entityDisplay;constructor(){}static getInstance(){return Rm.instance??=new Rm,Rm.instance}configure(e){this.entityDisplay=e}static resetInstance(){Rm.instance=null}hasRoute(e){return this.entityDisplay?.[e]!==void 0}isCitable(e){if(!Object.values(this.entityDisplay??{}).some((n)=>n.citable===!0))return this.hasRoute(e);return this.entityDisplay?.[e]?.citable===!0}generateUrl(e,t){let n=this.entityDisplay?.[e];if(n)return`/${n.pluralName??n.label.toLowerCase()+"s"}/${t}`;return`/${UA(e)}/${t}`}}var q5=["primary","secondary"];var IEe=a.custom((e)=>typeof e==="function","Expected a React component"),kEe=a.strictObject({show:a.boolean().optional(),label:a.string().min(1).optional(),slot:a.enum(q5).optional(),priority:a.number().optional()}),REe=a.strictObject({id:a.string().min(1),template:a.string().min(1),content:a.unknown().optional(),dataQuery:a.looseObject({entityType:a.string().optional(),template:a.string().optional(),query:a.record(a.string(),a.unknown()).optional()}).optional(),order:a.number().optional()}),PEe=a.strictObject({id:a.string().min(1),path:a.string().startsWith("/"),title:a.string().optional(),pageLabel:a.string().optional(),description:a.string().optional(),sections:a.array(REe).optional(),layout:a.string().min(1).optional(),fullscreen:a.boolean().optional(),pluginId:a.string().optional(),sourceEntityType:a.string().optional(),external:a.boolean().optional(),navigation:kEe.optional()}),AEe=a.strictObject({label:a.string().min(1),pluralName:a.string().min(1).optional(),layout:a.string().min(1).optional(),paginate:a.boolean().optional(),pageSize:a.number().int().positive().optional(),citable:a.boolean().optional(),navigation:a.strictObject({show:a.boolean().optional(),slot:a.enum(q5).optional(),priority:a.number().optional()}).optional()}),OEe=a.strictObject({schema:a.custom((e)=>e instanceof a.ZodType,"Expected a Zod schema"),component:a.custom((e)=>typeof e==="function","Expected a React component"),title:a.string().min(1),description:a.string(),requiredPermission:a.enum(["admin","trusted","public"]).optional(),fullscreen:a.boolean().optional()}),B5=a.strictObject({namespace:a.string().min(1),sections:a.record(a.string(),OEe)}),DEe=a.record(a.string(),a.json()),MEe=a.record(a.string(),a.record(a.string(),DEe)),Z5={layouts:a.record(a.string(),IEe).refine((e)=>typeof e.default==="function",{message:'Site layouts must include a "default" component'}),routes:a.array(PEe),content:MEe.optional(),sections:a.union([B5,a.array(B5)]).optional(),themeOverride:a.string().optional(),headScripts:a.array(a.string()).optional(),entityDisplay:a.record(a.string(),AEe),staticAssets:a.record(a.string(),a.string()).optional()},Xet=a.strictObject(Z5).partial();var $5=a.strictObject(Z5).superRefine((e,t)=>{let n=new Set;for(let[i,s]of e.routes.entries()){if(n.has(s.id))t.addIssue({code:"custom",path:["routes",i,"id"],message:`Duplicate route id "${s.id}"`});n.add(s.id);let c=s.layout??"default";if(!e.layouts[c])t.addIssue({code:"custom",path:["routes",i,"layout"],message:`Unknown layout "${c}"`})}let r=Array.isArray(e.sections)?e.sections:e.sections?[e.sections]:[],o=new Map(r.map((i)=>[i.namespace,i]));if(o.size!==r.length)t.addIssue({code:"custom",path:["sections"],message:"Section group namespaces must be unique"});for(let[i,s]of Object.entries(e.content??{})){let c=o.get(i);if(!c){t.addIssue({code:"custom",path:["content",i],message:`Content namespace "${i}" has no section group`});continue}for(let[l,u]of Object.entries(s)){let p=c.sections[l];if(!p){t.addIssue({code:"custom",path:["content",i,l],message:`Content section "${i}.${l}" is not defined`});continue}let d=p.schema.safeParse(u);if(!d.success)t.addIssue({code:"custom",path:["content",i,l],message:`Content does not satisfy the "${i}.${l}" schema: ${a.prettifyError(d.error)}`})}}});var _Ee=a.string(),zEe=a.custom((e)=>{if(!pi(e))return!1;let{plugin:t,...n}=e;if(t!==void 0&&typeof t!=="function")return!1;return $5.safeParse(n).success});var u_=a.enum(["file_operations","content_operations","data_processing","batch_processing"]),FEe=a.looseObject({pluginId:a.string().optional(),progressToken:a.union([a.string(),a.number()]).optional(),operationType:u_,operationTarget:a.string().optional(),interfaceType:a.string().optional(),conversationId:a.string().optional(),channelId:a.string().optional(),requestedByActor:Fs.optional(),requestedByUserId:a.string().optional(),requestedByInterface:a.string().optional(),silent:a.boolean().optional(),provenance:Ns.optional()}),sp=a.looseObject({pluginId:a.string().optional(),progressToken:a.union([a.string(),a.number()]).optional(),operationType:u_,operationTarget:a.string().optional(),interfaceType:a.string().optional(),conversationId:a.string().optional(),channelId:a.string().optional(),requestedByActor:Fs.optional(),requestedByUserId:a.string().optional(),requestedByInterface:a.string().optional(),silent:a.boolean().optional(),provenance:Ns.optional(),rootJobId:a.string()}),Stt=a.enum(["none","skip","replace","coalesce"]);var jEe=a.object({id:a.string(),type:a.string(),data:a.string(),status:a.enum(["pending","processing","completed","failed"]),source:a.string().nullable(),priority:a.number(),retryCount:a.number(),maxRetries:a.number(),lastError:a.string().nullable(),createdAt:a.number(),scheduledFor:a.number(),startedAt:a.number().nullable(),completedAt:a.number().nullable(),attemptId:a.string().nullable(),workerSlotId:a.string().nullable(),workerSessionId:a.string().nullable(),leaseExpiresAt:a.number().nullable(),attemptHeartbeatAt:a.number().nullable(),runtimeUpdatedAt:a.number().nullable(),metadata:sp,progress:a.custom((e)=>typeof e==="object"&&e!==null&&("progress"in e)&&typeof e.progress==="number").nullable(),result:a.unknown().nullable().optional()}),Ka=15000;var p_=a.enum(["pending","processing","completed","failed"]),U5=a.enum(["completed","failed"]),je={PENDING:"pending",PROCESSING:"processing",COMPLETED:"completed",FAILED:"failed"},NEe=a.object({id:a.string(),type:a.string(),status:p_,data:a.unknown(),result:a.unknown().optional(),lastError:a.string().optional().nullable(),attempts:a.number(),maxRetries:a.number(),priority:a.number(),createdAt:a.date(),updatedAt:a.date(),processedAt:a.date().optional().nullable(),completedAt:a.date().optional().nullable(),failedAt:a.date().optional().nullable()}),LEe=a.object({jobId:a.string(),type:a.string(),status:U5,result:a.unknown().optional(),error:a.string().optional()}),d_=a.object({success:a.literal(!1),error:a.string().optional()}),Cw=a.object({id:a.string(),type:a.enum(["job","batch"]),status:p_,message:a.string().optional(),progress:a.object({current:a.number(),total:a.number(),percentage:a.number()}).optional(),aggregationKey:a.string().optional(),batchDetails:a.object({totalOperations:a.number(),completedOperations:a.number(),failedOperations:a.number(),currentOperation:a.string().optional(),errors:a.array(a.string()).optional()}).optional(),jobDetails:a.object({jobType:a.string(),priority:a.number(),retryCount:a.number()}).optional(),metadata:sp});var G=Nt("job_queue",{id:le("id").primaryKey().$defaultFn(()=>Pt()),type:le("type").notNull(),data:le("data").notNull(),result:le("result",{mode:"json"}),progress:le("progress",{mode:"json"}).$type(),source:le("source"),metadata:le("metadata",{mode:"json"}).$type().notNull(),status:le("status",{enum:["pending","processing","completed","failed"]}).notNull().default("pending"),priority:qe("priority").notNull().default(0),retryCount:qe("retryCount").notNull().default(0),maxRetries:qe("maxRetries").notNull().default(3),lastError:le("lastError"),createdAt:qe("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:qe("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:qe("startedAt"),completedAt:qe("completedAt"),attemptId:le("attemptId"),workerSlotId:le("workerSlotId"),workerSessionId:le("workerSessionId"),leaseExpiresAt:qe("leaseExpiresAt"),attemptHeartbeatAt:qe("attemptHeartbeatAt"),runtimeUpdatedAt:qe("runtimeUpdatedAt")},(e)=>({queueReadyIdx:zt("idx_job_queue_ready").on(e.status,e.priority,e.scheduledFor),jobTypeIdx:zt("idx_job_queue_type").on(e.type,e.status),runtimeUpdatesIdx:zt("idx_job_queue_runtime_updates").on(e.runtimeUpdatedAt,e.id),jobSourceIdx:zt("idx_job_queue_source").on(e.source)})),Ut=Nt("job_worker_sessions",{slotId:le("slotId").primaryKey(),sessionId:le("sessionId").notNull().unique(),startedAt:qe("startedAt").notNull(),heartbeatAt:qe("heartbeatAt").notNull(),expiresAt:qe("expiresAt").notNull().default(0)},(e)=>({heartbeatIdx:zt("idx_job_worker_sessions_heartbeat").on(e.heartbeatAt),expiresIdx:zt("idx_job_worker_sessions_expires").on(e.expiresAt)}));function W5(e){return Ui({url:e.url,schema:{jobQueue:G,jobWorkerSessions:Ut},authToken:e.authToken,authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN"})}class m_{declarations=new Map;handlers=new Map;validators=new Map;logger;mode;finalizedRegistrations;constructor(e,t){this.logger=e.child("HandlerRegistry"),this.mode=t}registerHandler(e,t,n){if(this.finalizedRegistrations)throw Error("Job handler registrations are finalized");if(this.declarations.has(e))throw Error(`Job handler is already registered for type: ${e}`);if(this.declarations.set(e,{handler:t,pluginId:n}),this.validators.set(e,t),this.mode!=="validation-only")this.handlers.set(e,t);this.logger.debug("Registered job execution declaration",{type:e,pluginId:n,mode:this.mode})}unregisterHandler(e){this.declarations.delete(e),this.handlers.delete(e),this.validators.delete(e),this.logger.debug("Unregistered job handler",{type:e})}unregisterPluginHandlers(e){let t=[...this.declarations.entries()].filter(([,n])=>n.pluginId===e).map(([n])=>n);for(let n of t)this.declarations.delete(n),this.handlers.delete(n),this.validators.delete(n);if(t.length>0)this.logger.debug("Unregistered plugin handlers",{pluginId:e,count:t.length,types:t})}finalizeRegistrations(){return this.finalizedRegistrations??=Object.freeze([...this.declarations.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>Object.freeze({type:e,pluginId:t.pluginId}))),this.finalizedRegistrations}getExecutionRegistrations(){if(!this.finalizedRegistrations)throw Error("Job handler registrations are not finalized");return this.finalizedRegistrations}getRegisteredTypes(){return[...this.handlers.keys()]}getHandler(e){return this.handlers.get(e)}getValidator(e){return this.validators.get(e)}}var BEe=a.looseObject({deduplicationKey:a.string().optional()});class f_{findDuplicate(e,t,n){if(!t||t==="none")return null;let r=this.filterByDeduplicationKey(e,n).sort((i,s)=>s.createdAt-i.createdAt||s.id.localeCompare(i.id)),o=r.find((i)=>i.status===je.PENDING)??null;if(t==="skip"||t==="replace")return o;return o??r[0]??null}filterByDeduplicationKey(e,t){if(!t)return e;return e.filter((n)=>{let r=BEe.safeParse(n.metadata);return r.success&&r.data.deduplicationKey===t})}}var qEe=2000,ZEe=5,$Ee=40,UEe=new aD;class g_{db;transactionClient;databaseUrl;logger;deduplicator=new f_;writeRetryBudgetMs;constructor(e,t,n,r,o){this.db=e,this.transactionClient=t,this.databaseUrl=n,this.logger=r.child("JobQueueRepository"),this.writeRetryBudgetMs=o?.writeRetryBudgetMs??qEe}async insert(e){await this.write("insert",async()=>this.db.insert(G).values(e))}async enqueueAtomic(e){return UEe.run(this.databaseUrl,async()=>{let t=Date.now()+this.writeRetryBudgetMs;return this.attemptEnqueue(e,t,1)})}async attemptEnqueue(e,t,n){let r=await this.runEnqueueTransaction(e,t,n);if(r.retry)return this.attemptEnqueue(e,t,n+1);return r.decision}async runEnqueueTransaction(e,t,n){let r=await this.acquireWriteTransaction(e,t),o={prepared:!1},i=!1;try{let s=await this.decideEnqueue(r,e,()=>{o.prepared=!0});return i=!0,await r.commit(),{retry:!1,decision:s}}catch(s){let c=i&&this.isSerializationConflict(s)&&!r.closed,l=!0;if(!r.closed)try{await r.rollback()}catch(u){l=!1,this.logger.error("Failed to roll back atomic enqueue",{type:e.jobData.type,rollbackError:u})}if(o.prepared)e.onInsertRollback?.();if(!c||!l)throw s;return await this.waitForConflictRetry("commit",e,t,n,s),{retry:!0}}finally{r.close()}}async decideEnqueue(e,t,n){let{jobData:r,strategy:o,deduplicationKey:i,beforeInsert:s}=t,c=o??"none",l=async()=>{await s?.(),n()},u=async()=>{await l(),await this.insertJob(e,r)};if(c==="none")return await u(),{kind:"inserted",jobId:r.id};let p=await this.getActiveDeduplicationCandidates(e,r.type),d=this.deduplicator.findDuplicate(p,c,i);if(!d)return await u(),{kind:"inserted",jobId:r.id};if(c==="skip")return{kind:"skipped",jobId:d.id};if(c==="coalesce"){if((await e.execute({sql:"UPDATE `job_queue` SET `scheduledFor` = ? WHERE `id` = ? AND `status` = ?",args:[Date.now(),d.id,d.status]})).rowsAffected!==1)throw Error(`Atomic coalesce lost selected job ${d.id}`);return{kind:"coalesced",jobId:d.id}}await l();let g=Date.now();if((await e.execute({sql:"UPDATE `job_queue`\n SET `status` = ?,\n `lastError` = ?,\n `completedAt` = ?,\n `runtimeUpdatedAt` = max(?, coalesce((SELECT max(`runtimeUpdatedAt`) FROM `job_queue`), 0) + 1)\n WHERE `id` = ? AND `status` = ?",args:[je.FAILED,"Replaced by newer job",g,g,d.id,je.PENDING]})).rowsAffected!==1)throw Error(`Atomic replace lost selected job ${d.id}`);return await this.insertJob(e,r),{kind:"replaced",jobId:r.id,replacedJobId:d.id}}async getActiveDeduplicationCandidates(e,t){return(await e.execute({sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ? AND `status` IN (?, ?)",args:[t,je.PENDING,je.PROCESSING]})).rows.map((r)=>this.parseDeduplicationCandidate(r))}parseDeduplicationCandidate(e){let{id:t,status:n,createdAt:r,metadata:o}=e;if(typeof t!=="string"||n!==je.PENDING&&n!==je.PROCESSING||typeof r!=="number"&&typeof r!=="bigint"||typeof o!=="string")throw Error("Invalid active job row returned during atomic enqueue");let i=JSON.parse(o);return{id:t,status:n,createdAt:Number(r),metadata:i}}async insertJob(e,t){if((await e.execute({sql:"INSERT INTO `job_queue` (\n `id`, `type`, `data`, `result`, `source`, `metadata`,\n `status`, `priority`, `retryCount`, `maxRetries`,\n `lastError`, `createdAt`, `scheduledFor`, `startedAt`,\n `completedAt`\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",args:[t.id,t.type,t.data,this.serializeJson(t.result),t.source,JSON.stringify(t.metadata),t.status,t.priority,t.retryCount,t.maxRetries,t.lastError,t.createdAt,t.scheduledFor,t.startedAt,t.completedAt]})).rowsAffected!==1)throw Error(`Atomic enqueue did not insert job ${t.id}`)}serializeJson(e){if(e===void 0||e===null)return null;return JSON.stringify(e)}acquireWriteTransaction(e,t){return this.retryOnConflict("acquire",e,()=>this.transactionClient.transaction("write"),(n)=>this.isSerializationConflict(n),t)}async waitForConflictRetry(e,t,n,r,o){let i=Math.min(ZEe*2**(r-1),$Ee),s=i/2+Math.random()*(i/2);if(Date.now()+s>=n)throw this.transactionConflictError(e,t,r,o);await new Promise((c)=>setTimeout(c,s))}async retryOnConflict(e,t,n,r,o=Date.now()+this.writeRetryBudgetMs,i=1){try{return await n()}catch(s){if(!r(s))throw s;return await this.waitForConflictRetry(e,t,o,i,s),this.retryOnConflict(e,t,n,r,o,i+1)}}transactionConflictError(e,t,n,r){if(typeof t==="string")return Error(`Failed job queue write "${t}" within ${this.writeRetryBudgetMs}ms after ${n} attempts`,{cause:r});let o=t.strategy??"none",i=t.deduplicationKey?"present":"absent";return Error(`Failed to ${e} atomic enqueue transaction for type "${t.jobData.type}" within ${this.writeRetryBudgetMs}ms after ${n} attempts (strategy: ${o}, key: ${i})`,{cause:r})}write(e,t){return this.retryOnConflict("write",e,t,(n)=>{let r=new Set;for(let o=n;o!==void 0&&!r.has(o);){if(r.add(o),typeof o==="object"&&o!==null&&"code"in o&&/^SQLITE_(?:BUSY|LOCKED)(?:_|$)/u.test(String(o.code)))return!0;o=o instanceof Error?o.cause:void 0}return!1})}isSerializationConflict(e){for(let t=e;t!==void 0;){let n=typeof t==="object"&&t!==null&&"code"in t?String(t.code):"",r=Ke(t,"");if(/SQLITE_(?:BUSY|LOCKED)/u.test(n)||/SQLITE_(?:BUSY|LOCKED)|database is locked|transaction (?:busy|conflict)/iu.test(r))return!0;t=t instanceof Error?t.cause:void 0}return!1}async startWorkerSession(e,t,n=Date.now(),r=Ka){let o=n+r;await this.write("start worker session",async()=>this.db.insert(Ut).values({slotId:e,sessionId:t,startedAt:n,heartbeatAt:n,expiresAt:o}).onConflictDoUpdate({target:Ut.slotId,set:{sessionId:t,startedAt:n,heartbeatAt:n,expiresAt:o}}))}async heartbeatWorkerSession(e,t,n=Date.now(),r=Ka){return(await this.write("heartbeat worker session",async()=>this.db.update(Ut).set({heartbeatAt:n,expiresAt:n+r}).where(oe(O(Ut.slotId,e),O(Ut.sessionId,t))).returning({slotId:Ut.slotId}))).length===1}async endWorkerSession(e,t){return(await this.write("end worker session",async()=>this.db.delete(Ut).where(oe(O(Ut.slotId,e),O(Ut.sessionId,t))).returning({slotId:Ut.slotId}))).length===1}async complete(e,t,n){let r=Date.now(),i=(await this.write("complete",async()=>this.db.update(G).set({status:je.COMPLETED,result:t,lastError:null,completedAt:r,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(r)}).where(this.attemptWriteGuard(e,n)).returning({id:G.id}))).length===1;if(i)this.logger.debug("Job completed",{jobId:e,hasResult:t!==void 0});return i}async update(e,t,n){let o=(await this.write("update",async()=>this.db.update(G).set({data:JSON.stringify(t)}).where(this.attemptWriteGuard(e,n)).returning({id:G.id}))).length===1;if(o)this.logger.debug("Job data updated",{jobId:e});return o}async recordAttemptProgress(e,t,n,r=Date.now()){return(await this.write("record progress",async()=>this.db.update(G).set({attemptHeartbeatAt:r,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(r),progress:n}).where(this.attemptWriteGuard(e,t)).returning({id:G.id}))).length===1}async renewAttemptLease(e,t,n,r){return(await this.write("renew attempt lease",async()=>this.db.update(G).set({attemptHeartbeatAt:n,leaseExpiresAt:n+r}).where(this.attemptWriteGuard(e,t)).returning({id:G.id}))).length===1}async fail(e,t,n,r=Date.now()){let i=(await this.db.select({retryCount:G.retryCount,maxRetries:G.maxRetries,type:G.type,scheduledFor:G.scheduledFor,startedAt:G.startedAt,runtimeUpdatedAt:G.runtimeUpdatedAt}).from(G).where(this.attemptWriteGuard(e,n)).limit(1))[0];if(!i)return!1;let s=i.retryCount<i.maxRetries,c=s?i.retryCount+1:i.retryCount,l=Math.min(1000*2**i.retryCount,60000),u=s?r+l:i.scheduledFor;if((await this.write("fail",async()=>this.db.update(G).set({status:s?je.PENDING:je.FAILED,retryCount:c,lastError:t.message,scheduledFor:u,completedAt:s?null:r,runtimeUpdatedAt:s?i.runtimeUpdatedAt:this.nextRuntimeUpdatedAt(r),startedAt:s?null:i.startedAt,attemptId:null,workerSlotId:null,workerSessionId:null,leaseExpiresAt:null,attemptHeartbeatAt:null}).where(oe(this.attemptWriteGuard(e,n),O(G.retryCount,i.retryCount))).returning({id:G.id}))).length!==1)return!1;if(s)this.logger.debug("Job scheduled for retry",{jobId:e,retryCount:c,backoffMs:l,scheduledFor:new Date(u).toISOString()});else this.logger.error("Job failed after max retries",{jobId:e,type:i.type,retryCount:i.retryCount,error:t.message});return!0}async retireUnownedActiveJob(e){let t=e.reason.trim();if(t.length===0)throw Error("Retired job reason must not be empty");let r=(await this.write("retire unowned job",async()=>this.db.update(G).set({status:je.FAILED,lastError:t,completedAt:e.now,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(e.now)}).where(oe(O(G.id,e.jobId),O(G.type,e.expectedType),fr(O(G.status,je.PENDING),O(G.status,je.PROCESSING)),rr(G.attemptId),rr(G.workerSlotId),rr(G.workerSessionId),rr(G.leaseExpiresAt),rr(G.attemptHeartbeatAt),rr(G.progress),rr(G.result))).returning()))[0]??null;if(r)this.logger.warn("Retired unowned legacy job",{jobId:r.id,type:r.type,reason:t});return r}async getStatus(e){return(await this.db.select().from(G).where(O(G.id,e)).limit(1))[0]??null}async getJobsByRootJobId(e){return this.db.select().from(G).where(x`json_extract(${G.metadata}, '$.rootJobId') = ${e}`).orderBy(st(G.createdAt),st(G.id))}async getStatusByEntityId(e){return(await this.db.select().from(G).where(x`json_extract(${G.data}, '$.id') = ${e}`).orderBy(dn(G.createdAt)).limit(1))[0]??null}async getStats(){let e=await this.db.select({status:G.status,count:x`count(*)`}).from(G).groupBy(G.status),t={pending:0,processing:0,failed:0,completed:0,total:0};for(let n of e){let r=Number(n.count);t[n.status]=r,t.total+=r}return t}async getDiagnostics(e=Date.now()){let[t,n,r]=await Promise.all([this.db.select({type:G.type,status:G.status,count:x`count(*)`}).from(G).groupBy(G.type,G.status),this.db.select({oldestPendingAt:x`min(case when ${G.status} = ${je.PENDING} then ${G.createdAt} end)`,duePending:x`coalesce(sum(case when ${G.status} = ${je.PENDING} and ${G.scheduledFor} <= ${e} then 1 else 0 end), 0)`,oldestDuePendingAt:x`min(case when ${G.status} = ${je.PENDING} and ${G.scheduledFor} <= ${e} then ${G.scheduledFor} end)`,latestClaimAt:x`max(${G.startedAt})`,oldestProcessingAt:x`min(case when ${G.status} = ${je.PROCESSING} then ${G.startedAt} end)`,staleLeaseCount:x`coalesce(sum(case when ${G.status} = ${je.PROCESSING} and ${G.leaseExpiresAt} is not null and ${G.leaseExpiresAt} <= ${e} then 1 else 0 end), 0)`}).from(G),this.db.select({total:x`count(*)`,active:x`coalesce(sum(case when ${Ut.expiresAt} > ${e} then 1 else 0 end), 0)`,stale:x`coalesce(sum(case when ${Ut.expiresAt} <= ${e} then 1 else 0 end), 0)`,latestHeartbeatAt:x`max(${Ut.heartbeatAt})`}).from(Ut)]),o={pending:0,processing:0,completed:0,failed:0},i=t.map((u)=>{let p=Number(u.count);return o[u.status]+=p,{type:u.type,status:u.status,count:p}}),s=n[0],c=r[0],l=(u)=>u===null||u===void 0?null:Math.max(0,e-Number(u));return{totals:o,byType:i,oldestPendingAgeMs:l(s?.oldestPendingAt),duePending:Number(s?.duePending??0),oldestDuePendingAgeMs:l(s?.oldestDuePendingAt),latestClaimAgeMs:l(s?.latestClaimAt),oldestProcessingAgeMs:l(s?.oldestProcessingAt),staleLeaseCount:Number(s?.staleLeaseCount??0),workerSessions:{total:Number(c?.total??0),active:Number(c?.active??0),stale:Number(c?.stale??0),latestHeartbeatAgeMs:l(c?.latestHeartbeatAt)}}}async getRuntimeUpdates(e,t){return(await this.db.select().from(G).where(x`(${G.runtimeUpdatedAt}, ${G.id}) > (${e.updatedAt}, ${e.jobId})`).orderBy(st(G.runtimeUpdatedAt),st(G.id)).limit(t)).map((r)=>({job:r,cursor:{updatedAt:r.runtimeUpdatedAt??0,jobId:r.id}}))}async cleanup(e){let t=Date.now()-e;return(await this.write("cleanup",async()=>this.db.delete(G).where(oe(fr(O(G.status,je.COMPLETED),O(G.status,je.FAILED)),Hr(G.completedAt,t))))).rowsAffected}async getActiveJobs(e){let t=fr(O(G.status,je.PENDING),O(G.status,je.PROCESSING)),n=e&&e.length>0?oe(t,It(G.type,e)):t;return this.db.select().from(G).where(n).orderBy(dn(G.createdAt))}async getRecentJobs(e,t=20){let n=e&&e.length>0?It(G.type,e):void 0;return this.db.select().from(G).where(n).orderBy(dn(G.createdAt)).limit(t)}async getFailedJobs(e){let t=O(G.status,je.FAILED),n=e&&e.length>0?oe(t,It(G.type,e)):t;return this.db.select().from(G).where(n).orderBy(dn(G.createdAt))}async claimNextReady(e){let{now:t,attemptId:n,workerSlotId:r,workerSessionId:o,leaseDurationMs:i,executableTypes:s}=e,c=this.db.select({slotId:Ut.slotId}).from(Ut).where(oe(O(Ut.slotId,r),O(Ut.sessionId,o),qa(Ut.expiresAt,t))),l=this.db.select({slotId:Ut.slotId}).from(Ut).where(oe(O(Ut.slotId,G.workerSlotId),O(Ut.sessionId,G.workerSessionId))),u=oe(O(G.status,je.PROCESSING),fr(rr(G.attemptId),iT(l),Hr(G.leaseExpiresAt,t))),p=x`${G.status} = ${je.PROCESSING} AND ${G.retryCount} + 1 > ${G.maxRetries}`,d=this.db.select({id:G.id}).from(G).where(oe(It(G.type,s),fr(oe(O(G.status,je.PENDING),Hr(G.scheduledFor,t)),u))).orderBy(st(G.priority),st(G.createdAt)).limit(1),f=(await this.write("claim",async()=>this.db.update(G).set({status:x`CASE WHEN ${p} THEN ${je.FAILED} ELSE ${je.PROCESSING} END`,retryCount:x`CASE WHEN ${G.status} = ${je.PROCESSING} THEN ${G.retryCount} + 1 ELSE ${G.retryCount} END`,lastError:x`CASE WHEN ${G.status} = ${je.PROCESSING} THEN 'Attempt lease expired' ELSE ${G.lastError} END`,startedAt:x`CASE WHEN ${p} THEN ${G.startedAt} ELSE ${t} END`,completedAt:x`CASE WHEN ${p} THEN ${t} ELSE NULL END`,attemptId:x`CASE WHEN ${p} THEN ${G.attemptId} ELSE ${n} END`,workerSlotId:x`CASE WHEN ${p} THEN ${G.workerSlotId} ELSE ${r} END`,workerSessionId:x`CASE WHEN ${p} THEN ${G.workerSessionId} ELSE ${o} END`,leaseExpiresAt:x`CASE WHEN ${p} THEN ${G.leaseExpiresAt} ELSE ${t+i} END`,attemptHeartbeatAt:x`CASE WHEN ${p} THEN ${G.attemptHeartbeatAt} ELSE ${t} END`,runtimeUpdatedAt:x`CASE WHEN ${p} THEN ${this.nextRuntimeUpdatedAt(t)} ELSE ${G.runtimeUpdatedAt} END`}).where(oe(It(G.id,d),Zu(c))).returning()))[0];if(f?.status!==je.PROCESSING)return null;return this.logger.debug("Job claimed",{jobId:f.id,attemptId:f.attemptId,workerSlotId:r,workerSessionId:o}),f}nextRuntimeUpdatedAt(e){return x`max(${e}, coalesce((select max(${G.runtimeUpdatedAt}) from ${G}), 0) + 1)`}attemptWriteGuard(e,t){return t?oe(O(G.id,e),O(G.status,je.PROCESSING),O(G.attemptId,t)):oe(O(G.id,e),rr(G.attemptId),fr(O(G.status,je.PENDING),O(G.status,je.PROCESSING)))}}import{AsyncLocalStorage as WEe}from"async_hooks";class xl{storage=new WEe;static createFresh(){return new xl}constructor(){}current(){return this.storage.getStore()}run(e,t,n){if(t.length===0)throw Error("Operation ID must not be empty");let r=Ns.parse(e),o=HEe(r);return this.storage.run(Object.freeze({provenance:o,operationId:t}),n)}}function HEe(e){if(Object.freeze(e.projectionLineage),e.sourceEntity)Object.freeze(e.sourceEntity);return Object.freeze(e)}class h_{client;logger;handlerRegistry;repository;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;inFlightEnqueues=0;databaseUrl;operationContext;projectionAdmission;directWorkerSlotId=`direct:${Pt()}`;directWorkerSessionId=Pt();directLeaseDurationMs;directSessionStart=null;close(){this.closeRequested=!0,this.closeClientWhenReady()}static createFresh(e,t,n){return new h_(e,t??di.getInstance(),n)}constructor(e,t,n){let{db:r,client:o,url:i}=W5(e);this.client=o,this.databaseUrl=i,this.logger=t.child("JobQueueService"),this.operationContext=n?.operationContext??xl.createFresh(),this.projectionAdmission=n?.projectionAdmission,this.handlerRegistry=new m_(this.logger,n?.handlerRegistrationMode??"combined"),this.repository=new g_(r,o,i,this.logger),this.directLeaseDurationMs=e.claimTimeoutMs??300000}initialize(){if(this.closeRequested)return Promise.resolve();return this.walInitialization??=this.initializeWALMode(),this.walInitialization}async initializeWALMode(){try{await Wi(this.client,this.databaseUrl)}catch(e){this.logger.warn("Failed to enable WAL mode (non-fatal)",e)}finally{this.walInitializationSettled=!0,this.closeClientWhenReady()}}closeClientWhenReady(){if(!this.closeRequested||this.inFlightEnqueues>0||this.walInitialization!==null&&!this.walInitializationSettled)return;this.closeClient()}closeClient(){if(this.clientClosed)return;this.clientClosed=!0,this.client.close()}registerHandler(e,t,n){this.handlerRegistry.registerHandler(e,t,n)}unregisterHandler(e){this.handlerRegistry.unregisterHandler(e)}unregisterPluginHandlers(e){this.handlerRegistry.unregisterPluginHandlers(e)}getRegisteredTypes(){return this.handlerRegistry.getRegisteredTypes()}getHandler(e){return this.handlerRegistry.getHandler(e)}getValidator(e){return this.handlerRegistry.getValidator(e)}finalizeHandlerRegistrations(){return this.handlerRegistry.finalizeRegistrations()}getExecutionRegistrations(){return this.handlerRegistry.getExecutionRegistrations()}async enqueue(e){if(this.closeRequested)throw Error("Cannot enqueue a job after the queue service is closed");this.inFlightEnqueues++;try{return await this.enqueueValidated(e)}finally{this.inFlightEnqueues--,this.closeClientWhenReady()}}async enqueueValidated(e){let{type:t,data:n,options:r}=e,o=this.handlerRegistry.getValidator(t);if(!o)throw Error(`No job type declared: ${t}`);let i=o.validateAndParse(n);if(i===null)throw Error(`Invalid job data for type: ${t}`);let s=Date.now(),c=Pt(),l=r?.rootJobId??this.operationContext.current()?.provenance.rootJobId??c,u=this.createJobProvenance(c,l,r),p=r?.metadata??{operationType:"data_processing"},{provenance:d,...g}=p,f={id:c,type:t,data:JSON.stringify(i),status:je.PENDING,priority:r?.priority??0,maxRetries:r?.maxRetries??3,retryCount:0,source:r?.source??null,metadata:{...g,...r?.deduplicationKey&&{deduplicationKey:r.deduplicationKey},rootJobId:l,provenance:u},createdAt:s,scheduledFor:r?.delayMs?s+r.delayMs:s,result:null,lastError:null,startedAt:null,completedAt:null},v,T=()=>{v?.rollback(),v=void 0};try{let E=await this.repository.enqueueAtomic({jobData:f,strategy:r?.deduplication,deduplicationKey:r?.deduplicationKey,beforeInsert:async()=>{v=await this.projectionAdmission?.reserveJobAdmission(u)},onInsertRollback:T});if(v?.commit(),v=void 0,E.kind==="skipped")this.logger.debug("Skipping duplicate job (already pending)",{type:t,existingJobId:E.jobId});else if(E.kind==="coalesced")this.logger.debug("Coalescing with existing job",{type:t,existingJobId:E.jobId});else{if(E.kind==="replaced")this.logger.debug("Replacing duplicate job",{type:t,oldJobId:E.replacedJobId});this.logger.debug("Job enqueued",{id:E.jobId,type:t,priority:f.priority,rootJobId:f.metadata.rootJobId})}return E.jobId}catch(E){throw T(),this.logger.error("Failed to enqueue job",{type:t,error:Ke(E)}),E}}createJobProvenance(e,t,n){let r=this.operationContext.current(),o=n?.metadata.provenance??r?.provenance,i=o?.rootJobId===t?o:void 0,s=r?.provenance.rootJobId===t?r.operationId:void 0,c=n?.projection,l=c?[...i?.projectionLineage??[],c.id]:[...i?.projectionLineage??[]],u=c?.id??i?.projectionId;return Ns.parse({rootJobId:t,causationId:s??i?.causationId??e,...u?{projectionId:u}:{},projectionLineage:l,...c?.sourceEntity?{sourceEntity:c.sourceEntity}:i?.sourceEntity?{sourceEntity:i.sourceEntity}:{},derivationDepth:l.length})}async dequeue(e){let t=this.handlerRegistry.getRegisteredTypes();if(t.length===0)return null;let n=e??await this.getDirectClaimOptions(),r=Date.now(),o=await this.repository.claimNextReady({...n,now:r,attemptId:Pt(),executableTypes:t});if(!o)return null;return this.logger.debug("Job dequeued",{id:o.id,type:o.type,priority:o.priority,retryCount:o.retryCount,attemptId:o.attemptId,workerSlotId:o.workerSlotId,workerSessionId:o.workerSessionId}),o}async startWorkerSession(e,t,n=Ka){await this.repository.startWorkerSession(e,t,Date.now(),n)}heartbeatWorkerSession(e,t,n=Ka){return this.repository.heartbeatWorkerSession(e,t,Date.now(),n)}endWorkerSession(e,t){return this.repository.endWorkerSession(e,t)}renewAttemptLease(e,t,n){return this.repository.renewAttemptLease(e,t,Date.now(),n)}recordAttemptProgress(e,t,n){return this.repository.recordAttemptProgress(e,t,n)}complete(e,t,n){return this.repository.complete(e,t,n)}update(e,t,n){return this.repository.update(e,t,n)}fail(e,t,n){return this.repository.fail(e,t,n)}retireUnownedActiveJob(e){return this.repository.retireUnownedActiveJob(e)}async getDirectClaimOptions(){return this.directSessionStart??=this.repository.startWorkerSession(this.directWorkerSlotId,this.directWorkerSessionId,Date.now(),this.directLeaseDurationMs),await this.directSessionStart,{workerSlotId:this.directWorkerSlotId,workerSessionId:this.directWorkerSessionId,leaseDurationMs:this.directLeaseDurationMs}}async getStatus(e){return this.repository.getStatus(e)}async getJobsByRootJobId(e){return this.repository.getJobsByRootJobId(e)}async getStatusByEntityId(e){return this.repository.getStatusByEntityId(e)}async getStats(){return this.repository.getStats()}getDiagnostics(e){return this.repository.getDiagnostics(e)}async waitForIdle(e={}){let t=e.quietMs??250,n=e.pollIntervalMs??25,r=Date.now()+(e.timeoutMs??30000),o=async(i)=>{e.signal?.throwIfAborted();let{totals:s}=await this.getDiagnostics(),l=s.pending===0&&s.processing===0?i??Date.now():null;if(l!==null&&Date.now()-l>=t)return;if(Date.now()>=r)throw Error(`Timed out waiting for the job queue to settle: ${s.pending} pending, ${s.processing} processing`);return await Bun.sleep(n),o(l)};return o(null)}getRuntimeUpdates(e,t=1000){return this.repository.getRuntimeUpdates(e,t)}async cleanup(e){let t=await this.repository.cleanup(e);if(t>0)this.logger.info("Cleaned up old jobs",{deletedCount:t,olderThanMs:e});return t}async getActiveJobs(e){return this.repository.getActiveJobs(e)}async getRecentJobs(e,t){return this.repository.getRecentJobs(e,t)}async getFailedJobs(e){return this.repository.getFailedJobs(e)}}class H5 extends Error{constructor(e,t){super(`Job ${e} exceeded its ${t}ms execution deadline`);this.name="JobDeadlineExceededError"}}class y_{logger;jobQueueService;progressMonitor;config;isRunning=!1;shouldStop=!1;activeJobs=new Set;stats;startTime=0;pollFiber=null;currentPoll=null;workerScope=null;jobFibers=null;activeTransition=null;transitionQueue=[];clock;operationContext;projectionBatchScope;workerSessionId=null;workerHeartbeatStop=null;static createFresh(e,t,n,r,o){return new y_(e,t,n,r,o)}constructor(e,t,n,r,o){if(this.logger=n.child("JobQueueWorker"),this.jobQueueService=e,this.progressMonitor=t,this.clock=o?.clock,this.operationContext=o?.operationContext??xl.createFresh(),this.projectionBatchScope=o?.projectionBatchScope,this.config={concurrency:r?.concurrency??1,pollInterval:r?.pollInterval??1000,maxJobs:r?.maxJobs??0,autoStart:r?.autoStart??!1,workerSlotId:r?.workerSlotId??process.env.BRAIN_JOB_WORKER_SLOT_ID??"default",defaultExecutionTimeoutMs:r?.defaultExecutionTimeoutMs??300000,cancellationGraceMs:r?.cancellationGraceMs??5000,errorCallbackTimeoutMs:r?.errorCallbackTimeoutMs??1e4,leaseDurationMs:r?.leaseDurationMs??30000,attemptHeartbeatIntervalMs:r?.attemptHeartbeatIntervalMs??1e4,workerHeartbeatIntervalMs:r?.workerHeartbeatIntervalMs??5000,workerSessionTimeoutMs:r?.workerSessionTimeoutMs??Ka,onUnhealthy:r?.onUnhealthy??(()=>{return})},this.stats={processedJobs:0,failedJobs:0,activeJobs:0,uptime:0,isRunning:!1,isHealthy:!0},this.logger.debug("JobQueueWorker initialized",{concurrency:this.config.concurrency,pollInterval:this.config.pollInterval,maxJobs:this.config.maxJobs,autoStart:this.config.autoStart}),this.config.autoStart)this.start().catch((i)=>{this.logger.error("Failed to auto-start JobQueueWorker",{error:i})})}start(){return this.requestTransition("start",!0)}async startWorker(){if(this.isRunning){this.logger.warn("Worker is already running");return}this.logger.debug("Starting JobQueueWorker");let e=Pt();await this.jobQueueService.startWorkerSession(this.config.workerSlotId,e,this.config.workerSessionTimeoutMs),this.workerSessionId=e,this.isRunning=!0,this.shouldStop=!1,this.startTime=Date.now(),this.stats.isRunning=!0,this.stats.isHealthy=!0,delete this.stats.unhealthyReason,this.startWorkerHeartbeat(),this.workerScope=de.runSync(Xt.make()),this.jobFibers=de.runSync(Xt.extend(Ur.make(),this.workerScope)),this.pollFiber=de.runFork(this.runPollingLoop())}stop(){return this.requestTransition("stop",!0)}async stopWorker(e){if(!this.isRunning){this.logger.warn("Worker is not running");return}if(this.logger.debug("Stopping JobQueueWorker"),this.shouldStop=!0,e.awaitInFlightPoll&&this.pollFiber){let n=this.pollFiber;await de.runPromise(ii.interrupt(n)),this.pollFiber=null}if(e.awaitInFlightPoll&&this.currentPoll)await this.currentPoll,this.currentPoll=null;if(this.jobFibers)this.logger.debug("Waiting for active jobs to complete",{activeJobs:this.activeJobs.size}),await de.runPromise(Ur.awaitEmpty(this.jobFibers));await this.closeWorkerScope(),await this.stopWorkerHeartbeat();let t=this.workerSessionId;if(this.workerSessionId=null,t)await this.jobQueueService.endWorkerSession(this.config.workerSlotId,t);this.isRunning=!1,this.stats.isRunning=!1,this.logger.debug("JobQueueWorker stopped")}getStats(){return{...this.stats,activeJobs:this.activeJobs.size,uptime:this.isRunning?Date.now()-this.startTime:0}}isWorkerRunning(){return this.isRunning}isStopRequested(){return this.shouldStop}async processAvailableJobs(){if(!this.isRunning||this.shouldStop)return;try{let e=this.config.concurrency-this.activeJobs.size;if(e<=0)return;if(this.config.maxJobs>0){let n=this.stats.processedJobs+this.stats.failedJobs,r=this.config.maxJobs-n-this.activeJobs.size;if(r<=0){this.logger.debug("Maximum job limit reached, stopping worker",{maxJobs:this.config.maxJobs,processedJobs:this.stats.processedJobs,failedJobs:this.stats.failedJobs}),await this.requestTransition("stop",!1);return}e=Math.min(e,r)}let t=this.jobFibers;if(!t)throw Error("Worker job fiber scope is not available");for(let n=0;n<e;n++){if(this.isStopRequested())break;let r=this.workerSessionId;if(!r)throw Error("Worker session is not available");let o=await this.jobQueueService.dequeue({workerSlotId:this.config.workerSlotId,workerSessionId:r,leaseDurationMs:this.config.leaseDurationMs});if(!o)break;this.activeJobs.add(o.id),await de.runPromise(Ur.run(t,o.id,de.promise(()=>this.processJobWrapper(o))))}}catch(e){this.logger.error("Error processing available jobs",{error:e}),this.stats.lastError=Ke(e)}}async processJobWrapper(e){let t=e.id;try{this.logger.debug("Processing job",{jobId:t,type:e.type,priority:e.priority,retryCount:e.retryCount});let n=await this.processJob(e);if(n.status==="completed")this.stats.processedJobs++,this.logger.debug("Job completed successfully",{jobId:t,type:n.type});else this.stats.failedJobs++,this.logger.warn("Job failed",{jobId:t,type:n.type,error:n.error})}catch(n){this.stats.failedJobs++,this.logger.error("Error processing job",{jobId:t,type:e.type,error:n}),this.stats.lastError=Ke(n)}finally{this.activeJobs.delete(t)}}runPollingLoop(){let t=de.suspend(()=>{if(!this.isWorkerRunning()||this.isStopRequested())return de.interrupt;return this.currentPoll=this.processAvailableJobs(),de.promise(()=>this.currentPoll??Promise.resolve()).pipe(de.andThen(de.suspend(()=>(this.currentPoll=null,!this.isWorkerRunning()||this.isStopRequested()?de.interrupt:de.void))))}).pipe(de.schedule(ws.spaced(this.config.pollInterval)),de.asVoid);return(this.clock?de.withClock(t,this.clock):t).pipe(de.ensuring(de.sync(()=>{this.pollFiber=null})))}requestTransition(e,t){let n=this.transitionQueue.at(-1)??this.activeTransition;if(n?.kind===e)return n.promise;let r=()=>{return},o=()=>{return},i=new Promise((c,l)=>{r=c,o=l}),s={kind:e,awaitInFlightPoll:t,promise:i,resolve:r,reject:o};return this.transitionQueue.push(s),this.runNextTransition(),i}runNextTransition(){if(this.activeTransition)return;let e=this.transitionQueue.shift();if(!e)return;this.activeTransition=e,(e.kind==="start"?this.startWorker():this.stopWorker({awaitInFlightPoll:e.awaitInFlightPoll})).then(()=>this.completeTransition(e,!0),(n)=>this.completeTransition(e,!1,n))}completeTransition(e,t,n){if(this.activeTransition!==e)return;if(this.activeTransition=null,t)e.resolve();else e.reject(n);queueMicrotask(()=>this.runNextTransition())}async closeWorkerScope(){let e=this.workerScope;if(this.workerScope=null,this.jobFibers=null,e)await de.runPromise(Xt.close(e,jt.void))}startHeartbeatLoop(e){let t=null,n=!1,r=setInterval(()=>{if(n||t)return;t=e.beat().then((o)=>{if(!o)e.onStale()}).catch(e.onError).finally(()=>{t=null})},Math.max(1,e.intervalMs));return async()=>{if(n)return;n=!0,clearInterval(r),await t}}startWorkerHeartbeat(){this.workerHeartbeatStop=this.startHeartbeatLoop({intervalMs:this.config.workerHeartbeatIntervalMs,beat:async()=>{let e=this.workerSessionId;if(!e)return!0;return this.jobQueueService.heartbeatWorkerSession(this.config.workerSlotId,e,this.config.workerSessionTimeoutMs)},onStale:()=>this.markUnhealthy("Worker session was superseded"),onError:(e)=>this.markUnhealthy(`Worker session heartbeat failed: ${Ke(e)}`)})}async stopWorkerHeartbeat(){await this.workerHeartbeatStop?.(),this.workerHeartbeatStop=null}startAttemptHeartbeat(e,t){let n=e.attemptId;if(!n)return async()=>{return};return this.startHeartbeatLoop({intervalMs:this.config.attemptHeartbeatIntervalMs,beat:()=>this.jobQueueService.renewAttemptLease(e.id,n,this.config.leaseDurationMs),onStale:()=>{let r=Error("Job attempt was superseded");t.abort(r),this.markUnhealthy(r.message)},onError:(r)=>{let o=Pm(r);t.abort(o),this.markUnhealthy(`Attempt lease heartbeat failed: ${o.message}`)}})}markUnhealthy(e){if(!this.stats.isHealthy)return;this.stats.isHealthy=!1,this.stats.unhealthyReason=e,this.stats.lastError=e,this.shouldStop=!0,this.logger.error("Job queue worker is unhealthy",{reason:e});try{this.config.onUnhealthy(e)}catch(t){this.logger.error("Job queue worker unhealthy callback failed",{reason:e,error:Ke(t)})}}async raceOutcome(e,t){let n,r=new Promise((o)=>{n=setTimeout(()=>o({kind:"timeout"}),Math.max(1,t))});try{return await Promise.race([e,r])}finally{if(n)clearTimeout(n)}}async executeWithDeadline(e,t,n,r){let o=Promise.resolve().then(r).then((l)=>({kind:"success",value:l}),(l)=>({kind:"failure",error:l})),i=await this.raceOutcome(o,t);if(i.kind!=="timeout"){if(i.kind==="failure")throw i.error;return i.value}let s=new H5(e,t);if(n.abort(s),(await this.raceOutcome(o,this.config.cancellationGraceMs)).kind!=="timeout")throw s;throw this.markUnhealthy(`${s.message}; handler ignored cancellation grace`),await o,s}processJob(e){let t=e.metadata.provenance??{rootJobId:e.metadata.rootJobId,causationId:e.id,projectionLineage:[],derivationDepth:0};return this.operationContext.run(t,e.id,()=>{let n=this.projectionBatchScope;return n?n.runFreshBatchScope(()=>this.processJobWithinContext(e)):this.processJobWithinContext(e)})}async processJobWithinContext(e){let t=e.attemptId;if(!t){let c=Error(`Claimed job ${e.id} has no attempt fencing token`);return this.markUnhealthy(c.message),{jobId:e.id,type:e.type,status:je.FAILED,error:c.message}}let n=this.jobQueueService.getHandler(e.type);if(!n){let c=Error(`No handler registered for job type: ${e.type}`);return await this.jobQueueService.fail(e.id,c,t),{jobId:e.id,type:e.type,status:je.FAILED,error:c.message}}let r=new AbortController,o=this.startAttemptHeartbeat(e,r),i=!1,s=async()=>{if(i)return;i=!0,await o()};try{this.logger.debug("Processing job",{jobId:e.id,type:e.type,attemptId:t});let c=JSON.parse(e.data),l=n.validateAndParse(c);if(l===null)throw Error(`Invalid job data for type: ${e.type}`);let u=this.progressMonitor.createProgressReporter(e.id,t),p=n.executionTimeoutMs??this.config.defaultExecutionTimeoutMs,d=await this.executeWithDeadline(e.type,p,r,()=>n.process(l,e.id,u,r.signal));await s();let g=d_.safeParse(d);if(g.success){let v=g.data.error??"Handler returned failure",T=Error(v);if(await this.jobQueueService.fail(e.id,T,t))await this.emitTerminalFailure(e,T,n,t);return{jobId:e.id,type:e.type,status:je.FAILED,error:v}}if(!await this.jobQueueService.complete(e.id,d,t))return{jobId:e.id,type:e.type,status:je.FAILED,error:"Job attempt no longer owns the claim"};return await this.runHandlerSuccessCallback(n,e,t),await this.progressMonitor.handleJobStatusChange(e.id,"completed",e.metadata),{jobId:e.id,type:e.type,status:je.COMPLETED,result:d}}catch(c){let l=Pm(c);if(await s(),await this.runHandlerErrorCallback("onError",n,e,l,t),await this.jobQueueService.fail(e.id,l,t))await this.emitTerminalFailure(e,l,n,t);return{jobId:e.id,type:e.type,status:je.FAILED,error:l.message}}}async runHandlerSuccessCallback(e,t,n){let r=e.onTerminalSuccess;if(!r)return;try{let o=e.validateAndParse(JSON.parse(t.data));if(o===null)return;let i=this.progressMonitor.createProgressReporter(t.id,n),s=new AbortController;await this.executeWithDeadline(`${t.type}:onTerminalSuccess`,this.config.errorCallbackTimeoutMs,s,()=>r.call(e,o,t.id,i,s.signal))}catch(o){this.logger.error("Terminal job success callback failed",{jobId:t.id,type:t.type,error:o})}}async emitTerminalFailure(e,t,n,r){if((await this.jobQueueService.getStatus(e.id))?.status!==je.FAILED)return;await this.runHandlerErrorCallback("onTerminalError",n,e,t,r),await this.progressMonitor.handleJobStatusChange(e.id,"failed",e.metadata)}async runHandlerErrorCallback(e,t,n,r,o){let i=t[e];if(!i)return;try{let s=t.validateAndParse(JSON.parse(n.data));if(s===null)return;let c=this.progressMonitor.createProgressReporter(n.id,o),l=new AbortController;await this.executeWithDeadline(`${n.type}:${e}`,this.config.errorCallbackTimeoutMs,l,()=>i.call(t,r,s,n.id,c,l.signal))}catch(s){this.logger.error(e==="onError"?"Job handler error callback failed":"Job handler terminal error callback failed",{jobId:n.id,error:s})}}}var JEe=86400000,J5=3600000;class b_{jobQueue;logger;batches=new Map;cleanupFiber=null;cleanupSupervisor=null;inFlightCleanups=new Set;activeTransition=null;transitionQueue=[];acceptingCleanup=!0;clock;static createFresh(e,t,n){return new b_(e,t,n)}constructor(e,t,n){this.jobQueue=e,this.logger=t,this.clock=n?.clock}start(e=J5){return this.requestTransition("start",e)}stop(){return this.requestTransition("stop",J5)}async startCleanup(e){if(this.acceptingCleanup=!0,this.cleanupFiber)return;this.cleanupFiber=de.runFork(this.runCleanupLoop(e))}runCleanupLoop(e){let t=this.cleanupTerminalBatchMetadata().pipe(de.schedule(ws.spaced(e)),de.asVoid);return this.clock?de.withClock(t,this.clock):t}scheduleTerminalBatchCleanup(){if(!this.acceptingCleanup)return;this.cleanupSupervisor??=this.createCleanupSupervisor();let e=de.runFork(this.cleanupTerminalBatchMetadata());Nu.unsafeAdd(this.cleanupSupervisor.fibers,e)}async stopCleanup(){this.acceptingCleanup=!1;let e=this.cleanupFiber;if(this.cleanupFiber=null,e)await de.runPromise(ii.interrupt(e));let t=this.cleanupSupervisor;if(t)await de.runPromise(Nu.awaitEmpty(t.fibers));while(this.inFlightCleanups.size>0)await Promise.allSettled(this.inFlightCleanups);if(t)await de.runPromise(Xt.close(t.scope,jt.void)),this.cleanupSupervisor=null}requestTransition(e,t){let n=this.transitionQueue.at(-1)??this.activeTransition;if(n?.kind===e)return n.promise;let r=()=>{return},o=()=>{return},i=new Promise((c,l)=>{r=c,o=l}),s={kind:e,intervalMs:t,promise:i,resolve:r,reject:o};return this.transitionQueue.push(s),this.runNextTransition(),i}runNextTransition(){if(this.activeTransition)return;let e=this.transitionQueue.shift();if(!e)return;this.activeTransition=e,(e.kind==="start"?this.startCleanup(e.intervalMs):this.stopCleanup()).then(()=>this.completeTransition(e,!0),(n)=>this.completeTransition(e,!1,n))}completeTransition(e,t,n){if(this.activeTransition!==e)return;if(this.activeTransition=null,t)e.resolve();else e.reject(n);queueMicrotask(()=>this.runNextTransition())}createCleanupSupervisor(){let e=de.runSync(Xt.make()),t=de.runSync(Xt.extend(Nu.make(),e));return{scope:e,fibers:t}}cleanupTerminalBatchMetadata(){return de.tryPromise({try:()=>{let e=this.cleanup(JEe);return this.inFlightCleanups.add(e),e.then(()=>this.inFlightCleanups.delete(e),()=>this.inFlightCleanups.delete(e)),e},catch:(e)=>e}).pipe(de.asVoid,de.catchAll((e)=>de.sync(()=>{this.logger.warn("Failed to clean up terminal batch metadata",{error:e})})))}validateOperations(e){for(let t of e){let n=this.jobQueue.getValidator(t.type);if(!n)throw Error(`No job type declared: ${t.type}`);if(n.validateAndParse(t.data)===null)throw Error(`Invalid job data for type: ${t.type}`)}}async enqueueBatch(e,t,n,r){if(e.length===0)throw Error("Cannot enqueue empty batch");this.validateOperations(e);let o=[];this.batches.set(n,{jobIds:o,operations:e,source:t.source,startedAt:new Date().toISOString(),metadata:{...t.metadata,rootJobId:n}});try{for(let i of e){let s={...t,rootJobId:n,metadata:{...t.metadata,operationTarget:i.type}},c=await this.jobQueue.enqueue({type:i.type,data:i.data,options:s});o.push(c)}return this.logger.debug("Enqueued batch operations",{batchId:n,operationCount:e.length,jobIds:o,rootJobId:n}),this.scheduleTerminalBatchCleanup(),n}catch(i){throw this.batches.delete(n),this.logger.error("Failed to enqueue batch operations",{error:i,operationCount:e.length,enqueuedJobs:o.length}),i}}async getBatchStatus(e){let t=this.batches.get(e);if(!t)return null;try{let n=await Promise.all(t.jobIds.map((u)=>this.jobQueue.getStatus(u))),r=0,o=0,i=0,s=[];for(let[u,p]of n.entries()){if(!p){o++;let d=t.operations[u],g=t.jobIds[u]??"unknown";s.push(`Missing job ${g}${d?` for ${d.type}`:""}`);continue}switch(p.status){case"completed":r++;break;case"failed":if(o++,p.lastError)s.push(p.lastError);break;case"processing":case"pending":i++;break}}i+=t.operations.length-t.jobIds.length;let c;if(i>0)c=je.PROCESSING;else if(o>0)c=je.FAILED;else c=je.COMPLETED;if(t.terminalAt===void 0&&(c===je.COMPLETED||c===je.FAILED))t.terminalAt=Date.now();let l;for(let u=0;u<t.jobIds.length;u++){let p=n[u];if(p&&p.status!=="completed"&&p.status!=="failed"){let d=t.operations[u];if(d)l=`Processing ${d.type}`;break}}return{batchId:e,totalOperations:t.operations.length,completedOperations:r,failedOperations:o,errors:s,status:c,currentOperation:l,metadata:t.metadata}}catch(n){throw this.logger.error("Failed to get batch status",{batchId:e,error:n}),n}}inspectRetention(e){let t=this.batches.get(e);return t?{terminalAt:t.terminalAt}:void 0}async cleanup(e){let t=Date.now()-e,n=0;for(let[r,o]of this.batches.entries()){if(o.terminalAt!==void 0){if(o.terminalAt<=t)this.batches.delete(r),n++;continue}if(new Date(o.startedAt).getTime()<=t){let s=await this.getBatchStatus(r);if(s&&(s.status===je.COMPLETED||s.status===je.FAILED))this.batches.delete(r),n++}}return this.logger.debug("Cleaned up batch metadata",{cleaned:n}),n}registerBatch(e,t,n,r,o){this.batches.set(e,{jobIds:t,operations:n,source:r,startedAt:new Date().toISOString(),metadata:o}),this.logger.debug("Registered batch metadata",{batchId:e,operationCount:n.length,jobIds:t})}async getActiveBatches(){let e=[];try{for(let[t,n]of this.batches){let r=await this.getBatchStatus(t);if(r&&(r.status==="pending"||r.status==="processing"))e.push({batchId:t,status:r,metadata:{operations:n.operations,source:n.source,startedAt:n.startedAt,metadata:n.metadata}})}return this.logger.debug("Retrieved active batches",{count:e.length}),e}catch(t){throw this.logger.error("Failed to get active batches",{error:t}),t}}}var GEe=a.preprocess((e)=>{if(typeof e!=="string")return e;return JSON.parse(e)},a.record(a.string(),a.unknown()));class x_{jobQueueService;messageBus;batchJobManager;logger;mode;pollTimer;pollCursor={updatedAt:0,jobId:""};polling=!1;static createFresh(e,t,n,r,o="combined"){return new x_(e,t,n,r,o)}constructor(e,t,n,r,o){this.jobQueueService=e,this.messageBus=t,this.batchJobManager=n,this.logger=r,this.mode=o}start(){if(this.mode==="durable-reader"&&!this.pollTimer){this.pollCursor={updatedAt:Date.now(),jobId:""},this.pollTimer=setInterval(()=>{this.pollDurableUpdates()},250),this.pollTimer.unref(),this.logger.debug("Job progress monitor ready (durable polling mode)");return}this.logger.debug("Job progress monitor ready (event-driven mode)")}stop(){if(this.pollTimer)clearInterval(this.pollTimer);this.pollTimer=void 0,this.logger.debug("Job progress monitor stopped")}async pollDurableUpdates(){if(this.polling)return;this.polling=!0;try{let e=await this.jobQueueService.getRuntimeUpdates(this.pollCursor,100);for(let t of e)if(this.pollCursor=t.cursor,t.job.status==="processing"&&t.job.progress)await this.publishJobProgress(t.job,t.job.progress);else if(t.job.status==="completed"||t.job.status==="failed")await this.handleJobStatusChange(t.job.id,t.job.status,t.job.metadata)}catch(e){this.logger.error("Failed to poll durable job progress",{error:e})}finally{this.polling=!1}}createProgressReporter(e,t){let n=Qa.from(async(r)=>{await this.emitJobProgress(e,r,t)});if(!n)throw Error("Failed to create ProgressReporter");return n}async emitBatchProgress(e,t,n){try{let r={totalOperations:t.totalOperations,completedOperations:t.completedOperations,failedOperations:t.failedOperations,currentOperation:t.currentOperation??"Processing batch...",errors:t.errors},o={id:e,type:"batch",status:t.status,metadata:n,batchDetails:r};if(t.totalOperations>0)o.progress={current:t.completedOperations,total:t.totalOperations,percentage:Math.round(t.completedOperations/t.totalOperations*100)};await this.messageBus.send({type:cy.progress,payload:o,sender:"job-progress-monitor",broadcast:!0}),this.logger.debug("Emitted batch progress update",{batchId:e,status:t.status,progress:`${t.completedOperations}/${t.totalOperations}`})}catch(r){this.logger.error("Error emitting batch progress update",{batchId:e,error:r})}}isBatchChild(e,t){return!!t&&t!==e}get publishesEvents(){return this.mode!=="durable-writer"}async broadcastEvent(e){await this.messageBus.send({type:cy.progress,payload:e,sender:"job-progress-monitor",broadcast:!0})}async emitJobProgress(e,t,n){try{if(n&&!await this.jobQueueService.recordAttemptProgress(e,n,t)){this.logger.debug("Discarding progress from obsolete job attempt",{jobId:e,attemptId:n});return}if(!this.publishesEvents)return;let r=await this.jobQueueService.getStatus(e);if(!r){this.logger.warn("Job not found for progress update",{jobId:e});return}await this.publishJobProgress(r,t)}catch(r){this.logger.error("Error emitting job progress",{jobId:e,error:r})}}async publishJobProgress(e,t){if(e.metadata.silent)return;if(this.isBatchChild(e.id,e.metadata.rootJobId))return;let n=t.total??0,r={id:e.id,type:"job",status:"processing",metadata:e.metadata,message:t.message};if(n>0)r.progress={current:t.progress,total:n,percentage:Math.round(t.progress/n*100)};await this.broadcastEvent(r)}async emitJobCompletion(e){await this.emitJobStatusEvent(e,"completed")}async emitJobFailure(e){await this.emitJobStatusEvent(e,"failed")}async emitJobStatusEvent(e,t){if(!this.publishesEvents)return;try{let n=await this.jobQueueService.getStatus(e);if(!n){this.logger.warn(`Cannot emit ${t} for unknown job`,{jobId:e});return}if(n.metadata.silent)return;if(this.isBatchChild(e,n.metadata.rootJobId)){this.logger.debug(`Skipping individual job ${t} for batch operation`,{jobId:e,rootJobId:n.metadata.rootJobId});return}let r={id:e,type:"job",status:t,message:this.extractStatusMessage(n,t),metadata:n.metadata,jobDetails:{jobType:n.type,priority:n.priority,retryCount:n.retryCount}};await this.broadcastEvent(r),this.logger.debug(`Emitted job ${t} event`,{jobId:e})}catch(n){this.logger.error(`Error emitting job ${t} event`,{jobId:e,error:n})}}extractStatusMessage(e,t){if(t==="failed")return e.lastError??void 0;if(!e.result)return;try{let n=GEe.parse(e.result),r=n.message;if(r)return String(r);let o=n.routesBuilt;if(o!==void 0)return`${o} routes built`}catch{}return}getStats(){return{isRunning:!0}}async handleJobStatusChange(e,t,n){if(!this.publishesEvents)return;let r=n?sp.safeParse(n):void 0,o=r?.success?r.data:void 0;if(o?.silent)return;try{if(await this.emitJobStatusEvent(e,t),o&&this.isBatchChild(e,o.rootJobId))try{let i=o.rootJobId,s=await this.batchJobManager.getBatchStatus(i);if(s){let c=s.metadata??o;await this.emitBatchProgress(i,s,c)}}catch(i){this.logger.warn("Failed to emit batch progress",{jobId:e,rootJobId:o.rootJobId,error:i})}}catch(i){this.logger.error("Failed to handle job status change",{jobId:e,status:t,error:i})}}}var VEe=a.record(a.string(),a.unknown());class ly{logger;schema;jobTypeName;executionTimeoutMs;constructor(e,t){this.logger=e,this.schema=t.schema,this.jobTypeName=t.jobTypeName,this.executionTimeoutMs=t.executionTimeoutMs}validateAndParse(e){if(!this.schema)throw Error(`${this.jobTypeName}: No schema provided. Override validateAndParse() or provide a schema.`);let t=this.schema.safeParse(e);if(!t.success)return this.logger.warn(`Invalid ${this.jobTypeName} job data`,{data:e,validationError:t.error.issues}),null;return this.logger.debug(`${this.jobTypeName} job data validation successful`,{data:this.summarizeDataForLog(t.data)}),t.data}async onError(e,t,n,r,o){this.logger.error(`${this.jobTypeName} job error handler triggered`,{jobId:n,errorMessage:e.message,errorStack:e.stack,data:this.summarizeDataForLog(t)})}async reportProgress(e,t){await e.report({progress:t.progress,total:t.total??100,message:t.message})}summarizeDataForLog(e){let t=VEe.safeParse(e);return t.success?t.data:{}}}function uy(e,t,n){return async(r)=>{let{type:o,data:i,toolContext:s=null,options:c,projection:l}=r,u=s?G5(s):void 0,{metadata:p,...d}=c??{},g={operationType:"data_processing",pluginId:t,...p,...s&&{interfaceType:s.interfaceType,conversationId:s.conversationId,channelId:s.channelId,requestedByActor:s.actor,...u?{requestedByUserId:u}:{},requestedByInterface:s.interfaceType,...s.progressToken!==void 0&&{progressToken:s.progressToken}}};if(s&&!u)delete g.requestedByUserId;let f={...d,source:t,...c?.rootJobId&&{rootJobId:c.rootJobId},...l&&{projection:l},metadata:g},v=n&&!o.includes(":")?`${t}:${o}`:o;return e.enqueue({type:v,data:i,options:f})}}function S_(e,t){return async(n,r)=>{let o=r?.rootJobId??Pt(),i=n.map((c)=>({...c,type:c.type.includes(":")?c.type:`${t}:${c.type}`})),s={...r,source:t,rootJobId:o,metadata:{...r?.metadata,operationType:"batch_processing",pluginId:t}};return await e.enqueueBatch(i,s,o,t),o}}function v_(e,t){return(n,r)=>{let o=n.includes(":")?n:`${t}:${n}`;e.registerHandler(o,r,t)}}var QEe=a.custom((e)=>typeof e==="object"&&e!==null&&("safeParse"in e)),KEe=a.object({name:a.string(),schema:QEe});function V5(e){return KEe.safeParse(e).success}function YEe(e){if(!e)return;return{status:e.status,message:e.message,lastCheck:e.lastCheck?.toISOString(),details:e.details}}function Q5(e){return{model:e.model,version:e.version,uptime:e.uptime,entities:e.entities,entityCounts:e.entityCounts,embeddings:e.embeddings,ai:e.ai,daemons:e.daemons.map((t)=>({name:t.name,pluginId:t.pluginId,status:t.status,health:YEe(t.health)})),endpoints:e.endpoints,interactions:e.interactions}}var K5={digest:"conversation:digest"};var XEe="/api/chat",fo="web-chat-guest",Ew=a.strictObject({idleSeconds:a.number().int().positive().max(Math.floor(Number.MAX_SAFE_INTEGER/1000)),maxAgeSeconds:a.number().int().positive().max(Math.floor(Number.MAX_SAFE_INTEGER/1000))}).refine((e)=>e.idleSeconds<=e.maxAgeSeconds,"Guest idle expiry must not exceed maximum age"),Iw=a.strictObject({visitorId:a.string().uuid(),retention:Ew}),Je=a.string().trim().min(1).max(256),hrt="x-brain-conversation-id",yrt=a.strictObject({expiresAt:a.number().int().positive(),provider:a.string().min(1),notice:a.string().min(1),deletionLimitations:a.string().min(1),retention:Ew,messageCharacters:a.number().int().positive(),canSend:a.boolean(),presentation:X5.optional()}),eIe=a.strictObject({conversationId:Je,state:a.enum(["active","completed","failed","interrupted","uncertain"])}),t9=a.string().regex(/^upload-[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i),w_=a.string().trim().min(1).max(48),C_=a.string().datetime(),Y5=a.string().regex(/^\/(?!\/)/).max(2048),Am=a.string().regex(/^(?:\/(?!\/)|https?:\/\/)/).max(2048),tIe=a.looseObject({kind:a.literal("tool-approval"),id:Je,toolCallId:Je.optional(),toolName:a.string().trim().min(1).max(256),input:a.record(a.string(),a.unknown()).optional(),summary:a.string().max(4096),completionSummary:a.string().max(4096).optional(),preview:a.string().max(1e5).optional(),state:a.enum(["approval-requested","approval-responded","output-available","output-denied","output-error"]),output:a.unknown().optional(),error:a.string().max(4096).optional()}),nIe=a.looseObject({entityType:a.string().trim().min(1).max(128).optional(),entityId:Je.optional(),attachmentType:a.string().trim().min(1).max(128).optional()}),rIe=a.looseObject({mediaType:a.string().trim().min(1).max(255),url:Am,downloadUrl:Am.optional(),previewUrl:Am.optional(),filename:a.string().trim().min(1).max(255).optional(),sizeBytes:a.number().int().nonnegative().optional(),source:nIe.optional()}),n9=a.looseObject({kind:a.literal("attachment"),id:Je,jobId:Je.optional(),title:a.string().max(4096),description:a.string().max(20000).optional(),attachment:rIe}),oIe=a.looseObject({id:Je,title:a.string().max(4096).optional(),source:a.string().trim().min(1).max(512),url:Am.optional(),entityType:a.string().trim().min(1).max(128).optional(),entityId:Je.optional(),excerpt:a.string().max(20000).optional(),provenance:a.record(a.string(),a.unknown()).optional()}),E_=a.looseObject({kind:a.literal("sources"),id:Je,title:a.string().max(4096).optional(),sources:a.array(oIe).min(1).max(100)}),iIe=a.discriminatedUnion("type",[a.object({type:a.literal("prompt"),id:Je,label:a.string().trim().min(1).max(256),prompt:a.string().min(1).max(1e5),description:a.string().max(4096).optional()}),a.object({type:a.literal("event"),id:Je,label:a.string().trim().min(1).max(256),event:a.string().trim().min(1).max(256),fromState:a.string().trim().min(1).max(256).optional(),description:a.string().max(4096).optional()})]),r9=a.looseObject({kind:a.literal("actions"),id:Je,title:a.string().max(4096).optional(),actions:a.array(iIe).min(1).max(100)}),o9=a.discriminatedUnion("kind",[tIe,n9,E_,r9]);function brt(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e.slice(0,10)){let o=E_.safeParse(r);if(!o.success||o.data.id!=="sources:tool-results")continue;for(let i of o.data.sources){if(t.length>=15)break;if(!i.entityType||!i.entityId||i.entityId.length>256||i.source!==i.entityType||i.id!==`${i.entityType}:${i.entityId}`||n.has(i.id))continue;n.add(i.id);let s;if(i.url&&i.url.length<=512)try{let c=new URL(i.url);if(c.protocol==="https:"&&!c.username&&!c.password&&c.href.length<=512)s=c.href}catch{}t.push({id:i.id,source:i.entityType,entityType:i.entityType,entityId:i.entityId,title:(i.title??i.entityId).slice(0,160),...i.excerpt?{excerpt:i.excerpt.slice(0,280)}:{},...s?{url:s}:{}})}}return t.length?[{kind:"sources",id:"sources:tool-results",title:"Retrieved sources",sources:t}]:[]}var sIe=a.object({id:Je,toolCallId:Je.optional(),toolName:a.string().trim().min(1).max(256),summary:a.string().max(4096),completionSummary:a.string().max(4096).optional(),preview:a.string().max(1e5).optional(),args:a.unknown()}),i9=a.object({toolName:a.string().trim().min(1).max(256),args:a.record(a.string(),a.unknown()).optional(),jobId:Je.optional(),data:a.unknown().optional(),error:a.object({message:a.string().max(4096),code:a.string().trim().min(1).max(256).optional()}).optional()}),xrt=a.looseObject({text:a.string().max(1e6),toolResults:a.array(i9).max(100).optional(),cards:a.array(o9).max(100).optional(),pendingConfirmations:a.array(sIe).max(100).optional(),usage:a.object({promptTokens:a.number().int().nonnegative(),completionTokens:a.number().int().nonnegative(),totalTokens:a.number().int().nonnegative()})});function Srt(e=XEe){let t=aIe(e);return{stream:t,actions:`${t}/actions`,sessions:`${t}/sessions`,sessionArchive:`${t}/sessions/archive`,messages:`${t}/messages`,uploads:`${t}/uploads`,contextSessions:`${t}/context-sessions`,documentAttachments:`${t}/attachments/document`,imageAttachments:`${t}/attachments/image`,jobStatus:`${t}/jobs/status`}}function aIe(e){let t=e.trim();if(!t.startsWith("/")||t.startsWith("//")||t.length>512||/[\s"'<>\\]/u.test(t)||t.includes("?")||t.includes("#"))throw Error("Chat API path must be a same-origin absolute path without query or fragment");let n=t.replace(/\/+$/,"");if(n.length===0)throw Error("Chat API path must not be the site root");return n}var cIe=a.strictObject({version:a.literal(1),sourceId:a.string().trim().regex(/^[a-z][a-z0-9-]*$/).max(64),itemId:a.string().trim().min(1).max(300),titleSeed:a.string().trim().min(1).max(160).refine((e)=>!/[\p{Cc}\p{Cf}]/u.test(e))}),vrt=a.object({query:a.string().trim().max(200).default(""),archived:a.boolean().default(!1),offset:a.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).default(0),limit:a.number().int().min(1).max(100).default(25)}),lIe=a.looseObject({id:Je,title:w_,lastActiveAt:C_,archived:a.boolean().optional(),contextHandoff:cIe.optional()}),Trt=a.looseObject({sessions:a.array(lIe).max(100)}),uIe=a.looseObject({kind:a.string().trim().min(1).max(64),id:Je}),pIe=a.looseObject({kind:a.literal("text"),filename:a.string().trim().min(1).max(255),mediaType:a.string().trim().min(1).max(255),sizeBytes:a.number().int().nonnegative(),createdAt:C_,source:uIe.optional()}),s9=a.looseObject({id:Je,role:a.enum(["user","assistant"]),content:a.string().max(1e6),attachments:a.array(pIe).max(100).optional(),cards:a.array(o9).max(100).optional()}),wrt=a.looseObject({messages:a.array(s9).max(100)}),Crt=a.string().min(1).max(256).refine((e)=>e.trim().length>0),Ert=a.strictObject({messages:a.array(s9).max(100),submission:eIe.nullable()}),Irt=a.object({type:a.literal("text"),text:a.string().max(1e6)}),krt=a.object({type:a.literal("file"),mediaType:a.string().trim().min(1).max(255).optional(),filename:a.string().trim().min(1).max(255).optional(),url:a.string().min(1).max(2000000)}),a9=a.object({kind:a.literal("upload"),id:t9}),Rrt=a.object({type:a.literal("data-upload"),data:a.looseObject({ref:a9})}),dIe=a.object({id:Je,approved:a.boolean(),toolCallId:Je.optional(),toolName:a.string().trim().min(1).max(256).optional(),input:a.record(a.string(),a.unknown()).optional(),title:a.string().max(4096).optional()}),Prt=a.looseObject({state:a.literal("approval-responded"),toolCallId:Je.optional(),toolName:a.string().trim().min(1).max(256).optional(),input:a.record(a.string(),a.unknown()).optional(),title:a.string().max(4096).optional(),approval:dIe}),mIe=a.object({id:Je.optional(),role:a.enum(["user","assistant","system"]),parts:a.array(a.unknown()).max(1000).optional(),content:a.string().max(1e6).optional()}),Art=a.object({id:Je.optional(),messages:a.array(mIe).min(1).max(200),trigger:a.string().trim().min(1).max(64).optional()}).strict(),Ort=a.strictObject({id:Je.optional(),messages:a.array(a.strictObject({id:Je,role:a.literal("user"),parts:a.array(a.strictObject({type:a.literal("text"),text:a.string()})).min(1).max(16)})).length(1)}),c9=a.enum(["pending","processing","completed","failed"]),fIe=a.looseObject({type:a.enum(["job","batch"]),status:c9,operationType:a.enum(["file_operations","content_operations","data_processing","batch_processing"]),operationTarget:a.string().max(1024).optional(),message:a.string().max(4096).optional(),progress:a.object({current:a.number().nonnegative(),total:a.number().nonnegative(),percentage:a.number().min(0).max(100)}).optional()}),gIe=a.looseObject({status:a.enum(["tool-running","tool-completed","tool-awaiting-approval","tool-failed"]),toolName:a.string().trim().min(1).max(256),error:a.string().max(4096).optional()}),Drt=a.discriminatedUnion("type",[a.looseObject({type:a.literal("start"),messageId:Je.optional()}),a.looseObject({type:a.literal("start-step")}),a.looseObject({type:a.literal("finish-step")}),a.looseObject({type:a.literal("finish"),finishReason:a.enum(["length","error","stop","content-filter","tool-calls","other"]).optional()}),a.looseObject({type:a.literal("abort"),reason:a.string().max(4096).optional()}),a.looseObject({type:a.literal("error"),errorText:a.string().max(20000)}),a.looseObject({type:a.literal("text-start"),id:Je}),a.looseObject({type:a.literal("text-delta"),id:Je,delta:a.string().max(1e6)}),a.looseObject({type:a.literal("text-end"),id:Je}),a.looseObject({type:a.literal("reasoning-start"),id:Je}),a.looseObject({type:a.literal("reasoning-delta"),id:Je,delta:a.string().max(1e6)}),a.looseObject({type:a.literal("reasoning-end"),id:Je}),a.looseObject({type:a.literal("tool-input-start"),toolCallId:Je,toolName:a.string().trim().min(1).max(256),title:a.string().max(4096).optional()}),a.looseObject({type:a.literal("tool-input-delta"),toolCallId:Je,inputTextDelta:a.string().max(1e6)}),a.looseObject({type:a.literal("tool-input-available"),toolCallId:Je,toolName:a.string().trim().min(1).max(256),input:a.unknown(),title:a.string().max(4096).optional()}),a.looseObject({type:a.literal("tool-input-error"),toolCallId:Je,toolName:a.string().trim().min(1).max(256),input:a.unknown(),errorText:a.string().max(20000),title:a.string().max(4096).optional()}),a.looseObject({type:a.literal("tool-approval-request"),approvalId:Je,toolCallId:Je}),a.looseObject({type:a.literal("tool-output-available"),toolCallId:Je,output:a.unknown(),preliminary:a.boolean().optional()}),a.looseObject({type:a.literal("tool-output-error"),toolCallId:Je,errorText:a.string().max(20000)}),a.looseObject({type:a.literal("tool-output-denied"),toolCallId:Je}),a.looseObject({type:a.literal("source-url"),sourceId:Je,url:Am,title:a.string().max(4096).optional()}),a.looseObject({type:a.literal("source-document"),sourceId:Je,mediaType:a.string().trim().min(1).max(255),title:a.string().max(4096),filename:a.string().trim().min(1).max(255).optional()}),a.looseObject({type:a.literal("file"),url:Am,mediaType:a.string().trim().min(1).max(255)}),a.looseObject({type:a.literal("data-progress"),id:Je.optional(),data:fIe,transient:a.boolean().optional()}),a.looseObject({type:a.literal("data-status"),id:Je.optional(),data:gIe,transient:a.boolean().optional()}),a.looseObject({type:a.literal("data-tool-result"),id:Je.optional(),data:i9,transient:a.boolean().optional()}),a.looseObject({type:a.literal("data-actions"),id:Je.optional(),data:r9,transient:a.boolean().optional()}),a.looseObject({type:a.literal("data-sources"),id:Je.optional(),data:E_,transient:a.boolean().optional()}),a.looseObject({type:a.literal("data-attachment"),id:Je.optional(),data:n9,transient:a.boolean().optional()})]),Mrt=a.strictObject({conversationId:Je}),_rt=a.object({title:w_}).strict(),zrt=a.object({renamed:a.boolean(),title:w_}),Frt=a.object({archived:a.boolean()}),jrt=a.object({deleted:a.boolean()}),Nrt=a.object({conversationId:Je,action:e9}).strict(),Lrt=a.looseObject({id:Je,status:c9,message:a.string().max(4096).optional()}),Brt=a.looseObject({id:t9,ref:a9,filename:a.string().trim().min(1).max(255),mediaType:a.string().trim().min(1).max(255),sizeBytes:a.number().int().nonnegative(),createdAt:C_,url:Y5,downloadUrl:Y5}).refine((e)=>e.id===e.ref.id,{path:["ref","id"],message:"Upload response ids must match"});var Ie=Nt("conversations",{id:le("id").primaryKey(),sessionId:le("session_id").notNull(),interfaceType:le("interface_type").notNull(),channelId:le("channel_id").notNull(),personId:le("person_id"),started:le("started").notNull(),lastActive:le("last_active").notNull(),metadata:le("metadata"),created:le("created").notNull(),updated:le("updated").notNull()},(e)=>({sessionIdx:zt("idx_conversations_session").on(e.sessionId),channelIdx:zt("idx_conversations_channel").on(e.channelId),personIdx:zt("idx_conversations_person").on(e.personId),interfaceSessionIdx:zt("idx_conversations_interface_session").on(e.interfaceType,e.sessionId),interfaceChannelIdx:zt("idx_conversations_interface_channel").on(e.interfaceType,e.channelId)})),jn=Nt("messages",{id:le("id").primaryKey(),conversationId:le("conversation_id").notNull().references(()=>Ie.id,{onDelete:"cascade"}),role:le("role").notNull(),content:le("content").notNull(),timestamp:le("timestamp").notNull(),metadata:le("metadata")},(e)=>({conversationIdx:zt("idx_messages_conversation").on(e.conversationId),timestampIdx:zt("idx_messages_timestamp").on(e.timestamp)})),ap=Nt("summary_tracking",{conversationId:le("conversation_id").primaryKey().references(()=>Ie.id,{onDelete:"cascade"}),lastSummarizedAt:le("last_summarized_at"),lastMessageId:le("last_message_id"),messagesSinceSummary:qe("messages_since_summary").default(0),updated:le("updated").notNull()});function l9(e){return Ui({url:e.url,schema:{conversations:Ie,messages:jn,summaryTracking:ap},authToken:e.authToken,authTokenEnv:"CONVERSATION_DATABASE_AUTH_TOKEN"})}var hIe=a.preprocess((e)=>{if(typeof e!=="string")return e;try{return JSON.parse(e)}catch{return}},a.record(a.string(),a.unknown())).catch({});function Ya(e){return hIe.parse(e)}var kw="conversation:messageAdded",I_="conversation:started",py=a.object({identity:Fs,interfaceType:a.string(),role:Tm,displayName:a.string().optional(),username:a.string().optional(),isBot:a.boolean().optional()}),yIe=a.preprocess(bIe,py);function bIe(e){if(!pi(e)||"identity"in e)return e;let{actorId:t,interfaceType:n,role:r}=e;if(typeof t!=="string"||typeof n!=="string"||r!=="user"&&r!=="assistant")return e;let{userId:o,canonicalId:i}=e;return{identity:u9({actorId:t,interfaceType:n,role:r,...typeof o==="string"?{userId:o}:{},...typeof i==="string"?{canonicalId:i}:{}}),interfaceType:n,role:r,...typeof e.displayName==="string"?{displayName:e.displayName}:{},...typeof e.username==="string"?{username:e.username}:{},...typeof e.isBot==="boolean"?{isBot:e.isBot}:{}}}var dy=a.object({messageId:a.string().optional(),channelId:a.string().optional(),channelName:a.string().optional(),threadId:a.string().optional(),metadata:a.record(a.string(),a.unknown()).optional()}),p9=a.looseObject({actor:yIe.optional(),source:dy.optional()});function d9(e){if(typeof e==="string")try{let t=JSON.parse(e);return pi(t)?t:null}catch{return null}return pi(e)?e:null}function xIe(e){if(e.role!=="assistant")return!1;if(e.content.trim().length===0)return!1;let t=d9(e.metadata),n=t?.entityMemoryRefs;if(Array.isArray(n)&&n.length>0)return!1;let r=t?.cards;if(!Array.isArray(r))return!0;return!r.some((o)=>{if(!pi(o))return!1;if(o.kind==="tool-approval")return!0;return o.kind==="actions"&&o.id==="actions:upload-intent"})}var SIe=a.object({id:a.string(),conversationId:a.string(),role:a.string(),content:a.string(),timestamp:a.string(),metadata:a.string().nullable()}),m9=a.object({conversationId:a.string(),messageCount:a.number(),messages:a.array(SIe),windowStart:a.number(),windowEnd:a.number(),windowSize:a.number(),timestamp:a.string()});var Gi=x`strftime('%Y-%m-%dT%H:%M:%fZ', 'now')`;function k_(){return g9(!1)}function f9(){return g9(!0)}function g9(e){let t=Ew.shape.maxAgeSeconds.maxValue,n=x`(
166
+ 5. Structure your response clearly and concisely`,dataSourceId:"shell:ai-content",requiredPermission:"public",useKnowledgeContext:!0,schema:vw,formatter:new iy};var pEe=a.object({type:a.string().describe("Type of source (e.g., note, article)"),title:a.string().describe("Title or identifier of the source"),relevance:a.number().min(0).max(1).describe("Relevance score")}),R5=a.object({answer:a.string().describe("The answer to the user's query"),sources:a.array(pEe).optional().describe("Sources used to generate the answer"),confidence:a.enum(["high","medium","low"]).optional().describe("Confidence level of the answer"),suggestions:a.array(a.string()).optional().describe("Related topics or follow-up questions")});function Va(e,t){return e.parse(t)}class Qa{callback;heartbeatInterval;constructor(e){this.callback=e}static from(e){if(!e)return;return new Qa(e)}static noop(){return new Qa(async()=>{})}createSub(e){let{scale:t}=e??{};if(t){let{start:n,end:r}=t,o=r-n;return new Qa(async(i)=>{let s=n+i.progress/(i.total??100)*o;await this.callback({...i,progress:s,total:100})})}return new Qa(this.callback)}async report(e){await this.callback(e)}startHeartbeat(e,t=5000){this.stopHeartbeat(),this.heartbeatInterval=setInterval(()=>{this.report({message:e,progress:0}).catch(()=>{})},t)}stopHeartbeat(){if(this.heartbeatInterval)clearInterval(this.heartbeatInterval),this.heartbeatInterval=void 0}toCallback(){return this.callback}}var mEe=a.object({enabled:a.boolean().describe("Whether the plugin is enabled"),debug:a.boolean().describe("Enable debug logging for this plugin")});function fEe(e,t){return t.reduce((n,r)=>typeof n==="object"&&n!==null?Reflect.get(n,r):void 0,e)}function gEe(e){return e.map((t)=>`${t.path||"<root>"}: ${t.message}`).join("; ")}class km extends Error{pluginId;issues;constructor(e,t){super(`Invalid plugin config for ${e} at ${gEe(t)}; correct the listed fields in brain.yaml or the package's use() configuration`);this.name="PluginConfigValidationError",this.pluginId=e,this.issues=t}static fromZod(e,t,n){return new km(e,t.issues.map((r)=>({path:r.path.map(String).join("."),code:r.code,message:r.message,missing:r.code==="custom"&&r.params?.missing===!0||(r.code==="invalid_type"||r.code==="custom")&&fEe(n,r.path)===void 0})))}}var hEe=a.object({toolName:a.string(),args:a.unknown(),progressToken:a.union([a.string(),a.number()]).optional(),hasProgress:a.boolean().optional(),interfaceType:a.string(),actor:Fs,displayName:a.string().optional(),conversationId:a.string().optional(),channelId:a.string().optional(),channelName:a.string().optional(),runId:a.string().optional(),toolCallId:a.string().optional(),userPermissionLevel:a.enum(["admin","trusted","public"]).optional(),isAnchor:a.boolean().optional(),signal:a.custom((e)=>e instanceof AbortSignal).optional()}),yEe=a.object({resourceUri:a.string()});class ip{id;version;description;packageName;config;context;get logger(){return this.context?.logger??di.createFresh({context:this.id})}constructor(e,t,n,r){this.id=e,this.packageName=t.name,this.version=t.version,this.description=t.description??`${t.name} plugin`;let o=r.safeParse(n);if(!o.success)throw km.fromZod(e,o.error,n);this.config=o.data}setupMessageHandlers(e){e.messaging.subscribe(sy.toolExecute(this.id),async(t)=>{try{let n=hEe.safeParse(t.payload);if(!n.success)return{success:!1,error:"Invalid tool execution request format"};let{toolName:r,args:o,progressToken:i,hasProgress:s,interfaceType:c,actor:l,displayName:u,conversationId:p,channelId:d,channelName:g,runId:f,toolCallId:v,userPermissionLevel:T,isAnchor:E,signal:A}=n.data,j=(await this.getTools()).find((D)=>D.name===r);if(!j)return{success:!1,error:`Tool not found: ${r}`};let ie={interfaceType:c,actor:l,...u&&{displayName:u},...p&&{conversationId:p},...d&&{channelId:d},...g&&{channelName:g},...f&&{runId:f},...v&&{toolCallId:v},...T&&{userPermissionLevel:T},...E!==void 0&&{isAnchor:E},...A&&{signal:A},...s&&i!==void 0&&{progressToken:i,sendProgress:async(D)=>{await e.messaging.send({type:sy.progress(this.id),payload:{progressToken:i,notification:D}})}}};return{success:!0,data:await j.handler(o,ie)}}catch(n){return this.logger.error("Tool execution error",n),{success:!1,error:Ke(n)}}}),e.messaging.subscribe(sy.resourceGet(this.id),async(t)=>{try{let n=yEe.safeParse(t.payload);if(!n.success)return{success:!1,error:"Invalid resource get request format"};let{resourceUri:r}=n.data,i=(await this.getResources()).find((c)=>c.uri===r);if(!i)return{success:!1,error:`Resource not found: ${r}`};return{success:!0,data:await i.handler()}}catch(n){return this.logger.error("Resource fetch error",n),{success:!1,error:Ke(n)}}})}async onRegister(e){}async onRegistrationComplete(e){}async finalizeRegistration(){await this.onRegistrationComplete(this.getContext())}async onReady(e){}async ready(){await this.onReady(this.getContext())}async getCapabilities(){let e=await this.getInstructions();return{tools:await this.getTools(),resources:await this.getResources(),...e&&{instructions:e}}}async getTools(){return[]}async getResources(){return[]}async getInstructions(){return}async shutdown(){await this.onShutdown()}async onShutdown(){}getContext(){if(!this.context)throw Error(`Plugin ${this.id}: Plugin not registered yet`);return this.context}determineUserPermissionLevel(e){return"public"}createProgressBridge(e){if(!e)return;let t=this.context;if(!t)return;let n=this.id;return Qa.from(async(r)=>{await t.messaging.send({type:sy.progress(n),payload:{progressToken:e,notification:{progress:r.progress,total:r.total,message:r.message}}})})}}var P5=a.object({id:a.string(),template:a.string(),content:a.unknown().optional(),dataQuery:a.looseObject({entityType:a.string().optional(),template:a.string().optional(),query:a.looseObject({id:a.string().optional(),limit:a.number().optional(),offset:a.number().optional()}).optional()}).optional(),order:a.number().optional()}),o_=["primary","secondary"],A5=a.object({show:a.boolean().default(!1),label:a.string().optional(),slot:a.enum(o_).default("primary"),priority:a.number().min(0).max(100).default(50)}).optional(),i_=a.object({id:a.string(),path:a.string(),title:a.string().default(""),pageLabel:a.string().optional(),description:a.string().default(""),sections:a.array(P5).default([]),layout:a.string().default("default"),fullscreen:a.boolean().optional(),pluginId:a.string().optional(),sourceEntityType:a.string().optional(),external:a.boolean().optional(),navigation:A5}),O5=a.object({routes:a.array(i_),pluginId:a.string()}),D5=a.object({paths:a.array(a.string()).optional(),pluginId:a.string().optional()}),M5=a.object({pluginId:a.string().optional()}),_5=a.object({path:a.string()}),Tw=a.object({label:a.string(),href:a.string(),priority:a.number()});var bEe="site:metadata:get",xEe="site:metadata:updated",s_=a.object({heading:a.string().describe("Main CTA heading text"),buttonText:a.string().describe("Call-to-action button text"),buttonLink:a.string().describe("URL or anchor for the CTA button")}),z5=a.object({blurb:a.string().optional().describe("Short italic subtitle under the section title")}),ww=a.object({represents:a.enum(["brain","anchor"]).default("anchor").describe("Identity represented by the site"),title:a.string().describe("The site's title"),description:a.string().describe("The site's description"),url:a.string().optional().describe("Canonical site URL"),copyright:a.string().optional().describe("Copyright notice text"),logo:a.boolean().optional().describe("Whether to display logo instead of title text in header"),themeMode:a.enum(["light","dark"]).optional().describe("Default theme mode"),analyticsScript:a.string().optional().describe("Analytics script HTML"),cta:s_.optional().describe("Call-to-action configuration"),sections:a.record(a.string(),z5).optional().describe("Optional per-section blurbs, keyed by section id (e.g. 'essays', 'presentations', 'about'). Used by homepage templates that render editorial section headers.")});var SEe=a.object({platform:a.enum(["github","instagram","linkedin","email","website"]).describe("Social media platform"),url:a.string().describe("Profile or contact URL"),label:a.string().optional().describe("Optional display label")}),vEe=ww.extend({copyright:a.string(),navigation:a.object({primary:a.array(Tw),secondary:a.array(Tw)}),socialLinks:a.array(SEe).optional().describe("Social media links from profile metadata")});function ay(e,t){return t?e.nullable().default(null):e}function c_(e){switch(e.type){case"string":return ay(a.string(),e.optional);case"number":return ay(a.number(),e.optional);case"enum":return ay(a.enum(e.options),e.optional);case"object":{let t={};for(let[n,r]of Object.entries(e.fields))t[n]=c_(r);return ay(a.object(t),e.optional)}case"array":{let t=a.array(TEe(e));if(e.minItems!==void 0)t=t.min(e.minItems);if(e.length!==void 0)t=t.length(e.length);return ay(t,e.optional)}}}function TEe(e){let{items:t}=e;switch(t.type){case"string":return a.string();case"number":return a.number();case"enum":return a.enum(t.options);case"object":{let n={};for(let[r,o]of Object.entries(t.fields))n[r]=c_(o);return a.object(n)}}}function a_(e,t){switch(t.type){case"string":case"enum":return{key:e,label:t.label,type:"string"};case"number":return{key:e,label:t.label,type:"number"};case"object":return{key:e,label:t.label,type:"object",children:Object.entries(t.fields).map(([n,r])=>a_(n,r))};case"array":{let n={key:e,label:t.label,type:"array"};switch(t.items.type){case"string":case"enum":return n.itemType="string",n;case"number":return n.itemType="number",n;case"object":return n.itemType="object",n.itemMappings=Object.entries(t.items.fields).map(([r,o])=>a_(r,o)),n}}}}function F5(e,t){let n={};for(let[i,s]of Object.entries(t.fields))n[i]=c_(s);let r=a.object(n),o=new Im(r,{title:t.title,mappings:Object.entries(t.fields).map(([i,s])=>a_(i,s))});return{name:e,description:t.description,schema:r,formatter:o,requiredPermission:t.requiredPermission??"public",layout:{component:t.layout,...t.fullscreen!==void 0?{fullscreen:t.fullscreen}:{}},...t.runtimeScripts?{runtimeScripts:t.runtimeScripts}:{}}}function wEe(e){let t={};for(let[n,r]of Object.entries(e.sections))t[n]=F5(n,r);return t}var CEe=ww.omit({url:!0,analyticsScript:!0}),j5=CEe.extend({title:a.string().optional().describe("Optional site title override"),description:a.string().optional().describe("Optional site description override")});function N5(e){return j5.parse(vm(e).frontmatter)}async function EEe(e){let n=(await e.listEntities({entityType:"site-info",options:{limit:1}}))[0];if(!n)throw Error("Site info not found \u2014 create a site-info entity");return N5(n.content)}function l_(e,t={}){let n=L5(e),r=L5(t.sharedDomain??"rizom.ai").replace(/^\./,""),o=`.${r}`;if(n.endsWith(o)){let i=n.slice(0,-o.length);if(i.length>0&&!i.includes("."))return`${i}-preview.${r}`}return`preview.${n}`}function L5(e){return e.trim().replace(/^https?:\/\//i,"").replace(/\/$/,"").toLowerCase()}class Rm{static instance=null;entityDisplay;constructor(){}static getInstance(){return Rm.instance??=new Rm,Rm.instance}configure(e){this.entityDisplay=e}static resetInstance(){Rm.instance=null}hasRoute(e){return this.entityDisplay?.[e]!==void 0}isCitable(e){if(this.entityDisplay?.[e]?.citable===!1)return!1;if(!Object.values(this.entityDisplay??{}).some((n)=>n.citable===!0))return this.hasRoute(e);return this.entityDisplay?.[e]?.citable===!0}generateUrl(e,t){let n=this.entityDisplay?.[e];if(n)return`/${n.pluralName??n.label.toLowerCase()+"s"}/${t}`;return`/${UA(e)}/${t}`}}var q5=["primary","secondary"];var IEe=a.custom((e)=>typeof e==="function","Expected a React component"),kEe=a.strictObject({show:a.boolean().optional(),label:a.string().min(1).optional(),slot:a.enum(q5).optional(),priority:a.number().optional()}),REe=a.strictObject({id:a.string().min(1),template:a.string().min(1),content:a.unknown().optional(),dataQuery:a.looseObject({entityType:a.string().optional(),template:a.string().optional(),query:a.record(a.string(),a.unknown()).optional()}).optional(),order:a.number().optional()}),PEe=a.strictObject({id:a.string().min(1),path:a.string().startsWith("/"),title:a.string().optional(),pageLabel:a.string().optional(),description:a.string().optional(),sections:a.array(REe).optional(),layout:a.string().min(1).optional(),fullscreen:a.boolean().optional(),pluginId:a.string().optional(),sourceEntityType:a.string().optional(),external:a.boolean().optional(),navigation:kEe.optional()}),AEe=a.strictObject({label:a.string().min(1),pluralName:a.string().min(1).optional(),layout:a.string().min(1).optional(),paginate:a.boolean().optional(),pageSize:a.number().int().positive().optional(),citable:a.boolean().optional(),navigation:a.strictObject({show:a.boolean().optional(),slot:a.enum(q5).optional(),priority:a.number().optional()}).optional()}),OEe=a.strictObject({schema:a.custom((e)=>e instanceof a.ZodType,"Expected a Zod schema"),component:a.custom((e)=>typeof e==="function","Expected a React component"),title:a.string().min(1),description:a.string(),requiredPermission:a.enum(["admin","trusted","public"]).optional(),fullscreen:a.boolean().optional()}),B5=a.strictObject({namespace:a.string().min(1),sections:a.record(a.string(),OEe)}),DEe=a.record(a.string(),a.json()),MEe=a.record(a.string(),a.record(a.string(),DEe)),Z5={layouts:a.record(a.string(),IEe).refine((e)=>typeof e.default==="function",{message:'Site layouts must include a "default" component'}),routes:a.array(PEe),content:MEe.optional(),sections:a.union([B5,a.array(B5)]).optional(),themeOverride:a.string().optional(),headScripts:a.array(a.string()).optional(),entityDisplay:a.record(a.string(),AEe),staticAssets:a.record(a.string(),a.string()).optional()},Xet=a.strictObject(Z5).partial();var $5=a.strictObject(Z5).superRefine((e,t)=>{let n=new Set;for(let[i,s]of e.routes.entries()){if(n.has(s.id))t.addIssue({code:"custom",path:["routes",i,"id"],message:`Duplicate route id "${s.id}"`});n.add(s.id);let c=s.layout??"default";if(!e.layouts[c])t.addIssue({code:"custom",path:["routes",i,"layout"],message:`Unknown layout "${c}"`})}let r=Array.isArray(e.sections)?e.sections:e.sections?[e.sections]:[],o=new Map(r.map((i)=>[i.namespace,i]));if(o.size!==r.length)t.addIssue({code:"custom",path:["sections"],message:"Section group namespaces must be unique"});for(let[i,s]of Object.entries(e.content??{})){let c=o.get(i);if(!c){t.addIssue({code:"custom",path:["content",i],message:`Content namespace "${i}" has no section group`});continue}for(let[l,u]of Object.entries(s)){let p=c.sections[l];if(!p){t.addIssue({code:"custom",path:["content",i,l],message:`Content section "${i}.${l}" is not defined`});continue}let d=p.schema.safeParse(u);if(!d.success)t.addIssue({code:"custom",path:["content",i,l],message:`Content does not satisfy the "${i}.${l}" schema: ${a.prettifyError(d.error)}`})}}});var _Ee=a.string(),zEe=a.custom((e)=>{if(!pi(e))return!1;let{plugin:t,...n}=e;if(t!==void 0&&typeof t!=="function")return!1;return $5.safeParse(n).success});var u_=a.enum(["file_operations","content_operations","data_processing","batch_processing"]),FEe=a.looseObject({pluginId:a.string().optional(),progressToken:a.union([a.string(),a.number()]).optional(),operationType:u_,operationTarget:a.string().optional(),interfaceType:a.string().optional(),conversationId:a.string().optional(),channelId:a.string().optional(),requestedByActor:Fs.optional(),requestedByUserId:a.string().optional(),requestedByInterface:a.string().optional(),silent:a.boolean().optional(),provenance:Ns.optional()}),sp=a.looseObject({pluginId:a.string().optional(),progressToken:a.union([a.string(),a.number()]).optional(),operationType:u_,operationTarget:a.string().optional(),interfaceType:a.string().optional(),conversationId:a.string().optional(),channelId:a.string().optional(),requestedByActor:Fs.optional(),requestedByUserId:a.string().optional(),requestedByInterface:a.string().optional(),silent:a.boolean().optional(),provenance:Ns.optional(),rootJobId:a.string()}),Stt=a.enum(["none","skip","replace","coalesce"]);var jEe=a.object({id:a.string(),type:a.string(),data:a.string(),status:a.enum(["pending","processing","completed","failed"]),source:a.string().nullable(),priority:a.number(),retryCount:a.number(),maxRetries:a.number(),lastError:a.string().nullable(),createdAt:a.number(),scheduledFor:a.number(),startedAt:a.number().nullable(),completedAt:a.number().nullable(),attemptId:a.string().nullable(),workerSlotId:a.string().nullable(),workerSessionId:a.string().nullable(),leaseExpiresAt:a.number().nullable(),attemptHeartbeatAt:a.number().nullable(),runtimeUpdatedAt:a.number().nullable(),metadata:sp,progress:a.custom((e)=>typeof e==="object"&&e!==null&&("progress"in e)&&typeof e.progress==="number").nullable(),result:a.unknown().nullable().optional()}),Ka=15000;var p_=a.enum(["pending","processing","completed","failed"]),U5=a.enum(["completed","failed"]),je={PENDING:"pending",PROCESSING:"processing",COMPLETED:"completed",FAILED:"failed"},NEe=a.object({id:a.string(),type:a.string(),status:p_,data:a.unknown(),result:a.unknown().optional(),lastError:a.string().optional().nullable(),attempts:a.number(),maxRetries:a.number(),priority:a.number(),createdAt:a.date(),updatedAt:a.date(),processedAt:a.date().optional().nullable(),completedAt:a.date().optional().nullable(),failedAt:a.date().optional().nullable()}),LEe=a.object({jobId:a.string(),type:a.string(),status:U5,result:a.unknown().optional(),error:a.string().optional()}),d_=a.object({success:a.literal(!1),error:a.string().optional()}),Cw=a.object({id:a.string(),type:a.enum(["job","batch"]),status:p_,message:a.string().optional(),progress:a.object({current:a.number(),total:a.number(),percentage:a.number()}).optional(),aggregationKey:a.string().optional(),batchDetails:a.object({totalOperations:a.number(),completedOperations:a.number(),failedOperations:a.number(),currentOperation:a.string().optional(),errors:a.array(a.string()).optional()}).optional(),jobDetails:a.object({jobType:a.string(),priority:a.number(),retryCount:a.number()}).optional(),metadata:sp});var G=Nt("job_queue",{id:le("id").primaryKey().$defaultFn(()=>Pt()),type:le("type").notNull(),data:le("data").notNull(),result:le("result",{mode:"json"}),progress:le("progress",{mode:"json"}).$type(),source:le("source"),metadata:le("metadata",{mode:"json"}).$type().notNull(),status:le("status",{enum:["pending","processing","completed","failed"]}).notNull().default("pending"),priority:qe("priority").notNull().default(0),retryCount:qe("retryCount").notNull().default(0),maxRetries:qe("maxRetries").notNull().default(3),lastError:le("lastError"),createdAt:qe("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:qe("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:qe("startedAt"),completedAt:qe("completedAt"),attemptId:le("attemptId"),workerSlotId:le("workerSlotId"),workerSessionId:le("workerSessionId"),leaseExpiresAt:qe("leaseExpiresAt"),attemptHeartbeatAt:qe("attemptHeartbeatAt"),runtimeUpdatedAt:qe("runtimeUpdatedAt")},(e)=>({queueReadyIdx:zt("idx_job_queue_ready").on(e.status,e.priority,e.scheduledFor),jobTypeIdx:zt("idx_job_queue_type").on(e.type,e.status),runtimeUpdatesIdx:zt("idx_job_queue_runtime_updates").on(e.runtimeUpdatedAt,e.id),jobSourceIdx:zt("idx_job_queue_source").on(e.source)})),Ut=Nt("job_worker_sessions",{slotId:le("slotId").primaryKey(),sessionId:le("sessionId").notNull().unique(),startedAt:qe("startedAt").notNull(),heartbeatAt:qe("heartbeatAt").notNull(),expiresAt:qe("expiresAt").notNull().default(0)},(e)=>({heartbeatIdx:zt("idx_job_worker_sessions_heartbeat").on(e.heartbeatAt),expiresIdx:zt("idx_job_worker_sessions_expires").on(e.expiresAt)}));function W5(e){return Ui({url:e.url,schema:{jobQueue:G,jobWorkerSessions:Ut},authToken:e.authToken,authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN"})}class m_{declarations=new Map;handlers=new Map;validators=new Map;logger;mode;finalizedRegistrations;constructor(e,t){this.logger=e.child("HandlerRegistry"),this.mode=t}registerHandler(e,t,n){if(this.finalizedRegistrations)throw Error("Job handler registrations are finalized");if(this.declarations.has(e))throw Error(`Job handler is already registered for type: ${e}`);if(this.declarations.set(e,{handler:t,pluginId:n}),this.validators.set(e,t),this.mode!=="validation-only")this.handlers.set(e,t);this.logger.debug("Registered job execution declaration",{type:e,pluginId:n,mode:this.mode})}unregisterHandler(e){this.declarations.delete(e),this.handlers.delete(e),this.validators.delete(e),this.logger.debug("Unregistered job handler",{type:e})}unregisterPluginHandlers(e){let t=[...this.declarations.entries()].filter(([,n])=>n.pluginId===e).map(([n])=>n);for(let n of t)this.declarations.delete(n),this.handlers.delete(n),this.validators.delete(n);if(t.length>0)this.logger.debug("Unregistered plugin handlers",{pluginId:e,count:t.length,types:t})}finalizeRegistrations(){return this.finalizedRegistrations??=Object.freeze([...this.declarations.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>Object.freeze({type:e,pluginId:t.pluginId}))),this.finalizedRegistrations}getExecutionRegistrations(){if(!this.finalizedRegistrations)throw Error("Job handler registrations are not finalized");return this.finalizedRegistrations}getRegisteredTypes(){return[...this.handlers.keys()]}getHandler(e){return this.handlers.get(e)}getValidator(e){return this.validators.get(e)}}var BEe=a.looseObject({deduplicationKey:a.string().optional()});class f_{findDuplicate(e,t,n){if(!t||t==="none")return null;let r=this.filterByDeduplicationKey(e,n).sort((i,s)=>s.createdAt-i.createdAt||s.id.localeCompare(i.id)),o=r.find((i)=>i.status===je.PENDING)??null;if(t==="skip"||t==="replace")return o;return o??r[0]??null}filterByDeduplicationKey(e,t){if(!t)return e;return e.filter((n)=>{let r=BEe.safeParse(n.metadata);return r.success&&r.data.deduplicationKey===t})}}var qEe=2000,ZEe=5,$Ee=40,UEe=new aD;class g_{db;transactionClient;databaseUrl;logger;deduplicator=new f_;writeRetryBudgetMs;constructor(e,t,n,r,o){this.db=e,this.transactionClient=t,this.databaseUrl=n,this.logger=r.child("JobQueueRepository"),this.writeRetryBudgetMs=o?.writeRetryBudgetMs??qEe}async insert(e){await this.write("insert",async()=>this.db.insert(G).values(e))}async enqueueAtomic(e){return UEe.run(this.databaseUrl,async()=>{let t=Date.now()+this.writeRetryBudgetMs;return this.attemptEnqueue(e,t,1)})}async attemptEnqueue(e,t,n){let r=await this.runEnqueueTransaction(e,t,n);if(r.retry)return this.attemptEnqueue(e,t,n+1);return r.decision}async runEnqueueTransaction(e,t,n){let r=await this.acquireWriteTransaction(e,t),o={prepared:!1},i=!1;try{let s=await this.decideEnqueue(r,e,()=>{o.prepared=!0});return i=!0,await r.commit(),{retry:!1,decision:s}}catch(s){let c=i&&this.isSerializationConflict(s)&&!r.closed,l=!0;if(!r.closed)try{await r.rollback()}catch(u){l=!1,this.logger.error("Failed to roll back atomic enqueue",{type:e.jobData.type,rollbackError:u})}if(o.prepared)e.onInsertRollback?.();if(!c||!l)throw s;return await this.waitForConflictRetry("commit",e,t,n,s),{retry:!0}}finally{r.close()}}async decideEnqueue(e,t,n){let{jobData:r,strategy:o,deduplicationKey:i,beforeInsert:s}=t,c=o??"none",l=async()=>{await s?.(),n()},u=async()=>{await l(),await this.insertJob(e,r)};if(c==="none")return await u(),{kind:"inserted",jobId:r.id};let p=await this.getActiveDeduplicationCandidates(e,r.type),d=this.deduplicator.findDuplicate(p,c,i);if(!d)return await u(),{kind:"inserted",jobId:r.id};if(c==="skip")return{kind:"skipped",jobId:d.id};if(c==="coalesce"){if((await e.execute({sql:"UPDATE `job_queue` SET `scheduledFor` = ? WHERE `id` = ? AND `status` = ?",args:[Date.now(),d.id,d.status]})).rowsAffected!==1)throw Error(`Atomic coalesce lost selected job ${d.id}`);return{kind:"coalesced",jobId:d.id}}await l();let g=Date.now();if((await e.execute({sql:"UPDATE `job_queue`\n SET `status` = ?,\n `lastError` = ?,\n `completedAt` = ?,\n `runtimeUpdatedAt` = max(?, coalesce((SELECT max(`runtimeUpdatedAt`) FROM `job_queue`), 0) + 1)\n WHERE `id` = ? AND `status` = ?",args:[je.FAILED,"Replaced by newer job",g,g,d.id,je.PENDING]})).rowsAffected!==1)throw Error(`Atomic replace lost selected job ${d.id}`);return await this.insertJob(e,r),{kind:"replaced",jobId:r.id,replacedJobId:d.id}}async getActiveDeduplicationCandidates(e,t){return(await e.execute({sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ? AND `status` IN (?, ?)",args:[t,je.PENDING,je.PROCESSING]})).rows.map((r)=>this.parseDeduplicationCandidate(r))}parseDeduplicationCandidate(e){let{id:t,status:n,createdAt:r,metadata:o}=e;if(typeof t!=="string"||n!==je.PENDING&&n!==je.PROCESSING||typeof r!=="number"&&typeof r!=="bigint"||typeof o!=="string")throw Error("Invalid active job row returned during atomic enqueue");let i=JSON.parse(o);return{id:t,status:n,createdAt:Number(r),metadata:i}}async insertJob(e,t){if((await e.execute({sql:"INSERT INTO `job_queue` (\n `id`, `type`, `data`, `result`, `source`, `metadata`,\n `status`, `priority`, `retryCount`, `maxRetries`,\n `lastError`, `createdAt`, `scheduledFor`, `startedAt`,\n `completedAt`\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",args:[t.id,t.type,t.data,this.serializeJson(t.result),t.source,JSON.stringify(t.metadata),t.status,t.priority,t.retryCount,t.maxRetries,t.lastError,t.createdAt,t.scheduledFor,t.startedAt,t.completedAt]})).rowsAffected!==1)throw Error(`Atomic enqueue did not insert job ${t.id}`)}serializeJson(e){if(e===void 0||e===null)return null;return JSON.stringify(e)}acquireWriteTransaction(e,t){return this.retryOnConflict("acquire",e,()=>this.transactionClient.transaction("write"),(n)=>this.isSerializationConflict(n),t)}async waitForConflictRetry(e,t,n,r,o){let i=Math.min(ZEe*2**(r-1),$Ee),s=i/2+Math.random()*(i/2);if(Date.now()+s>=n)throw this.transactionConflictError(e,t,r,o);await new Promise((c)=>setTimeout(c,s))}async retryOnConflict(e,t,n,r,o=Date.now()+this.writeRetryBudgetMs,i=1){try{return await n()}catch(s){if(!r(s))throw s;return await this.waitForConflictRetry(e,t,o,i,s),this.retryOnConflict(e,t,n,r,o,i+1)}}transactionConflictError(e,t,n,r){if(typeof t==="string")return Error(`Failed job queue write "${t}" within ${this.writeRetryBudgetMs}ms after ${n} attempts`,{cause:r});let o=t.strategy??"none",i=t.deduplicationKey?"present":"absent";return Error(`Failed to ${e} atomic enqueue transaction for type "${t.jobData.type}" within ${this.writeRetryBudgetMs}ms after ${n} attempts (strategy: ${o}, key: ${i})`,{cause:r})}write(e,t){return this.retryOnConflict("write",e,t,(n)=>{let r=new Set;for(let o=n;o!==void 0&&!r.has(o);){if(r.add(o),typeof o==="object"&&o!==null&&"code"in o&&/^SQLITE_(?:BUSY|LOCKED)(?:_|$)/u.test(String(o.code)))return!0;o=o instanceof Error?o.cause:void 0}return!1})}isSerializationConflict(e){for(let t=e;t!==void 0;){let n=typeof t==="object"&&t!==null&&"code"in t?String(t.code):"",r=Ke(t,"");if(/SQLITE_(?:BUSY|LOCKED)/u.test(n)||/SQLITE_(?:BUSY|LOCKED)|database is locked|transaction (?:busy|conflict)/iu.test(r))return!0;t=t instanceof Error?t.cause:void 0}return!1}async startWorkerSession(e,t,n=Date.now(),r=Ka){let o=n+r;await this.write("start worker session",async()=>this.db.insert(Ut).values({slotId:e,sessionId:t,startedAt:n,heartbeatAt:n,expiresAt:o}).onConflictDoUpdate({target:Ut.slotId,set:{sessionId:t,startedAt:n,heartbeatAt:n,expiresAt:o}}))}async heartbeatWorkerSession(e,t,n=Date.now(),r=Ka){return(await this.write("heartbeat worker session",async()=>this.db.update(Ut).set({heartbeatAt:n,expiresAt:n+r}).where(oe(O(Ut.slotId,e),O(Ut.sessionId,t))).returning({slotId:Ut.slotId}))).length===1}async endWorkerSession(e,t){return(await this.write("end worker session",async()=>this.db.delete(Ut).where(oe(O(Ut.slotId,e),O(Ut.sessionId,t))).returning({slotId:Ut.slotId}))).length===1}async complete(e,t,n){let r=Date.now(),i=(await this.write("complete",async()=>this.db.update(G).set({status:je.COMPLETED,result:t,lastError:null,completedAt:r,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(r)}).where(this.attemptWriteGuard(e,n)).returning({id:G.id}))).length===1;if(i)this.logger.debug("Job completed",{jobId:e,hasResult:t!==void 0});return i}async update(e,t,n){let o=(await this.write("update",async()=>this.db.update(G).set({data:JSON.stringify(t)}).where(this.attemptWriteGuard(e,n)).returning({id:G.id}))).length===1;if(o)this.logger.debug("Job data updated",{jobId:e});return o}async recordAttemptProgress(e,t,n,r=Date.now()){return(await this.write("record progress",async()=>this.db.update(G).set({attemptHeartbeatAt:r,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(r),progress:n}).where(this.attemptWriteGuard(e,t)).returning({id:G.id}))).length===1}async renewAttemptLease(e,t,n,r){return(await this.write("renew attempt lease",async()=>this.db.update(G).set({attemptHeartbeatAt:n,leaseExpiresAt:n+r}).where(this.attemptWriteGuard(e,t)).returning({id:G.id}))).length===1}async fail(e,t,n,r=Date.now()){let i=(await this.db.select({retryCount:G.retryCount,maxRetries:G.maxRetries,type:G.type,scheduledFor:G.scheduledFor,startedAt:G.startedAt,runtimeUpdatedAt:G.runtimeUpdatedAt}).from(G).where(this.attemptWriteGuard(e,n)).limit(1))[0];if(!i)return!1;let s=i.retryCount<i.maxRetries,c=s?i.retryCount+1:i.retryCount,l=Math.min(1000*2**i.retryCount,60000),u=s?r+l:i.scheduledFor;if((await this.write("fail",async()=>this.db.update(G).set({status:s?je.PENDING:je.FAILED,retryCount:c,lastError:t.message,scheduledFor:u,completedAt:s?null:r,runtimeUpdatedAt:s?i.runtimeUpdatedAt:this.nextRuntimeUpdatedAt(r),startedAt:s?null:i.startedAt,attemptId:null,workerSlotId:null,workerSessionId:null,leaseExpiresAt:null,attemptHeartbeatAt:null}).where(oe(this.attemptWriteGuard(e,n),O(G.retryCount,i.retryCount))).returning({id:G.id}))).length!==1)return!1;if(s)this.logger.debug("Job scheduled for retry",{jobId:e,retryCount:c,backoffMs:l,scheduledFor:new Date(u).toISOString()});else this.logger.error("Job failed after max retries",{jobId:e,type:i.type,retryCount:i.retryCount,error:t.message});return!0}async retireUnownedActiveJob(e){let t=e.reason.trim();if(t.length===0)throw Error("Retired job reason must not be empty");let r=(await this.write("retire unowned job",async()=>this.db.update(G).set({status:je.FAILED,lastError:t,completedAt:e.now,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(e.now)}).where(oe(O(G.id,e.jobId),O(G.type,e.expectedType),fr(O(G.status,je.PENDING),O(G.status,je.PROCESSING)),rr(G.attemptId),rr(G.workerSlotId),rr(G.workerSessionId),rr(G.leaseExpiresAt),rr(G.attemptHeartbeatAt),rr(G.progress),rr(G.result))).returning()))[0]??null;if(r)this.logger.warn("Retired unowned legacy job",{jobId:r.id,type:r.type,reason:t});return r}async getStatus(e){return(await this.db.select().from(G).where(O(G.id,e)).limit(1))[0]??null}async getJobsByRootJobId(e){return this.db.select().from(G).where(x`json_extract(${G.metadata}, '$.rootJobId') = ${e}`).orderBy(st(G.createdAt),st(G.id))}async getStatusByEntityId(e){return(await this.db.select().from(G).where(x`json_extract(${G.data}, '$.id') = ${e}`).orderBy(dn(G.createdAt)).limit(1))[0]??null}async getStats(){let e=await this.db.select({status:G.status,count:x`count(*)`}).from(G).groupBy(G.status),t={pending:0,processing:0,failed:0,completed:0,total:0};for(let n of e){let r=Number(n.count);t[n.status]=r,t.total+=r}return t}async getDiagnostics(e=Date.now()){let[t,n,r]=await Promise.all([this.db.select({type:G.type,status:G.status,count:x`count(*)`}).from(G).groupBy(G.type,G.status),this.db.select({oldestPendingAt:x`min(case when ${G.status} = ${je.PENDING} then ${G.createdAt} end)`,duePending:x`coalesce(sum(case when ${G.status} = ${je.PENDING} and ${G.scheduledFor} <= ${e} then 1 else 0 end), 0)`,oldestDuePendingAt:x`min(case when ${G.status} = ${je.PENDING} and ${G.scheduledFor} <= ${e} then ${G.scheduledFor} end)`,latestClaimAt:x`max(${G.startedAt})`,oldestProcessingAt:x`min(case when ${G.status} = ${je.PROCESSING} then ${G.startedAt} end)`,staleLeaseCount:x`coalesce(sum(case when ${G.status} = ${je.PROCESSING} and ${G.leaseExpiresAt} is not null and ${G.leaseExpiresAt} <= ${e} then 1 else 0 end), 0)`}).from(G),this.db.select({total:x`count(*)`,active:x`coalesce(sum(case when ${Ut.expiresAt} > ${e} then 1 else 0 end), 0)`,stale:x`coalesce(sum(case when ${Ut.expiresAt} <= ${e} then 1 else 0 end), 0)`,latestHeartbeatAt:x`max(${Ut.heartbeatAt})`}).from(Ut)]),o={pending:0,processing:0,completed:0,failed:0},i=t.map((u)=>{let p=Number(u.count);return o[u.status]+=p,{type:u.type,status:u.status,count:p}}),s=n[0],c=r[0],l=(u)=>u===null||u===void 0?null:Math.max(0,e-Number(u));return{totals:o,byType:i,oldestPendingAgeMs:l(s?.oldestPendingAt),duePending:Number(s?.duePending??0),oldestDuePendingAgeMs:l(s?.oldestDuePendingAt),latestClaimAgeMs:l(s?.latestClaimAt),oldestProcessingAgeMs:l(s?.oldestProcessingAt),staleLeaseCount:Number(s?.staleLeaseCount??0),workerSessions:{total:Number(c?.total??0),active:Number(c?.active??0),stale:Number(c?.stale??0),latestHeartbeatAgeMs:l(c?.latestHeartbeatAt)}}}async getRuntimeUpdates(e,t){return(await this.db.select().from(G).where(x`(${G.runtimeUpdatedAt}, ${G.id}) > (${e.updatedAt}, ${e.jobId})`).orderBy(st(G.runtimeUpdatedAt),st(G.id)).limit(t)).map((r)=>({job:r,cursor:{updatedAt:r.runtimeUpdatedAt??0,jobId:r.id}}))}async cleanup(e){let t=Date.now()-e;return(await this.write("cleanup",async()=>this.db.delete(G).where(oe(fr(O(G.status,je.COMPLETED),O(G.status,je.FAILED)),Hr(G.completedAt,t))))).rowsAffected}async getActiveJobs(e){let t=fr(O(G.status,je.PENDING),O(G.status,je.PROCESSING)),n=e&&e.length>0?oe(t,It(G.type,e)):t;return this.db.select().from(G).where(n).orderBy(dn(G.createdAt))}async getRecentJobs(e,t=20){let n=e&&e.length>0?It(G.type,e):void 0;return this.db.select().from(G).where(n).orderBy(dn(G.createdAt)).limit(t)}async getFailedJobs(e){let t=O(G.status,je.FAILED),n=e&&e.length>0?oe(t,It(G.type,e)):t;return this.db.select().from(G).where(n).orderBy(dn(G.createdAt))}async claimNextReady(e){let{now:t,attemptId:n,workerSlotId:r,workerSessionId:o,leaseDurationMs:i,executableTypes:s}=e,c=this.db.select({slotId:Ut.slotId}).from(Ut).where(oe(O(Ut.slotId,r),O(Ut.sessionId,o),qa(Ut.expiresAt,t))),l=this.db.select({slotId:Ut.slotId}).from(Ut).where(oe(O(Ut.slotId,G.workerSlotId),O(Ut.sessionId,G.workerSessionId))),u=oe(O(G.status,je.PROCESSING),fr(rr(G.attemptId),iT(l),Hr(G.leaseExpiresAt,t))),p=x`${G.status} = ${je.PROCESSING} AND ${G.retryCount} + 1 > ${G.maxRetries}`,d=this.db.select({id:G.id}).from(G).where(oe(It(G.type,s),fr(oe(O(G.status,je.PENDING),Hr(G.scheduledFor,t)),u))).orderBy(st(G.priority),st(G.createdAt)).limit(1),f=(await this.write("claim",async()=>this.db.update(G).set({status:x`CASE WHEN ${p} THEN ${je.FAILED} ELSE ${je.PROCESSING} END`,retryCount:x`CASE WHEN ${G.status} = ${je.PROCESSING} THEN ${G.retryCount} + 1 ELSE ${G.retryCount} END`,lastError:x`CASE WHEN ${G.status} = ${je.PROCESSING} THEN 'Attempt lease expired' ELSE ${G.lastError} END`,startedAt:x`CASE WHEN ${p} THEN ${G.startedAt} ELSE ${t} END`,completedAt:x`CASE WHEN ${p} THEN ${t} ELSE NULL END`,attemptId:x`CASE WHEN ${p} THEN ${G.attemptId} ELSE ${n} END`,workerSlotId:x`CASE WHEN ${p} THEN ${G.workerSlotId} ELSE ${r} END`,workerSessionId:x`CASE WHEN ${p} THEN ${G.workerSessionId} ELSE ${o} END`,leaseExpiresAt:x`CASE WHEN ${p} THEN ${G.leaseExpiresAt} ELSE ${t+i} END`,attemptHeartbeatAt:x`CASE WHEN ${p} THEN ${G.attemptHeartbeatAt} ELSE ${t} END`,runtimeUpdatedAt:x`CASE WHEN ${p} THEN ${this.nextRuntimeUpdatedAt(t)} ELSE ${G.runtimeUpdatedAt} END`}).where(oe(It(G.id,d),Zu(c))).returning()))[0];if(f?.status!==je.PROCESSING)return null;return this.logger.debug("Job claimed",{jobId:f.id,attemptId:f.attemptId,workerSlotId:r,workerSessionId:o}),f}nextRuntimeUpdatedAt(e){return x`max(${e}, coalesce((select max(${G.runtimeUpdatedAt}) from ${G}), 0) + 1)`}attemptWriteGuard(e,t){return t?oe(O(G.id,e),O(G.status,je.PROCESSING),O(G.attemptId,t)):oe(O(G.id,e),rr(G.attemptId),fr(O(G.status,je.PENDING),O(G.status,je.PROCESSING)))}}import{AsyncLocalStorage as WEe}from"async_hooks";class xl{storage=new WEe;static createFresh(){return new xl}constructor(){}current(){return this.storage.getStore()}run(e,t,n){if(t.length===0)throw Error("Operation ID must not be empty");let r=Ns.parse(e),o=HEe(r);return this.storage.run(Object.freeze({provenance:o,operationId:t}),n)}}function HEe(e){if(Object.freeze(e.projectionLineage),e.sourceEntity)Object.freeze(e.sourceEntity);return Object.freeze(e)}class h_{client;logger;handlerRegistry;repository;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;inFlightEnqueues=0;databaseUrl;operationContext;projectionAdmission;directWorkerSlotId=`direct:${Pt()}`;directWorkerSessionId=Pt();directLeaseDurationMs;directSessionStart=null;close(){this.closeRequested=!0,this.closeClientWhenReady()}static createFresh(e,t,n){return new h_(e,t??di.getInstance(),n)}constructor(e,t,n){let{db:r,client:o,url:i}=W5(e);this.client=o,this.databaseUrl=i,this.logger=t.child("JobQueueService"),this.operationContext=n?.operationContext??xl.createFresh(),this.projectionAdmission=n?.projectionAdmission,this.handlerRegistry=new m_(this.logger,n?.handlerRegistrationMode??"combined"),this.repository=new g_(r,o,i,this.logger),this.directLeaseDurationMs=e.claimTimeoutMs??300000}initialize(){if(this.closeRequested)return Promise.resolve();return this.walInitialization??=this.initializeWALMode(),this.walInitialization}async initializeWALMode(){try{await Wi(this.client,this.databaseUrl)}catch(e){this.logger.warn("Failed to enable WAL mode (non-fatal)",e)}finally{this.walInitializationSettled=!0,this.closeClientWhenReady()}}closeClientWhenReady(){if(!this.closeRequested||this.inFlightEnqueues>0||this.walInitialization!==null&&!this.walInitializationSettled)return;this.closeClient()}closeClient(){if(this.clientClosed)return;this.clientClosed=!0,this.client.close()}registerHandler(e,t,n){this.handlerRegistry.registerHandler(e,t,n)}unregisterHandler(e){this.handlerRegistry.unregisterHandler(e)}unregisterPluginHandlers(e){this.handlerRegistry.unregisterPluginHandlers(e)}getRegisteredTypes(){return this.handlerRegistry.getRegisteredTypes()}getHandler(e){return this.handlerRegistry.getHandler(e)}getValidator(e){return this.handlerRegistry.getValidator(e)}finalizeHandlerRegistrations(){return this.handlerRegistry.finalizeRegistrations()}getExecutionRegistrations(){return this.handlerRegistry.getExecutionRegistrations()}async enqueue(e){if(this.closeRequested)throw Error("Cannot enqueue a job after the queue service is closed");this.inFlightEnqueues++;try{return await this.enqueueValidated(e)}finally{this.inFlightEnqueues--,this.closeClientWhenReady()}}async enqueueValidated(e){let{type:t,data:n,options:r}=e,o=this.handlerRegistry.getValidator(t);if(!o)throw Error(`No job type declared: ${t}`);let i=o.validateAndParse(n);if(i===null)throw Error(`Invalid job data for type: ${t}`);let s=Date.now(),c=Pt(),l=r?.rootJobId??this.operationContext.current()?.provenance.rootJobId??c,u=this.createJobProvenance(c,l,r),p=r?.metadata??{operationType:"data_processing"},{provenance:d,...g}=p,f={id:c,type:t,data:JSON.stringify(i),status:je.PENDING,priority:r?.priority??0,maxRetries:r?.maxRetries??3,retryCount:0,source:r?.source??null,metadata:{...g,...r?.deduplicationKey&&{deduplicationKey:r.deduplicationKey},rootJobId:l,provenance:u},createdAt:s,scheduledFor:r?.delayMs?s+r.delayMs:s,result:null,lastError:null,startedAt:null,completedAt:null},v,T=()=>{v?.rollback(),v=void 0};try{let E=await this.repository.enqueueAtomic({jobData:f,strategy:r?.deduplication,deduplicationKey:r?.deduplicationKey,beforeInsert:async()=>{v=await this.projectionAdmission?.reserveJobAdmission(u)},onInsertRollback:T});if(v?.commit(),v=void 0,E.kind==="skipped")this.logger.debug("Skipping duplicate job (already pending)",{type:t,existingJobId:E.jobId});else if(E.kind==="coalesced")this.logger.debug("Coalescing with existing job",{type:t,existingJobId:E.jobId});else{if(E.kind==="replaced")this.logger.debug("Replacing duplicate job",{type:t,oldJobId:E.replacedJobId});this.logger.debug("Job enqueued",{id:E.jobId,type:t,priority:f.priority,rootJobId:f.metadata.rootJobId})}return E.jobId}catch(E){throw T(),this.logger.error("Failed to enqueue job",{type:t,error:Ke(E)}),E}}createJobProvenance(e,t,n){let r=this.operationContext.current(),o=n?.metadata.provenance??r?.provenance,i=o?.rootJobId===t?o:void 0,s=r?.provenance.rootJobId===t?r.operationId:void 0,c=n?.projection,l=c?[...i?.projectionLineage??[],c.id]:[...i?.projectionLineage??[]],u=c?.id??i?.projectionId;return Ns.parse({rootJobId:t,causationId:s??i?.causationId??e,...u?{projectionId:u}:{},projectionLineage:l,...c?.sourceEntity?{sourceEntity:c.sourceEntity}:i?.sourceEntity?{sourceEntity:i.sourceEntity}:{},derivationDepth:l.length})}async dequeue(e){let t=this.handlerRegistry.getRegisteredTypes();if(t.length===0)return null;let n=e??await this.getDirectClaimOptions(),r=Date.now(),o=await this.repository.claimNextReady({...n,now:r,attemptId:Pt(),executableTypes:t});if(!o)return null;return this.logger.debug("Job dequeued",{id:o.id,type:o.type,priority:o.priority,retryCount:o.retryCount,attemptId:o.attemptId,workerSlotId:o.workerSlotId,workerSessionId:o.workerSessionId}),o}async startWorkerSession(e,t,n=Ka){await this.repository.startWorkerSession(e,t,Date.now(),n)}heartbeatWorkerSession(e,t,n=Ka){return this.repository.heartbeatWorkerSession(e,t,Date.now(),n)}endWorkerSession(e,t){return this.repository.endWorkerSession(e,t)}renewAttemptLease(e,t,n){return this.repository.renewAttemptLease(e,t,Date.now(),n)}recordAttemptProgress(e,t,n){return this.repository.recordAttemptProgress(e,t,n)}complete(e,t,n){return this.repository.complete(e,t,n)}update(e,t,n){return this.repository.update(e,t,n)}fail(e,t,n){return this.repository.fail(e,t,n)}retireUnownedActiveJob(e){return this.repository.retireUnownedActiveJob(e)}async getDirectClaimOptions(){return this.directSessionStart??=this.repository.startWorkerSession(this.directWorkerSlotId,this.directWorkerSessionId,Date.now(),this.directLeaseDurationMs),await this.directSessionStart,{workerSlotId:this.directWorkerSlotId,workerSessionId:this.directWorkerSessionId,leaseDurationMs:this.directLeaseDurationMs}}async getStatus(e){return this.repository.getStatus(e)}async getJobsByRootJobId(e){return this.repository.getJobsByRootJobId(e)}async getStatusByEntityId(e){return this.repository.getStatusByEntityId(e)}async getStats(){return this.repository.getStats()}getDiagnostics(e){return this.repository.getDiagnostics(e)}async waitForIdle(e={}){let t=e.quietMs??250,n=e.pollIntervalMs??25,r=Date.now()+(e.timeoutMs??30000),o=async(i)=>{e.signal?.throwIfAborted();let{totals:s}=await this.getDiagnostics(),l=s.pending===0&&s.processing===0?i??Date.now():null;if(l!==null&&Date.now()-l>=t)return;if(Date.now()>=r)throw Error(`Timed out waiting for the job queue to settle: ${s.pending} pending, ${s.processing} processing`);return await Bun.sleep(n),o(l)};return o(null)}getRuntimeUpdates(e,t=1000){return this.repository.getRuntimeUpdates(e,t)}async cleanup(e){let t=await this.repository.cleanup(e);if(t>0)this.logger.info("Cleaned up old jobs",{deletedCount:t,olderThanMs:e});return t}async getActiveJobs(e){return this.repository.getActiveJobs(e)}async getRecentJobs(e,t){return this.repository.getRecentJobs(e,t)}async getFailedJobs(e){return this.repository.getFailedJobs(e)}}class H5 extends Error{constructor(e,t){super(`Job ${e} exceeded its ${t}ms execution deadline`);this.name="JobDeadlineExceededError"}}class y_{logger;jobQueueService;progressMonitor;config;isRunning=!1;shouldStop=!1;activeJobs=new Set;stats;startTime=0;pollFiber=null;currentPoll=null;workerScope=null;jobFibers=null;activeTransition=null;transitionQueue=[];clock;operationContext;projectionBatchScope;workerSessionId=null;workerHeartbeatStop=null;static createFresh(e,t,n,r,o){return new y_(e,t,n,r,o)}constructor(e,t,n,r,o){if(this.logger=n.child("JobQueueWorker"),this.jobQueueService=e,this.progressMonitor=t,this.clock=o?.clock,this.operationContext=o?.operationContext??xl.createFresh(),this.projectionBatchScope=o?.projectionBatchScope,this.config={concurrency:r?.concurrency??1,pollInterval:r?.pollInterval??1000,maxJobs:r?.maxJobs??0,autoStart:r?.autoStart??!1,workerSlotId:r?.workerSlotId??process.env.BRAIN_JOB_WORKER_SLOT_ID??"default",defaultExecutionTimeoutMs:r?.defaultExecutionTimeoutMs??300000,cancellationGraceMs:r?.cancellationGraceMs??5000,errorCallbackTimeoutMs:r?.errorCallbackTimeoutMs??1e4,leaseDurationMs:r?.leaseDurationMs??30000,attemptHeartbeatIntervalMs:r?.attemptHeartbeatIntervalMs??1e4,workerHeartbeatIntervalMs:r?.workerHeartbeatIntervalMs??5000,workerSessionTimeoutMs:r?.workerSessionTimeoutMs??Ka,onUnhealthy:r?.onUnhealthy??(()=>{return})},this.stats={processedJobs:0,failedJobs:0,activeJobs:0,uptime:0,isRunning:!1,isHealthy:!0},this.logger.debug("JobQueueWorker initialized",{concurrency:this.config.concurrency,pollInterval:this.config.pollInterval,maxJobs:this.config.maxJobs,autoStart:this.config.autoStart}),this.config.autoStart)this.start().catch((i)=>{this.logger.error("Failed to auto-start JobQueueWorker",{error:i})})}start(){return this.requestTransition("start",!0)}async startWorker(){if(this.isRunning){this.logger.warn("Worker is already running");return}this.logger.debug("Starting JobQueueWorker");let e=Pt();await this.jobQueueService.startWorkerSession(this.config.workerSlotId,e,this.config.workerSessionTimeoutMs),this.workerSessionId=e,this.isRunning=!0,this.shouldStop=!1,this.startTime=Date.now(),this.stats.isRunning=!0,this.stats.isHealthy=!0,delete this.stats.unhealthyReason,this.startWorkerHeartbeat(),this.workerScope=de.runSync(Xt.make()),this.jobFibers=de.runSync(Xt.extend(Ur.make(),this.workerScope)),this.pollFiber=de.runFork(this.runPollingLoop())}stop(){return this.requestTransition("stop",!0)}async stopWorker(e){if(!this.isRunning){this.logger.warn("Worker is not running");return}if(this.logger.debug("Stopping JobQueueWorker"),this.shouldStop=!0,e.awaitInFlightPoll&&this.pollFiber){let n=this.pollFiber;await de.runPromise(ii.interrupt(n)),this.pollFiber=null}if(e.awaitInFlightPoll&&this.currentPoll)await this.currentPoll,this.currentPoll=null;if(this.jobFibers)this.logger.debug("Waiting for active jobs to complete",{activeJobs:this.activeJobs.size}),await de.runPromise(Ur.awaitEmpty(this.jobFibers));await this.closeWorkerScope(),await this.stopWorkerHeartbeat();let t=this.workerSessionId;if(this.workerSessionId=null,t)await this.jobQueueService.endWorkerSession(this.config.workerSlotId,t);this.isRunning=!1,this.stats.isRunning=!1,this.logger.debug("JobQueueWorker stopped")}getStats(){return{...this.stats,activeJobs:this.activeJobs.size,uptime:this.isRunning?Date.now()-this.startTime:0}}isWorkerRunning(){return this.isRunning}isStopRequested(){return this.shouldStop}async processAvailableJobs(){if(!this.isRunning||this.shouldStop)return;try{let e=this.config.concurrency-this.activeJobs.size;if(e<=0)return;if(this.config.maxJobs>0){let n=this.stats.processedJobs+this.stats.failedJobs,r=this.config.maxJobs-n-this.activeJobs.size;if(r<=0){this.logger.debug("Maximum job limit reached, stopping worker",{maxJobs:this.config.maxJobs,processedJobs:this.stats.processedJobs,failedJobs:this.stats.failedJobs}),await this.requestTransition("stop",!1);return}e=Math.min(e,r)}let t=this.jobFibers;if(!t)throw Error("Worker job fiber scope is not available");for(let n=0;n<e;n++){if(this.isStopRequested())break;let r=this.workerSessionId;if(!r)throw Error("Worker session is not available");let o=await this.jobQueueService.dequeue({workerSlotId:this.config.workerSlotId,workerSessionId:r,leaseDurationMs:this.config.leaseDurationMs});if(!o)break;this.activeJobs.add(o.id),await de.runPromise(Ur.run(t,o.id,de.promise(()=>this.processJobWrapper(o))))}}catch(e){this.logger.error("Error processing available jobs",{error:e}),this.stats.lastError=Ke(e)}}async processJobWrapper(e){let t=e.id;try{this.logger.debug("Processing job",{jobId:t,type:e.type,priority:e.priority,retryCount:e.retryCount});let n=await this.processJob(e);if(n.status==="completed")this.stats.processedJobs++,this.logger.debug("Job completed successfully",{jobId:t,type:n.type});else this.stats.failedJobs++,this.logger.warn("Job failed",{jobId:t,type:n.type,error:n.error})}catch(n){this.stats.failedJobs++,this.logger.error("Error processing job",{jobId:t,type:e.type,error:n}),this.stats.lastError=Ke(n)}finally{this.activeJobs.delete(t)}}runPollingLoop(){let t=de.suspend(()=>{if(!this.isWorkerRunning()||this.isStopRequested())return de.interrupt;return this.currentPoll=this.processAvailableJobs(),de.promise(()=>this.currentPoll??Promise.resolve()).pipe(de.andThen(de.suspend(()=>(this.currentPoll=null,!this.isWorkerRunning()||this.isStopRequested()?de.interrupt:de.void))))}).pipe(de.schedule(ws.spaced(this.config.pollInterval)),de.asVoid);return(this.clock?de.withClock(t,this.clock):t).pipe(de.ensuring(de.sync(()=>{this.pollFiber=null})))}requestTransition(e,t){let n=this.transitionQueue.at(-1)??this.activeTransition;if(n?.kind===e)return n.promise;let r=()=>{return},o=()=>{return},i=new Promise((c,l)=>{r=c,o=l}),s={kind:e,awaitInFlightPoll:t,promise:i,resolve:r,reject:o};return this.transitionQueue.push(s),this.runNextTransition(),i}runNextTransition(){if(this.activeTransition)return;let e=this.transitionQueue.shift();if(!e)return;this.activeTransition=e,(e.kind==="start"?this.startWorker():this.stopWorker({awaitInFlightPoll:e.awaitInFlightPoll})).then(()=>this.completeTransition(e,!0),(n)=>this.completeTransition(e,!1,n))}completeTransition(e,t,n){if(this.activeTransition!==e)return;if(this.activeTransition=null,t)e.resolve();else e.reject(n);queueMicrotask(()=>this.runNextTransition())}async closeWorkerScope(){let e=this.workerScope;if(this.workerScope=null,this.jobFibers=null,e)await de.runPromise(Xt.close(e,jt.void))}startHeartbeatLoop(e){let t=null,n=!1,r=setInterval(()=>{if(n||t)return;t=e.beat().then((o)=>{if(!o)e.onStale()}).catch(e.onError).finally(()=>{t=null})},Math.max(1,e.intervalMs));return async()=>{if(n)return;n=!0,clearInterval(r),await t}}startWorkerHeartbeat(){this.workerHeartbeatStop=this.startHeartbeatLoop({intervalMs:this.config.workerHeartbeatIntervalMs,beat:async()=>{let e=this.workerSessionId;if(!e)return!0;return this.jobQueueService.heartbeatWorkerSession(this.config.workerSlotId,e,this.config.workerSessionTimeoutMs)},onStale:()=>this.markUnhealthy("Worker session was superseded"),onError:(e)=>this.markUnhealthy(`Worker session heartbeat failed: ${Ke(e)}`)})}async stopWorkerHeartbeat(){await this.workerHeartbeatStop?.(),this.workerHeartbeatStop=null}startAttemptHeartbeat(e,t){let n=e.attemptId;if(!n)return async()=>{return};return this.startHeartbeatLoop({intervalMs:this.config.attemptHeartbeatIntervalMs,beat:()=>this.jobQueueService.renewAttemptLease(e.id,n,this.config.leaseDurationMs),onStale:()=>{let r=Error("Job attempt was superseded");t.abort(r),this.markUnhealthy(r.message)},onError:(r)=>{let o=Pm(r);t.abort(o),this.markUnhealthy(`Attempt lease heartbeat failed: ${o.message}`)}})}markUnhealthy(e){if(!this.stats.isHealthy)return;this.stats.isHealthy=!1,this.stats.unhealthyReason=e,this.stats.lastError=e,this.shouldStop=!0,this.logger.error("Job queue worker is unhealthy",{reason:e});try{this.config.onUnhealthy(e)}catch(t){this.logger.error("Job queue worker unhealthy callback failed",{reason:e,error:Ke(t)})}}async raceOutcome(e,t){let n,r=new Promise((o)=>{n=setTimeout(()=>o({kind:"timeout"}),Math.max(1,t))});try{return await Promise.race([e,r])}finally{if(n)clearTimeout(n)}}async executeWithDeadline(e,t,n,r){let o=Promise.resolve().then(r).then((l)=>({kind:"success",value:l}),(l)=>({kind:"failure",error:l})),i=await this.raceOutcome(o,t);if(i.kind!=="timeout"){if(i.kind==="failure")throw i.error;return i.value}let s=new H5(e,t);if(n.abort(s),(await this.raceOutcome(o,this.config.cancellationGraceMs)).kind!=="timeout")throw s;throw this.markUnhealthy(`${s.message}; handler ignored cancellation grace`),await o,s}processJob(e){let t=e.metadata.provenance??{rootJobId:e.metadata.rootJobId,causationId:e.id,projectionLineage:[],derivationDepth:0};return this.operationContext.run(t,e.id,()=>{let n=this.projectionBatchScope;return n?n.runFreshBatchScope(()=>this.processJobWithinContext(e)):this.processJobWithinContext(e)})}async processJobWithinContext(e){let t=e.attemptId;if(!t){let c=Error(`Claimed job ${e.id} has no attempt fencing token`);return this.markUnhealthy(c.message),{jobId:e.id,type:e.type,status:je.FAILED,error:c.message}}let n=this.jobQueueService.getHandler(e.type);if(!n){let c=Error(`No handler registered for job type: ${e.type}`);return await this.jobQueueService.fail(e.id,c,t),{jobId:e.id,type:e.type,status:je.FAILED,error:c.message}}let r=new AbortController,o=this.startAttemptHeartbeat(e,r),i=!1,s=async()=>{if(i)return;i=!0,await o()};try{this.logger.debug("Processing job",{jobId:e.id,type:e.type,attemptId:t});let c=JSON.parse(e.data),l=n.validateAndParse(c);if(l===null)throw Error(`Invalid job data for type: ${e.type}`);let u=this.progressMonitor.createProgressReporter(e.id,t),p=n.executionTimeoutMs??this.config.defaultExecutionTimeoutMs,d=await this.executeWithDeadline(e.type,p,r,()=>n.process(l,e.id,u,r.signal));await s();let g=d_.safeParse(d);if(g.success){let v=g.data.error??"Handler returned failure",T=Error(v);if(await this.jobQueueService.fail(e.id,T,t))await this.emitTerminalFailure(e,T,n,t);return{jobId:e.id,type:e.type,status:je.FAILED,error:v}}if(!await this.jobQueueService.complete(e.id,d,t))return{jobId:e.id,type:e.type,status:je.FAILED,error:"Job attempt no longer owns the claim"};return await this.runHandlerSuccessCallback(n,e,t),await this.progressMonitor.handleJobStatusChange(e.id,"completed",e.metadata),{jobId:e.id,type:e.type,status:je.COMPLETED,result:d}}catch(c){let l=Pm(c);if(await s(),await this.runHandlerErrorCallback("onError",n,e,l,t),await this.jobQueueService.fail(e.id,l,t))await this.emitTerminalFailure(e,l,n,t);return{jobId:e.id,type:e.type,status:je.FAILED,error:l.message}}}async runHandlerSuccessCallback(e,t,n){let r=e.onTerminalSuccess;if(!r)return;try{let o=e.validateAndParse(JSON.parse(t.data));if(o===null)return;let i=this.progressMonitor.createProgressReporter(t.id,n),s=new AbortController;await this.executeWithDeadline(`${t.type}:onTerminalSuccess`,this.config.errorCallbackTimeoutMs,s,()=>r.call(e,o,t.id,i,s.signal))}catch(o){this.logger.error("Terminal job success callback failed",{jobId:t.id,type:t.type,error:o})}}async emitTerminalFailure(e,t,n,r){if((await this.jobQueueService.getStatus(e.id))?.status!==je.FAILED)return;await this.runHandlerErrorCallback("onTerminalError",n,e,t,r),await this.progressMonitor.handleJobStatusChange(e.id,"failed",e.metadata)}async runHandlerErrorCallback(e,t,n,r,o){let i=t[e];if(!i)return;try{let s=t.validateAndParse(JSON.parse(n.data));if(s===null)return;let c=this.progressMonitor.createProgressReporter(n.id,o),l=new AbortController;await this.executeWithDeadline(`${n.type}:${e}`,this.config.errorCallbackTimeoutMs,l,()=>i.call(t,r,s,n.id,c,l.signal))}catch(s){this.logger.error(e==="onError"?"Job handler error callback failed":"Job handler terminal error callback failed",{jobId:n.id,error:s})}}}var JEe=86400000,J5=3600000;class b_{jobQueue;logger;batches=new Map;cleanupFiber=null;cleanupSupervisor=null;inFlightCleanups=new Set;activeTransition=null;transitionQueue=[];acceptingCleanup=!0;clock;static createFresh(e,t,n){return new b_(e,t,n)}constructor(e,t,n){this.jobQueue=e,this.logger=t,this.clock=n?.clock}start(e=J5){return this.requestTransition("start",e)}stop(){return this.requestTransition("stop",J5)}async startCleanup(e){if(this.acceptingCleanup=!0,this.cleanupFiber)return;this.cleanupFiber=de.runFork(this.runCleanupLoop(e))}runCleanupLoop(e){let t=this.cleanupTerminalBatchMetadata().pipe(de.schedule(ws.spaced(e)),de.asVoid);return this.clock?de.withClock(t,this.clock):t}scheduleTerminalBatchCleanup(){if(!this.acceptingCleanup)return;this.cleanupSupervisor??=this.createCleanupSupervisor();let e=de.runFork(this.cleanupTerminalBatchMetadata());Nu.unsafeAdd(this.cleanupSupervisor.fibers,e)}async stopCleanup(){this.acceptingCleanup=!1;let e=this.cleanupFiber;if(this.cleanupFiber=null,e)await de.runPromise(ii.interrupt(e));let t=this.cleanupSupervisor;if(t)await de.runPromise(Nu.awaitEmpty(t.fibers));while(this.inFlightCleanups.size>0)await Promise.allSettled(this.inFlightCleanups);if(t)await de.runPromise(Xt.close(t.scope,jt.void)),this.cleanupSupervisor=null}requestTransition(e,t){let n=this.transitionQueue.at(-1)??this.activeTransition;if(n?.kind===e)return n.promise;let r=()=>{return},o=()=>{return},i=new Promise((c,l)=>{r=c,o=l}),s={kind:e,intervalMs:t,promise:i,resolve:r,reject:o};return this.transitionQueue.push(s),this.runNextTransition(),i}runNextTransition(){if(this.activeTransition)return;let e=this.transitionQueue.shift();if(!e)return;this.activeTransition=e,(e.kind==="start"?this.startCleanup(e.intervalMs):this.stopCleanup()).then(()=>this.completeTransition(e,!0),(n)=>this.completeTransition(e,!1,n))}completeTransition(e,t,n){if(this.activeTransition!==e)return;if(this.activeTransition=null,t)e.resolve();else e.reject(n);queueMicrotask(()=>this.runNextTransition())}createCleanupSupervisor(){let e=de.runSync(Xt.make()),t=de.runSync(Xt.extend(Nu.make(),e));return{scope:e,fibers:t}}cleanupTerminalBatchMetadata(){return de.tryPromise({try:()=>{let e=this.cleanup(JEe);return this.inFlightCleanups.add(e),e.then(()=>this.inFlightCleanups.delete(e),()=>this.inFlightCleanups.delete(e)),e},catch:(e)=>e}).pipe(de.asVoid,de.catchAll((e)=>de.sync(()=>{this.logger.warn("Failed to clean up terminal batch metadata",{error:e})})))}validateOperations(e){for(let t of e){let n=this.jobQueue.getValidator(t.type);if(!n)throw Error(`No job type declared: ${t.type}`);if(n.validateAndParse(t.data)===null)throw Error(`Invalid job data for type: ${t.type}`)}}async enqueueBatch(e,t,n,r){if(e.length===0)throw Error("Cannot enqueue empty batch");this.validateOperations(e);let o=[];this.batches.set(n,{jobIds:o,operations:e,source:t.source,startedAt:new Date().toISOString(),metadata:{...t.metadata,rootJobId:n}});try{for(let i of e){let s={...t,rootJobId:n,metadata:{...t.metadata,operationTarget:i.type}},c=await this.jobQueue.enqueue({type:i.type,data:i.data,options:s});o.push(c)}return this.logger.debug("Enqueued batch operations",{batchId:n,operationCount:e.length,jobIds:o,rootJobId:n}),this.scheduleTerminalBatchCleanup(),n}catch(i){throw this.batches.delete(n),this.logger.error("Failed to enqueue batch operations",{error:i,operationCount:e.length,enqueuedJobs:o.length}),i}}async getBatchStatus(e){let t=this.batches.get(e);if(!t)return null;try{let n=await Promise.all(t.jobIds.map((u)=>this.jobQueue.getStatus(u))),r=0,o=0,i=0,s=[];for(let[u,p]of n.entries()){if(!p){o++;let d=t.operations[u],g=t.jobIds[u]??"unknown";s.push(`Missing job ${g}${d?` for ${d.type}`:""}`);continue}switch(p.status){case"completed":r++;break;case"failed":if(o++,p.lastError)s.push(p.lastError);break;case"processing":case"pending":i++;break}}i+=t.operations.length-t.jobIds.length;let c;if(i>0)c=je.PROCESSING;else if(o>0)c=je.FAILED;else c=je.COMPLETED;if(t.terminalAt===void 0&&(c===je.COMPLETED||c===je.FAILED))t.terminalAt=Date.now();let l;for(let u=0;u<t.jobIds.length;u++){let p=n[u];if(p&&p.status!=="completed"&&p.status!=="failed"){let d=t.operations[u];if(d)l=`Processing ${d.type}`;break}}return{batchId:e,totalOperations:t.operations.length,completedOperations:r,failedOperations:o,errors:s,status:c,currentOperation:l,metadata:t.metadata}}catch(n){throw this.logger.error("Failed to get batch status",{batchId:e,error:n}),n}}inspectRetention(e){let t=this.batches.get(e);return t?{terminalAt:t.terminalAt}:void 0}async cleanup(e){let t=Date.now()-e,n=0;for(let[r,o]of this.batches.entries()){if(o.terminalAt!==void 0){if(o.terminalAt<=t)this.batches.delete(r),n++;continue}if(new Date(o.startedAt).getTime()<=t){let s=await this.getBatchStatus(r);if(s&&(s.status===je.COMPLETED||s.status===je.FAILED))this.batches.delete(r),n++}}return this.logger.debug("Cleaned up batch metadata",{cleaned:n}),n}registerBatch(e,t,n,r,o){this.batches.set(e,{jobIds:t,operations:n,source:r,startedAt:new Date().toISOString(),metadata:o}),this.logger.debug("Registered batch metadata",{batchId:e,operationCount:n.length,jobIds:t})}async getActiveBatches(){let e=[];try{for(let[t,n]of this.batches){let r=await this.getBatchStatus(t);if(r&&(r.status==="pending"||r.status==="processing"))e.push({batchId:t,status:r,metadata:{operations:n.operations,source:n.source,startedAt:n.startedAt,metadata:n.metadata}})}return this.logger.debug("Retrieved active batches",{count:e.length}),e}catch(t){throw this.logger.error("Failed to get active batches",{error:t}),t}}}var GEe=a.preprocess((e)=>{if(typeof e!=="string")return e;return JSON.parse(e)},a.record(a.string(),a.unknown()));class x_{jobQueueService;messageBus;batchJobManager;logger;mode;pollTimer;pollCursor={updatedAt:0,jobId:""};polling=!1;static createFresh(e,t,n,r,o="combined"){return new x_(e,t,n,r,o)}constructor(e,t,n,r,o){this.jobQueueService=e,this.messageBus=t,this.batchJobManager=n,this.logger=r,this.mode=o}start(){if(this.mode==="durable-reader"&&!this.pollTimer){this.pollCursor={updatedAt:Date.now(),jobId:""},this.pollTimer=setInterval(()=>{this.pollDurableUpdates()},250),this.pollTimer.unref(),this.logger.debug("Job progress monitor ready (durable polling mode)");return}this.logger.debug("Job progress monitor ready (event-driven mode)")}stop(){if(this.pollTimer)clearInterval(this.pollTimer);this.pollTimer=void 0,this.logger.debug("Job progress monitor stopped")}async pollDurableUpdates(){if(this.polling)return;this.polling=!0;try{let e=await this.jobQueueService.getRuntimeUpdates(this.pollCursor,100);for(let t of e)if(this.pollCursor=t.cursor,t.job.status==="processing"&&t.job.progress)await this.publishJobProgress(t.job,t.job.progress);else if(t.job.status==="completed"||t.job.status==="failed")await this.handleJobStatusChange(t.job.id,t.job.status,t.job.metadata)}catch(e){this.logger.error("Failed to poll durable job progress",{error:e})}finally{this.polling=!1}}createProgressReporter(e,t){let n=Qa.from(async(r)=>{await this.emitJobProgress(e,r,t)});if(!n)throw Error("Failed to create ProgressReporter");return n}async emitBatchProgress(e,t,n){try{let r={totalOperations:t.totalOperations,completedOperations:t.completedOperations,failedOperations:t.failedOperations,currentOperation:t.currentOperation??"Processing batch...",errors:t.errors},o={id:e,type:"batch",status:t.status,metadata:n,batchDetails:r};if(t.totalOperations>0)o.progress={current:t.completedOperations,total:t.totalOperations,percentage:Math.round(t.completedOperations/t.totalOperations*100)};await this.messageBus.send({type:cy.progress,payload:o,sender:"job-progress-monitor",broadcast:!0}),this.logger.debug("Emitted batch progress update",{batchId:e,status:t.status,progress:`${t.completedOperations}/${t.totalOperations}`})}catch(r){this.logger.error("Error emitting batch progress update",{batchId:e,error:r})}}isBatchChild(e,t){return!!t&&t!==e}get publishesEvents(){return this.mode!=="durable-writer"}async broadcastEvent(e){await this.messageBus.send({type:cy.progress,payload:e,sender:"job-progress-monitor",broadcast:!0})}async emitJobProgress(e,t,n){try{if(n&&!await this.jobQueueService.recordAttemptProgress(e,n,t)){this.logger.debug("Discarding progress from obsolete job attempt",{jobId:e,attemptId:n});return}if(!this.publishesEvents)return;let r=await this.jobQueueService.getStatus(e);if(!r){this.logger.warn("Job not found for progress update",{jobId:e});return}await this.publishJobProgress(r,t)}catch(r){this.logger.error("Error emitting job progress",{jobId:e,error:r})}}async publishJobProgress(e,t){if(e.metadata.silent)return;if(this.isBatchChild(e.id,e.metadata.rootJobId))return;let n=t.total??0,r={id:e.id,type:"job",status:"processing",metadata:e.metadata,message:t.message};if(n>0)r.progress={current:t.progress,total:n,percentage:Math.round(t.progress/n*100)};await this.broadcastEvent(r)}async emitJobCompletion(e){await this.emitJobStatusEvent(e,"completed")}async emitJobFailure(e){await this.emitJobStatusEvent(e,"failed")}async emitJobStatusEvent(e,t){if(!this.publishesEvents)return;try{let n=await this.jobQueueService.getStatus(e);if(!n){this.logger.warn(`Cannot emit ${t} for unknown job`,{jobId:e});return}if(n.metadata.silent)return;if(this.isBatchChild(e,n.metadata.rootJobId)){this.logger.debug(`Skipping individual job ${t} for batch operation`,{jobId:e,rootJobId:n.metadata.rootJobId});return}let r={id:e,type:"job",status:t,message:this.extractStatusMessage(n,t),metadata:n.metadata,jobDetails:{jobType:n.type,priority:n.priority,retryCount:n.retryCount}};await this.broadcastEvent(r),this.logger.debug(`Emitted job ${t} event`,{jobId:e})}catch(n){this.logger.error(`Error emitting job ${t} event`,{jobId:e,error:n})}}extractStatusMessage(e,t){if(t==="failed")return e.lastError??void 0;if(!e.result)return;try{let n=GEe.parse(e.result),r=n.message;if(r)return String(r);let o=n.routesBuilt;if(o!==void 0)return`${o} routes built`}catch{}return}getStats(){return{isRunning:!0}}async handleJobStatusChange(e,t,n){if(!this.publishesEvents)return;let r=n?sp.safeParse(n):void 0,o=r?.success?r.data:void 0;if(o?.silent)return;try{if(await this.emitJobStatusEvent(e,t),o&&this.isBatchChild(e,o.rootJobId))try{let i=o.rootJobId,s=await this.batchJobManager.getBatchStatus(i);if(s){let c=s.metadata??o;await this.emitBatchProgress(i,s,c)}}catch(i){this.logger.warn("Failed to emit batch progress",{jobId:e,rootJobId:o.rootJobId,error:i})}}catch(i){this.logger.error("Failed to handle job status change",{jobId:e,status:t,error:i})}}}var VEe=a.record(a.string(),a.unknown());class ly{logger;schema;jobTypeName;executionTimeoutMs;constructor(e,t){this.logger=e,this.schema=t.schema,this.jobTypeName=t.jobTypeName,this.executionTimeoutMs=t.executionTimeoutMs}validateAndParse(e){if(!this.schema)throw Error(`${this.jobTypeName}: No schema provided. Override validateAndParse() or provide a schema.`);let t=this.schema.safeParse(e);if(!t.success)return this.logger.warn(`Invalid ${this.jobTypeName} job data`,{data:e,validationError:t.error.issues}),null;return this.logger.debug(`${this.jobTypeName} job data validation successful`,{data:this.summarizeDataForLog(t.data)}),t.data}async onError(e,t,n,r,o){this.logger.error(`${this.jobTypeName} job error handler triggered`,{jobId:n,errorMessage:e.message,errorStack:e.stack,data:this.summarizeDataForLog(t)})}async reportProgress(e,t){await e.report({progress:t.progress,total:t.total??100,message:t.message})}summarizeDataForLog(e){let t=VEe.safeParse(e);return t.success?t.data:{}}}function uy(e,t,n){return async(r)=>{let{type:o,data:i,toolContext:s=null,options:c,projection:l}=r,u=s?G5(s):void 0,{metadata:p,...d}=c??{},g={operationType:"data_processing",pluginId:t,...p,...s&&{interfaceType:s.interfaceType,conversationId:s.conversationId,channelId:s.channelId,requestedByActor:s.actor,...u?{requestedByUserId:u}:{},requestedByInterface:s.interfaceType,...s.progressToken!==void 0&&{progressToken:s.progressToken}}};if(s&&!u)delete g.requestedByUserId;let f={...d,source:t,...c?.rootJobId&&{rootJobId:c.rootJobId},...l&&{projection:l},metadata:g},v=n&&!o.includes(":")?`${t}:${o}`:o;return e.enqueue({type:v,data:i,options:f})}}function S_(e,t){return async(n,r)=>{let o=r?.rootJobId??Pt(),i=n.map((c)=>({...c,type:c.type.includes(":")?c.type:`${t}:${c.type}`})),s={...r,source:t,rootJobId:o,metadata:{...r?.metadata,operationType:"batch_processing",pluginId:t}};return await e.enqueueBatch(i,s,o,t),o}}function v_(e,t){return(n,r)=>{let o=n.includes(":")?n:`${t}:${n}`;e.registerHandler(o,r,t)}}var QEe=a.custom((e)=>typeof e==="object"&&e!==null&&("safeParse"in e)),KEe=a.object({name:a.string(),schema:QEe});function V5(e){return KEe.safeParse(e).success}function YEe(e){if(!e)return;return{status:e.status,message:e.message,lastCheck:e.lastCheck?.toISOString(),details:e.details}}function Q5(e){return{model:e.model,version:e.version,uptime:e.uptime,entities:e.entities,entityCounts:e.entityCounts,embeddings:e.embeddings,ai:e.ai,daemons:e.daemons.map((t)=>({name:t.name,pluginId:t.pluginId,status:t.status,health:YEe(t.health)})),endpoints:e.endpoints,interactions:e.interactions}}var K5={digest:"conversation:digest"};var XEe="/api/chat",fo="web-chat-guest",Ew=a.strictObject({idleSeconds:a.number().int().positive().max(Math.floor(Number.MAX_SAFE_INTEGER/1000)),maxAgeSeconds:a.number().int().positive().max(Math.floor(Number.MAX_SAFE_INTEGER/1000))}).refine((e)=>e.idleSeconds<=e.maxAgeSeconds,"Guest idle expiry must not exceed maximum age"),Iw=a.strictObject({visitorId:a.string().uuid(),retention:Ew}),Je=a.string().trim().min(1).max(256),hrt="x-brain-conversation-id",yrt=a.strictObject({expiresAt:a.number().int().positive(),provider:a.string().min(1),notice:a.string().min(1),deletionLimitations:a.string().min(1),retention:Ew,messageCharacters:a.number().int().positive(),canSend:a.boolean(),presentation:X5.optional()}),eIe=a.strictObject({conversationId:Je,state:a.enum(["active","completed","failed","interrupted","uncertain"])}),t9=a.string().regex(/^upload-[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i),w_=a.string().trim().min(1).max(48),C_=a.string().datetime(),Y5=a.string().regex(/^\/(?!\/)/).max(2048),Am=a.string().regex(/^(?:\/(?!\/)|https?:\/\/)/).max(2048),tIe=a.looseObject({kind:a.literal("tool-approval"),id:Je,toolCallId:Je.optional(),toolName:a.string().trim().min(1).max(256),input:a.record(a.string(),a.unknown()).optional(),summary:a.string().max(4096),completionSummary:a.string().max(4096).optional(),preview:a.string().max(1e5).optional(),state:a.enum(["approval-requested","approval-responded","output-available","output-denied","output-error"]),output:a.unknown().optional(),error:a.string().max(4096).optional()}),nIe=a.looseObject({entityType:a.string().trim().min(1).max(128).optional(),entityId:Je.optional(),attachmentType:a.string().trim().min(1).max(128).optional()}),rIe=a.looseObject({mediaType:a.string().trim().min(1).max(255),url:Am,downloadUrl:Am.optional(),previewUrl:Am.optional(),filename:a.string().trim().min(1).max(255).optional(),sizeBytes:a.number().int().nonnegative().optional(),source:nIe.optional()}),n9=a.looseObject({kind:a.literal("attachment"),id:Je,jobId:Je.optional(),title:a.string().max(4096),description:a.string().max(20000).optional(),attachment:rIe}),oIe=a.looseObject({id:Je,title:a.string().max(4096).optional(),source:a.string().trim().min(1).max(512),url:Am.optional(),entityType:a.string().trim().min(1).max(128).optional(),entityId:Je.optional(),excerpt:a.string().max(20000).optional(),provenance:a.record(a.string(),a.unknown()).optional()}),E_=a.looseObject({kind:a.literal("sources"),id:Je,title:a.string().max(4096).optional(),sources:a.array(oIe).min(1).max(100)}),iIe=a.discriminatedUnion("type",[a.object({type:a.literal("prompt"),id:Je,label:a.string().trim().min(1).max(256),prompt:a.string().min(1).max(1e5),description:a.string().max(4096).optional()}),a.object({type:a.literal("event"),id:Je,label:a.string().trim().min(1).max(256),event:a.string().trim().min(1).max(256),fromState:a.string().trim().min(1).max(256).optional(),description:a.string().max(4096).optional()})]),r9=a.looseObject({kind:a.literal("actions"),id:Je,title:a.string().max(4096).optional(),actions:a.array(iIe).min(1).max(100)}),o9=a.discriminatedUnion("kind",[tIe,n9,E_,r9]);function brt(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let r of e.slice(0,10)){let o=E_.safeParse(r);if(!o.success||o.data.id!=="sources:tool-results")continue;for(let i of o.data.sources){if(t.length>=15)break;if(!i.entityType||!i.entityId||i.entityId.length>256||i.source!==i.entityType||i.id!==`${i.entityType}:${i.entityId}`||n.has(i.id))continue;n.add(i.id);let s;if(i.url&&i.url.length<=512)try{let c=new URL(i.url);if(c.protocol==="https:"&&!c.username&&!c.password&&c.href.length<=512)s=c.href}catch{}t.push({id:i.id,source:i.entityType,entityType:i.entityType,entityId:i.entityId,title:(i.title??i.entityId).slice(0,160),...i.excerpt?{excerpt:i.excerpt.slice(0,280)}:{},...s?{url:s}:{}})}}return t.length?[{kind:"sources",id:"sources:tool-results",title:"Retrieved sources",sources:t}]:[]}var sIe=a.object({id:Je,toolCallId:Je.optional(),toolName:a.string().trim().min(1).max(256),summary:a.string().max(4096),completionSummary:a.string().max(4096).optional(),preview:a.string().max(1e5).optional(),args:a.unknown()}),i9=a.object({toolName:a.string().trim().min(1).max(256),args:a.record(a.string(),a.unknown()).optional(),jobId:Je.optional(),data:a.unknown().optional(),error:a.object({message:a.string().max(4096),code:a.string().trim().min(1).max(256).optional()}).optional()}),xrt=a.looseObject({text:a.string().max(1e6),toolResults:a.array(i9).max(100).optional(),cards:a.array(o9).max(100).optional(),pendingConfirmations:a.array(sIe).max(100).optional(),usage:a.object({promptTokens:a.number().int().nonnegative(),completionTokens:a.number().int().nonnegative(),totalTokens:a.number().int().nonnegative()})});function Srt(e=XEe){let t=aIe(e);return{stream:t,actions:`${t}/actions`,sessions:`${t}/sessions`,sessionArchive:`${t}/sessions/archive`,messages:`${t}/messages`,uploads:`${t}/uploads`,contextSessions:`${t}/context-sessions`,documentAttachments:`${t}/attachments/document`,imageAttachments:`${t}/attachments/image`,jobStatus:`${t}/jobs/status`}}function aIe(e){let t=e.trim();if(!t.startsWith("/")||t.startsWith("//")||t.length>512||/[\s"'<>\\]/u.test(t)||t.includes("?")||t.includes("#"))throw Error("Chat API path must be a same-origin absolute path without query or fragment");let n=t.replace(/\/+$/,"");if(n.length===0)throw Error("Chat API path must not be the site root");return n}var cIe=a.strictObject({version:a.literal(1),sourceId:a.string().trim().regex(/^[a-z][a-z0-9-]*$/).max(64),itemId:a.string().trim().min(1).max(300),titleSeed:a.string().trim().min(1).max(160).refine((e)=>!/[\p{Cc}\p{Cf}]/u.test(e))}),vrt=a.object({query:a.string().trim().max(200).default(""),archived:a.boolean().default(!1),offset:a.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).default(0),limit:a.number().int().min(1).max(100).default(25)}),lIe=a.looseObject({id:Je,title:w_,lastActiveAt:C_,archived:a.boolean().optional(),contextHandoff:cIe.optional()}),Trt=a.looseObject({sessions:a.array(lIe).max(100)}),uIe=a.looseObject({kind:a.string().trim().min(1).max(64),id:Je}),pIe=a.looseObject({kind:a.literal("text"),filename:a.string().trim().min(1).max(255),mediaType:a.string().trim().min(1).max(255),sizeBytes:a.number().int().nonnegative(),createdAt:C_,source:uIe.optional()}),s9=a.looseObject({id:Je,role:a.enum(["user","assistant"]),content:a.string().max(1e6),attachments:a.array(pIe).max(100).optional(),cards:a.array(o9).max(100).optional()}),wrt=a.looseObject({messages:a.array(s9).max(100)}),Crt=a.string().min(1).max(256).refine((e)=>e.trim().length>0),Ert=a.strictObject({messages:a.array(s9).max(100),submission:eIe.nullable()}),Irt=a.object({type:a.literal("text"),text:a.string().max(1e6)}),krt=a.object({type:a.literal("file"),mediaType:a.string().trim().min(1).max(255).optional(),filename:a.string().trim().min(1).max(255).optional(),url:a.string().min(1).max(2000000)}),a9=a.object({kind:a.literal("upload"),id:t9}),Rrt=a.object({type:a.literal("data-upload"),data:a.looseObject({ref:a9})}),dIe=a.object({id:Je,approved:a.boolean(),toolCallId:Je.optional(),toolName:a.string().trim().min(1).max(256).optional(),input:a.record(a.string(),a.unknown()).optional(),title:a.string().max(4096).optional()}),Prt=a.looseObject({state:a.literal("approval-responded"),toolCallId:Je.optional(),toolName:a.string().trim().min(1).max(256).optional(),input:a.record(a.string(),a.unknown()).optional(),title:a.string().max(4096).optional(),approval:dIe}),mIe=a.object({id:Je.optional(),role:a.enum(["user","assistant","system"]),parts:a.array(a.unknown()).max(1000).optional(),content:a.string().max(1e6).optional()}),Art=a.object({id:Je.optional(),messages:a.array(mIe).min(1).max(200),trigger:a.string().trim().min(1).max(64).optional()}).strict(),Ort=a.strictObject({id:Je.optional(),messages:a.array(a.strictObject({id:Je,role:a.literal("user"),parts:a.array(a.strictObject({type:a.literal("text"),text:a.string()})).min(1).max(16)})).length(1)}),c9=a.enum(["pending","processing","completed","failed"]),fIe=a.looseObject({type:a.enum(["job","batch"]),status:c9,operationType:a.enum(["file_operations","content_operations","data_processing","batch_processing"]),operationTarget:a.string().max(1024).optional(),message:a.string().max(4096).optional(),progress:a.object({current:a.number().nonnegative(),total:a.number().nonnegative(),percentage:a.number().min(0).max(100)}).optional()}),gIe=a.looseObject({status:a.enum(["tool-running","tool-completed","tool-awaiting-approval","tool-failed"]),toolName:a.string().trim().min(1).max(256),error:a.string().max(4096).optional()}),Drt=a.discriminatedUnion("type",[a.looseObject({type:a.literal("start"),messageId:Je.optional()}),a.looseObject({type:a.literal("start-step")}),a.looseObject({type:a.literal("finish-step")}),a.looseObject({type:a.literal("finish"),finishReason:a.enum(["length","error","stop","content-filter","tool-calls","other"]).optional()}),a.looseObject({type:a.literal("abort"),reason:a.string().max(4096).optional()}),a.looseObject({type:a.literal("error"),errorText:a.string().max(20000)}),a.looseObject({type:a.literal("text-start"),id:Je}),a.looseObject({type:a.literal("text-delta"),id:Je,delta:a.string().max(1e6)}),a.looseObject({type:a.literal("text-end"),id:Je}),a.looseObject({type:a.literal("reasoning-start"),id:Je}),a.looseObject({type:a.literal("reasoning-delta"),id:Je,delta:a.string().max(1e6)}),a.looseObject({type:a.literal("reasoning-end"),id:Je}),a.looseObject({type:a.literal("tool-input-start"),toolCallId:Je,toolName:a.string().trim().min(1).max(256),title:a.string().max(4096).optional()}),a.looseObject({type:a.literal("tool-input-delta"),toolCallId:Je,inputTextDelta:a.string().max(1e6)}),a.looseObject({type:a.literal("tool-input-available"),toolCallId:Je,toolName:a.string().trim().min(1).max(256),input:a.unknown(),title:a.string().max(4096).optional()}),a.looseObject({type:a.literal("tool-input-error"),toolCallId:Je,toolName:a.string().trim().min(1).max(256),input:a.unknown(),errorText:a.string().max(20000),title:a.string().max(4096).optional()}),a.looseObject({type:a.literal("tool-approval-request"),approvalId:Je,toolCallId:Je}),a.looseObject({type:a.literal("tool-output-available"),toolCallId:Je,output:a.unknown(),preliminary:a.boolean().optional()}),a.looseObject({type:a.literal("tool-output-error"),toolCallId:Je,errorText:a.string().max(20000)}),a.looseObject({type:a.literal("tool-output-denied"),toolCallId:Je}),a.looseObject({type:a.literal("source-url"),sourceId:Je,url:Am,title:a.string().max(4096).optional()}),a.looseObject({type:a.literal("source-document"),sourceId:Je,mediaType:a.string().trim().min(1).max(255),title:a.string().max(4096),filename:a.string().trim().min(1).max(255).optional()}),a.looseObject({type:a.literal("file"),url:Am,mediaType:a.string().trim().min(1).max(255)}),a.looseObject({type:a.literal("data-progress"),id:Je.optional(),data:fIe,transient:a.boolean().optional()}),a.looseObject({type:a.literal("data-status"),id:Je.optional(),data:gIe,transient:a.boolean().optional()}),a.looseObject({type:a.literal("data-tool-result"),id:Je.optional(),data:i9,transient:a.boolean().optional()}),a.looseObject({type:a.literal("data-actions"),id:Je.optional(),data:r9,transient:a.boolean().optional()}),a.looseObject({type:a.literal("data-sources"),id:Je.optional(),data:E_,transient:a.boolean().optional()}),a.looseObject({type:a.literal("data-attachment"),id:Je.optional(),data:n9,transient:a.boolean().optional()})]),Mrt=a.strictObject({conversationId:Je}),_rt=a.object({title:w_}).strict(),zrt=a.object({renamed:a.boolean(),title:w_}),Frt=a.object({archived:a.boolean()}),jrt=a.object({deleted:a.boolean()}),Nrt=a.object({conversationId:Je,action:e9}).strict(),Lrt=a.looseObject({id:Je,status:c9,message:a.string().max(4096).optional()}),Brt=a.looseObject({id:t9,ref:a9,filename:a.string().trim().min(1).max(255),mediaType:a.string().trim().min(1).max(255),sizeBytes:a.number().int().nonnegative(),createdAt:C_,url:Y5,downloadUrl:Y5}).refine((e)=>e.id===e.ref.id,{path:["ref","id"],message:"Upload response ids must match"});var Ie=Nt("conversations",{id:le("id").primaryKey(),sessionId:le("session_id").notNull(),interfaceType:le("interface_type").notNull(),channelId:le("channel_id").notNull(),personId:le("person_id"),started:le("started").notNull(),lastActive:le("last_active").notNull(),metadata:le("metadata"),created:le("created").notNull(),updated:le("updated").notNull()},(e)=>({sessionIdx:zt("idx_conversations_session").on(e.sessionId),channelIdx:zt("idx_conversations_channel").on(e.channelId),personIdx:zt("idx_conversations_person").on(e.personId),interfaceSessionIdx:zt("idx_conversations_interface_session").on(e.interfaceType,e.sessionId),interfaceChannelIdx:zt("idx_conversations_interface_channel").on(e.interfaceType,e.channelId)})),jn=Nt("messages",{id:le("id").primaryKey(),conversationId:le("conversation_id").notNull().references(()=>Ie.id,{onDelete:"cascade"}),role:le("role").notNull(),content:le("content").notNull(),timestamp:le("timestamp").notNull(),metadata:le("metadata")},(e)=>({conversationIdx:zt("idx_messages_conversation").on(e.conversationId),timestampIdx:zt("idx_messages_timestamp").on(e.timestamp)})),ap=Nt("summary_tracking",{conversationId:le("conversation_id").primaryKey().references(()=>Ie.id,{onDelete:"cascade"}),lastSummarizedAt:le("last_summarized_at"),lastMessageId:le("last_message_id"),messagesSinceSummary:qe("messages_since_summary").default(0),updated:le("updated").notNull()});function l9(e){return Ui({url:e.url,schema:{conversations:Ie,messages:jn,summaryTracking:ap},authToken:e.authToken,authTokenEnv:"CONVERSATION_DATABASE_AUTH_TOKEN"})}var hIe=a.preprocess((e)=>{if(typeof e!=="string")return e;try{return JSON.parse(e)}catch{return}},a.record(a.string(),a.unknown())).catch({});function Ya(e){return hIe.parse(e)}var kw="conversation:messageAdded",I_="conversation:started",py=a.object({identity:Fs,interfaceType:a.string(),role:Tm,displayName:a.string().optional(),username:a.string().optional(),isBot:a.boolean().optional()}),yIe=a.preprocess(bIe,py);function bIe(e){if(!pi(e)||"identity"in e)return e;let{actorId:t,interfaceType:n,role:r}=e;if(typeof t!=="string"||typeof n!=="string"||r!=="user"&&r!=="assistant")return e;let{userId:o,canonicalId:i}=e;return{identity:u9({actorId:t,interfaceType:n,role:r,...typeof o==="string"?{userId:o}:{},...typeof i==="string"?{canonicalId:i}:{}}),interfaceType:n,role:r,...typeof e.displayName==="string"?{displayName:e.displayName}:{},...typeof e.username==="string"?{username:e.username}:{},...typeof e.isBot==="boolean"?{isBot:e.isBot}:{}}}var dy=a.object({messageId:a.string().optional(),channelId:a.string().optional(),channelName:a.string().optional(),threadId:a.string().optional(),metadata:a.record(a.string(),a.unknown()).optional()}),p9=a.looseObject({actor:yIe.optional(),source:dy.optional()});function d9(e){if(typeof e==="string")try{let t=JSON.parse(e);return pi(t)?t:null}catch{return null}return pi(e)?e:null}function xIe(e){if(e.role!=="assistant")return!1;if(e.content.trim().length===0)return!1;let t=d9(e.metadata),n=t?.entityMemoryRefs;if(Array.isArray(n)&&n.length>0)return!1;let r=t?.cards;if(!Array.isArray(r))return!0;return!r.some((o)=>{if(!pi(o))return!1;if(o.kind==="tool-approval")return!0;return o.kind==="actions"&&o.id==="actions:upload-intent"})}var SIe=a.object({id:a.string(),conversationId:a.string(),role:a.string(),content:a.string(),timestamp:a.string(),metadata:a.string().nullable()}),m9=a.object({conversationId:a.string(),messageCount:a.number(),messages:a.array(SIe),windowStart:a.number(),windowEnd:a.number(),windowSize:a.number(),timestamp:a.string()});var Gi=x`strftime('%Y-%m-%dT%H:%M:%fZ', 'now')`;function k_(){return g9(!1)}function f9(){return g9(!0)}function g9(e){let t=Ew.shape.maxAgeSeconds.maxValue,n=x`(
167
167
  CAST(round((julianday(${Gi}) - julianday(${Ie.started})) * 86400000) AS INTEGER) >= json_extract(${Ie.metadata}, '$.guest.retention.maxAgeSeconds') * 1000
168
168
  OR CAST(round((julianday(${Gi}) - julianday(${Ie.lastActive})) * 86400000) AS INTEGER) >= json_extract(${Ie.metadata}, '$.guest.retention.idleSeconds') * 1000
169
169
  )`;return x`CASE WHEN json_valid(${Ie.metadata}) THEN coalesce(
@@ -203,5 +203,5 @@ Result:`);if(n===-1)return;let r=e.slice(n+9).trim();if(!r)return;try{return JSO
203
203
  `)}function T7(e){return{identity:e.identity,interfaceType:e.interfaceType,role:e.role??"user",...e.displayName?{displayName:e.displayName}:{},...e.username?{username:e.username}:{},...e.isBot!==void 0?{isBot:MAe(e.isBot)}:{}}}function MAe(e){if(typeof e==="boolean")return e;return e.toLowerCase()==="true"}function w7(e){return{...e.messageId?{messageId:e.messageId}:{},...e.channelId?{channelId:e.channelId}:{},...e.channelName?{channelName:e.channelName}:{},...e.threadId?{threadId:e.threadId}:{},...e.metadata?{metadata:e.metadata}:{}}}function C7(e){if(e.skippedMessages.length===0)return{message:e.message};return{message:["Messages received while the previous response was still running (oldest first, for context only):",...e.skippedMessages.map(_Ae),"","Latest message to answer:",e.message].join(`
204
204
  `),metadata:{supersededMessageCount:e.skippedMessages.length,supersededMessageIds:e.skippedMessages.map((r)=>r.id).filter((r)=>r!==void 0)}}}function _Ae(e){let t=e.text.trim(),n=e.authorName?.trim();return n?`- ${n}: ${t}`:`- ${t}`}async function $Ae(e){let{entityType:t,title:n,deriveId:r,regeneratePrompt:o,context:i}=e,s=r(n),c=await i.entityService.getEntity({entityType:t,id:s});if(!c||c.metadata.status==="generating")return n;i.logger.debug(`Entity ID collision: ${t}/${s}, asking AI for a new title`);let l=a.object({title:a.string().max(80).describe("A short, unique title (2-6 words)")}),{object:u}=await i.ai.generateObject(`The title "${n}" is already taken. ${o}`,l),p=u.title;return i.logger.debug(`AI suggested new title: "${p}"`),p}class kC{tail=Promise.resolve();run(e){let t=this.tail.then(()=>e());return this.tail=t.then(()=>{return},()=>{return}),t}async settle(){await this.tail}}var UAe="current";class E7{store;schema;createEmpty;key;queue=new kC;statePromise;constructor(e){this.store=e.runtimeState.scoped({namespace:e.namespace,schema:e.schema}),this.schema=e.schema,this.createEmpty=e.createEmpty,this.key=e.key??UAe}mutate(e){return this.queue.run(async()=>{let t=await this.load(),n=await e(t);return await this.persist(t),n})}async snapshot(){return await this.settle(),structuredClone(await this.load())}settle(){return this.queue.settle()}load(){return this.statePromise??=this.store.get(this.key).then((e)=>e??this.createEmpty()),this.statePromise}async persist(e){await this.store.set(this.key,this.schema.parse(e))}}var oz=ci.extend({id:a.literal("brain-character"),entityType:a.literal("brain-character")}),RC=a.object({name:a.string().describe("The brain's friendly display name"),role:a.string().describe("The brain's primary role"),purpose:a.string().describe("The brain's purpose and goals"),values:a.array(a.string()).describe("Core values that guide behavior")});var WAe=a.record(a.string(),a.unknown());class zy extends tl{generateFrontMatter(e){let t=this.parseFrontmatter(e.content);return this.buildMarkdown("",WAe.parse(t))}}class PC extends zy{constructor(){super({entityType:"brain-character",purpose:"The brain's own identity, character, and purpose (singleton).",schema:oz,frontmatterSchema:RC,isSingleton:!0,hasBody:!1})}createCharacterContent(e){return this.buildMarkdown("",e)}parseCharacterBody(e){return this.parseFrontmatter(e)}toMarkdown(e){return this.generateFrontMatter(e)}fromMarkdown(e){return{content:e,entityType:"brain-character"}}extractMetadata(e){let t=this.parseFrontmatter(e.content);return{role:t.role,values:t.values}}}class Fy extends yw{codec;constructor(e,t,n,r,o,i){super(e,t,n,r,Os(o));this.codec=i}parseBody(e){return this.codec.parse(e)}createContent(e){return this.codec.create(e)}}class AC extends Fy{static getDefaultCharacter(){return{name:"Brain",role:"Knowledge assistant",purpose:"Help organize, understand, and retrieve information from your knowledge base",values:["clarity","accuracy","helpfulness"]}}static createFresh(e,t,n){return new AC(e,t,n)}constructor(e,t,n){let r=new PC;super(e,t,"brain-character",n??AC.getDefaultCharacter(),"brain character is loaded at bootstrap before any user is in scope",{parse:(o)=>r.parseCharacterBody(o),create:(o)=>r.createCharacterContent(o)})}getCharacter(){return this.get()}getCharacterContent(){return this.getContent()}}var iz=ci.extend({id:a.literal("anchor-profile"),entityType:a.literal("anchor-profile")}),I7=a.enum(["person","team","organization"]),pp=a.object({name:a.string().describe("Name of the anchor"),organization:a.string().optional().describe("Organization the anchor belongs to"),description:a.string().optional().describe("Short description or biography"),avatar:a.string().optional().describe("URL or asset path to avatar/logo"),website:a.string().optional().describe("Primary website URL"),email:a.string().optional().describe("Contact email"),socialLinks:a.array(a.object({platform:a.enum(["github","instagram","linkedin","email","website"]).describe("Social media platform"),url:a.string().describe("Profile or contact URL"),label:a.string().optional().describe("Optional display label")})).optional().describe("Social media and contact links")});class OC extends zy{constructor(){super({entityType:"anchor-profile",purpose:"The profile of the brain's Anchor (singleton).",schema:iz,frontmatterSchema:pp,isSingleton:!0,hasBody:!0})}createProfileContent(e){let t=pp.parse(e);return this.buildMarkdown("",t)}parseProfileBody(e,t){if(t){let{metadata:n,content:r}=Vn(e,t);return r?{...n,story:r}:n}return this.parseFrontmatter(e)}fromMarkdown(e){return{content:e,entityType:"anchor-profile"}}extractMetadata(e){let t=this.parseFrontmatter(e.content);return{name:t.name,email:t.email,website:t.website}}}class jy extends Fy{static getDefaultProfile(){return{name:"Unknown"}}static createFresh(e,t,n){return new jy(e,t,n)}constructor(e,t,n){let r=new OC;super(e,t,"anchor-profile",n??jy.getDefaultProfile(),"anchor profile is loaded at bootstrap before any user is in scope",{parse:(o)=>r.parseProfileBody(o),create:(o)=>r.createProfileContent(o)})}getProfile(){return this.get()}getProfileContent(){return this.getContent()}}var DC=a.enum(["person","team","organization"]),HAe=a.object({kind:a.string().trim().min(1),category:DC,labels:a.object({singular:a.string().trim().min(1),plural:a.string().trim().min(1)})});function JAe(e){if(typeof e!=="object"||e===null||!("shape"in e)||!("safeParse"in e)||typeof e.safeParse!=="function")throw Error("Profile kind fields must be a Zod object schema")}class k7{selectedKind;registrations=new Map;finalized=!1;resolved=null;selectedDefinition;constructor(e){let t=e?.trim();this.selectedKind=t===""?void 0:t}register(e,t){if(this.finalized)throw Error("Profile kind registration is closed");let n=HAe.parse(t);JAe(t.fields);let r=Object.freeze({...t,kind:n.kind,category:n.category,labels:Object.freeze({...n.labels})}),o=this.registrations.get(n.kind)??[];o.push({pluginId:e,definition:r}),this.registrations.set(n.kind,o)}unregisterPlugin(e){for(let[t,n]of this.registrations){let r=n.filter((o)=>o.pluginId!==e);if(r.length===0)this.registrations.delete(t);else this.registrations.set(t,r)}}finalize(){if(this.finalized)return this.resolved;let t=[...this.registrations.entries()].filter(([,r])=>r.length>1).sort(([r],[o])=>r.localeCompare(o))[0];if(t){let[r,o]=t,i=o.map((s)=>s.pluginId).sort().join(", ");throw Error(`Profile kind "${r}" is registered by multiple plugins: ${i}`)}if(!this.selectedKind)return this.finalized=!0,this.resolved=null,null;let n=this.registrations.get(this.selectedKind)?.[0];if(!n)throw Error(`Selected profile kind "${this.selectedKind}" is not registered`);return this.selectedDefinition=n.definition,this.resolved=Object.freeze({kind:n.definition.kind,category:n.definition.category,labels:Object.freeze({...n.definition.labels})}),this.finalized=!0,this.resolved}getResolved(){return this.assertFinalized(),this.resolved}getSelectedDefinition(){return this.assertFinalized(),this.selectedDefinition}isFinalized(){return this.finalized}assertFinalized(){if(!this.finalized)throw Error("Profile kind selection has not been finalized")}}var R7=30000;class az{logger;resolver;links=[];actorIndex=new Map;negativeActorIndex=new Map;static createFresh(e,t){return new az(e,t)}constructor(e,t){this.logger=e.child("CanonicalIdentityService"),this.resolver=t}async refreshCache(){this.links=[],this.actorIndex=new Map,this.negativeActorIndex=new Map,this.logger.debug("Canonical identity links refreshed",{linkCount:0,actorCount:0})}getLinks(){return this.links}resolveActor(e){let t=sz(e),n=this.actorIndex.get(t);if(!n)return null;if(n.expiresAt<=Date.now())return this.actorIndex.delete(t),null;return n.resolution}async enrichActor(e){if(e.identity.kind==="user"&&e.identity.canonicalId||e.role!=="user")return e;let t=this.resolveActor(e.identity);if(t)return this.enrichedActor(e,t);let n=sz(e.identity),r=this.negativeActorIndex.get(n);if(r&&r>Date.now())return e;this.negativeActorIndex.delete(n);let o=await this.resolver?.(e.identity);if(!o)return this.negativeActorIndex.set(n,Date.now()+R7),e;let i={identity:e.identity,...e.displayName?{label:e.displayName}:{}},s={...o,actors:[i],matchedActor:i};return this.actorIndex.set(n,{resolution:s,expiresAt:Date.now()+R7}),this.links=[...this.links.filter((c)=>c.userId!==s.userId),s],this.enrichedActor(e,s)}enrichedActor(e,t){return{...e,identity:{kind:"user",userId:t.userId,canonicalId:t.canonicalId},...t.displayName?{displayName:t.displayName}:{}}}}var P7="https://rizom.ai/ext/anchor-profile/v1",A7=a.looseObject({id:a.string(),description:a.string(),name:a.string().optional(),tags:a.array(a.string()).optional().default([])}),O7=pp.extend({kind:a.string().trim().min(1).optional(),category:DC.optional()}).superRefine((e,t)=>{if(e.kind===void 0!==(e.category===void 0))t.addIssue({code:"custom",message:"Anchor kind and category must be provided together"})}),GAe=a.looseObject({uri:a.string(),params:a.record(a.string(),a.unknown()).optional()}),D7=a.looseObject({name:a.string(),url:a.string(),description:a.string().optional(),skills:a.array(A7).optional().default([]),capabilities:a.looseObject({extensions:a.array(GAe).optional().default([])}).optional()});function VAe(e){let t=D7.safeParse(e);if(!t.success)return null;let n=t.data,o=(n.capabilities?.extensions??[]).find((s)=>s.uri===P7),i=null;if(o?.params){let s=O7.safeParse(o.params);if(s.success)i=s.data}return{brainName:n.name,url:n.url,description:n.description??"",skills:n.skills.map((s)=>({id:s.id,name:s.name??s.id,description:s.description,tags:s.tags})),anchor:i}}import{EventEmitter as z7}from"events";var sn={REGISTERED:"registered",INITIALIZED:"initialized",ERROR:"error",DISABLED:"disabled"},bi={REGISTERED:"plugin:registered",BEFORE_INITIALIZE:"plugin:before_initialize",INITIALIZED:"plugin:initialized",ERROR:"plugin:error",DISABLED:"plugin:disabled"};class xi extends Error{pluginId;constructor(e,t){super(`Plugin ${e}: ${t}`);this.name="PluginError",this.pluginId=e}}function qs(e,t){return Reflect.get(e,t,e)}function Zs(e,t,n){if(typeof e!=="function")throw TypeError("Cannot apply a non-callable trapped member");return Reflect.apply(e,t,n)}class cz{scope;ingress=new Set;closePromise=null;closed=!1;constructor(){this.scope=de.runSync(Xt.make())}addFinalizer(e){if(this.closed)throw Error("Cannot register a resource after plugin teardown");de.runSync(Xt.addFinalizer(this.scope,de.promise(async()=>{await e()})))}addIngress(e){if(this.closed)throw Error("Cannot register ingress after plugin teardown");this.ingress.add(e)}close(e=jt.void){return this.closed=!0,this.closePromise??=this.closeScope(e),this.closePromise}async closeScope(e){let t,n=!1,r=[...this.ingress].reverse();for(let c of r)try{c.stopAdmission()}catch(l){if(!n)t=l;n=!0}let o=await Promise.allSettled(r.map((c)=>Promise.resolve().then(()=>c.drain())));this.ingress.clear();let i=o.find((c)=>c.status==="rejected");if(!n&&i)t=i.reason,n=!0;let s=await de.runPromiseExit(Xt.close(this.scope,e));if(!n&&jt.isFailure(s))t=oi.squash(s.cause),n=!0;if(n)throw t}}function M7(e,t){let n=e.getMessageBus(),r=new Set,o={send:(te)=>n.send(te),hasHandlers:(te)=>n.hasHandlers?.(te)??!1,subscribe:(te,ce,Y)=>{let V=!0,me=new Set,xe=(ft)=>{if(!V)return{noop:!0};let bn,C=new Promise((I)=>{bn=I});me.add(C);let Lt=()=>{me.delete(C),bn()},Jn;try{Jn=Promise.resolve(ce(ft))}catch(I){throw Lt(),I}return Jn.then((I)=>(Lt(),I),(I)=>{throw Lt(),I})},se=n.subscribe(te,xe,Y),Qe={type:te,originalHandler:ce,stopAdmission:()=>{if(!V)return;V=!1,se(),r.delete(Qe)}};r.add(Qe);try{t.addIngress({stopAdmission:Qe.stopAdmission,drain:async()=>{await Promise.all(me)}})}catch(ft){throw Qe.stopAdmission(),ft}return Qe.stopAdmission},unsubscribe:(te,ce)=>{let Y=[...r].filter((V)=>V.type===te&&V.originalHandler===ce);if(Y.length===0){n.unsubscribe(te,ce);return}for(let V of Y)V.stopAdmission()},collect:(te)=>n.collect(te),validateMessage:(te,ce)=>n.validateMessage(te,ce),getHandlerCount:(te)=>n.getHandlerCount(te),getTargetedHandlerCount:(te,ce)=>n.getTargetedHandlerCount(te,ce),clearHandlers:(te)=>n.clearHandlers(te),clearAllHandlers:()=>n.clearAllHandlers()},i=e.getAttachmentRegistry(),s={...i,register:(te,ce,Y)=>{let V=!0,me=i.register(te,ce,Y),xe=()=>{if(!V)return;V=!1,me()};return t.addFinalizer(xe),xe}},c=e.getEntityRegistry(),l=new Proxy(c,{get(te,ce){let Y=qs(te,ce);if(ce==="registerEntityType"&&typeof Y==="function")return(...V)=>{let me=Zs(Y,te,V),xe=V[0];if(typeof xe==="string")t.addFinalizer(()=>te.unregisterEntityType(xe));return me};return typeof Y==="function"?Y.bind(te):Y}}),u=e.getProfileKindRegistry(),p=new Proxy(u,{get(te,ce){let Y=qs(te,ce);if(ce==="register"&&typeof Y==="function")return(...V)=>{let me=Zs(Y,te,V),xe=V[0];if(typeof xe==="string")t.addFinalizer(()=>te.unregisterPlugin(xe));return me};return typeof Y==="function"?Y.bind(te):Y}}),d=e.getChannelRegistry(),g=new Proxy(d,{get(te,ce){let Y=qs(te,ce);if((ce==="registerDescriptor"||ce==="registerDeliveryProvider")&&typeof Y==="function")return(...V)=>{let me=Zs(Y,te,V),xe=V[0];if(typeof xe==="string")t.addFinalizer(()=>te.unregisterPlugin(xe));return me};return typeof Y==="function"?Y.bind(te):Y}}),f=e.getInboxRegistry(),v=new Proxy(f,{get(te,ce){let Y=qs(te,ce);if(ce==="registerSource"&&typeof Y==="function")return(...V)=>{let me=Zs(Y,te,V),xe=V[0];if(typeof xe==="string")t.addFinalizer(()=>te.unregisterPlugin(xe));return me};return typeof Y==="function"?Y.bind(te):Y}}),T=e.getInboxFollowUpRegistry(),E=new Proxy(T,{get(te,ce){let Y=qs(te,ce);if(ce==="registerKind"&&typeof Y==="function")return(...V)=>{let me=Zs(Y,te,V),xe=V[0];if(typeof xe==="string")t.addFinalizer(()=>te.unregisterPlugin(xe));return me};return typeof Y==="function"?Y.bind(te):Y}}),A=e.getAccountSettingsRegistry(),L=new Proxy(A,{get(te,ce){let Y=qs(te,ce);if(ce==="register"&&typeof Y==="function")return(...V)=>{let me=Zs(Y,te,V);return t.addFinalizer(()=>{Zs(te.unregister,te,[me])}),me};return typeof Y==="function"?Y.bind(te):Y}}),j=e.getOperationalHealthRegistry(),ie=new Proxy(j,{get(te,ce){let Y=qs(te,ce);if(ce==="register"&&typeof Y==="function")return(...V)=>{let me=Zs(Y,te,V),xe=V[0];if(typeof xe==="string")t.addFinalizer(()=>te.unregisterPlugin(xe));return me};return typeof Y==="function"?Y.bind(te):Y}}),Ee=e.getDataSourceRegistry(),D=new Proxy(Ee,{get(te,ce){let Y=qs(te,ce);if(ce==="register"&&typeof Y==="function")return(...V)=>{let me=Zs(Y,te,V),xe=V[0];if(typeof xe==="object"&&xe!==null&&"id"in xe&&typeof xe.id==="string"){let se=xe.id.includes(":")?xe.id:`shell:${xe.id}`;t.addFinalizer(()=>te.unregister(se))}return me};return typeof Y==="function"?Y.bind(te):Y}}),Ce=e.getInsightsRegistry(),ke=new Proxy(Ce,{get(te,ce){let Y=qs(te,ce);if(ce==="register"&&typeof Y==="function")return(...V)=>{let me=Zs(Y,te,V),xe=V[0];if(typeof xe==="string")t.addFinalizer(()=>te.unregister(xe));return me};return typeof Y==="function"?Y.bind(te):Y}}),Me=new Proxy(e,{get(te,ce){if(ce==="getMessageBus")return()=>o;if(ce==="getAttachmentRegistry")return()=>s;if(ce==="getEntityRegistry")return()=>l;if(ce==="getDataSourceRegistry")return()=>D;if(ce==="getProfileKindRegistry")return()=>p;if(ce==="getChannelRegistry")return()=>g;if(ce==="getInboxRegistry")return()=>v;if(ce==="getInboxFollowUpRegistry")return()=>E;if(ce==="getOperationalHealthRegistry")return()=>ie;if(ce==="getAccountSettingsRegistry")return()=>L;if(ce==="getInsightsRegistry")return()=>ke;let Y=qs(te,ce);return typeof Y==="function"?Y.bind(te):Y}});return vY(e,Me),Me}class lz{plugins;events;daemonRegistry;logger;projectionRegistry;resourceScopes=new Map;releasePromises=new Map;constructor(e,t,n,r,o){this.plugins=e,this.events=t,this.daemonRegistry=n,this.projectionRegistry=r,this.logger=o.child("PluginLifecycle")}async initializePlugin(e,t,n){let r=this.plugins.get(e);if(!r)throw new xi(e,"Registration failed: Plugin is not registered");let o=r.plugin,i=new cz;i.addFinalizer(()=>t.unregisterPluginCapabilities?.(e)),i.addFinalizer(()=>t.getJobQueueService().unregisterPluginHandlers(e)),i.addFinalizer(()=>this.projectionRegistry.unregisterPlugin(e)),this.resourceScopes.set(e,i),this.releasePromises.delete(e),this.logger.debug(`Initializing plugin: ${e}`);try{this.events.emit(bi.BEFORE_INITIALIZE,e,o);let s=await o.register(M7(t,i),n);return r.status=sn.INITIALIZED,this.logger.debug(`Initialized plugin: ${e}`),this.events.emit(bi.INITIALIZED,e,o),s}catch(s){throw this.logger.error(`Error initializing plugin ${e}: ${Ke(s)}`),await this.failPluginInitialization(e,s),s}}async finalizePluginRegistration(e){let t=this.plugins.get(e);if(!t)throw new xi(e,"Registration finalization failed: Plugin is not registered");if(t.status!==sn.INITIALIZED)return;try{await t.plugin.finalizeRegistration?.(),this.logger.debug(`Registration finalized for plugin: ${e}`)}catch(n){throw await this.failPluginInitialization(e,n),n}}async readyPlugin(e){let t=this.plugins.get(e);if(!t)throw new xi(e,"Ready failed: Plugin is not registered");if(t.status!==sn.INITIALIZED){this.logger.debug(`Skipping ready hook for non-initialized plugin: ${e}`);return}try{await t.plugin.ready?.(),this.logger.debug(`Ready hook completed for plugin: ${e}`)}catch(n){let r=Pm(n);t.status=sn.ERROR,t.error=r;try{this.events.emit(bi.ERROR,e,r)}catch(o){this.logger.error(`Plugin error listener failed for ${e}`,o)}throw r}}async startPluginDaemons(e){let t=this.plugins.get(e);if(t?.status!==sn.INITIALIZED)return;try{await this.daemonRegistry.startPlugin(e),this.logger.debug(`Started daemons for plugin: ${e}`)}catch(n){if(t.plugin.requiresDaemonStartup?.())throw n;this.logger.warn(`Daemon ${e} failed to start: ${Ke(n)}`)}}async failPluginInitialization(e,t){let n=this.plugins.get(e);if(!n)return;let r=n.status!==sn.ERROR,o=Pm(t);if(n.status=sn.ERROR,n.error=o,await this.releasePluginResources(e,jt.fail(t)),r)try{this.events.emit(bi.ERROR,e,o)}catch(i){this.logger.error(`Plugin error listener failed for ${e}`,i)}}async disablePlugin(e){let t=this.plugins.get(e);if(!t){this.logger.warn(`Cannot disable plugin ${e}: not registered`);return}if(t.status===sn.DISABLED)return;this.logger.debug(`Disabling plugin: ${e}`);let n=t.status===sn.ERROR;await this.releasePluginResources(e,jt.void);let r=this.plugins.get(e);if(!n&&r&&r.status!==sn.DISABLED)r.status=sn.DISABLED,this.events.emit(bi.DISABLED,e,r.plugin);this.logger.debug(`Disabled plugin: ${e}`)}releasePluginResources(e,t){let n=this.releasePromises.get(e);if(n)return n;let r=this.releasePluginResourcesOnce(e,t);return this.releasePromises.set(e,r),r}async releasePluginResourcesOnce(e,t){let n=this.plugins.get(e);if(!n)return;try{await this.daemonRegistry.stopPlugin(e),this.logger.debug(`Stopped daemons for plugin: ${e}`)}catch(o){this.logger.error(`Failed to stop daemons for plugin: ${e}`,o)}let r=this.resourceScopes.get(e);if(this.resourceScopes.delete(e),r)try{await r.close(t)}catch(o){this.logger.error(`Failed to close resources for plugin ${e}`,o)}if(n.plugin.shutdown)try{await n.plugin.shutdown(),this.logger.debug(`Shutdown completed for plugin: ${e}`)}catch(o){this.logger.error(`Plugin shutdown failed for ${e}:`,o)}for(let o of this.daemonRegistry.getByPlugin(e))try{await this.daemonRegistry.unregister(o.name)}catch(i){this.logger.error(`Failed to unregister daemon ${o.name} for plugin ${e}`,i)}}}class uz{plugins;events;logger;constructor(e,t,n){this.plugins=e,this.events=t,this.logger=n.child("DependencyResolver")}async resolveInitializationOrder(e){this.logger.debug("Resolving plugin initialization order...");let t=Array.from(this.plugins.keys()),n=new Set,r=!0;while(r&&n.size<t.length){r=!1;for(let s of t){if(n.has(s))continue;if(!this.plugins.get(s))continue;if(this.getUnmetDependencies(s).length===0)try{await e(s),n.add(s),r=!0}catch(u){let p=Ke(u);this.logger.error(`Failed to initialize plugin ${s}: ${p}`),n.add(s),r=!0}}}let o=t.filter((s)=>!n.has(s));if(o.length>0){let s=o.join(", ");this.logger.error(`Failed to initialize plugins due to dependency issues: ${s}`);for(let c of o){let l=this.getUnmetDependencies(c);this.logger.error(`Plugin ${c} has unmet dependencies: ${l.join(", ")}`);let u=this.plugins.get(c);if(u)u.status=sn.ERROR,u.error=new xi(c,`Unmet dependencies: ${l.join(", ")}`);this.events.emit(bi.ERROR,c,u?.error)}}let i=new Set;for(let[s,c]of this.plugins)if(c.status===sn.INITIALIZED)i.add(s);return this.logger.debug(`Resolved ${i.size} of ${t.length} plugins`),{initialized:i,failed:o}}getUnmetDependencies(e){let t=this.plugins.get(e);if(!t)return[];let{dependencies:n}=t,r=[];for(let o of n){let i=this.plugins.get(o);if(!i){r.push(o);continue}if(i.status!==sn.INITIALIZED)r.push(o)}return r}}class pz{logger;projectionRegistry;constructor(e,t){this.logger=e.child("CapabilityRegistrar"),this.projectionRegistry=t}async registerCapabilities(e,t,n,r){if(!r?.executionOnly&&n.tools.length>0)e.registerTools(t,n.tools),this.logger.debug(`Registered ${n.tools.length} tools from ${t}`);if(!r?.executionOnly&&n.resources.length>0)e.registerResources(t,n.resources),this.logger.debug(`Registered ${n.resources.length} resources from ${t}`);if(!r?.executionOnly&&n.instructions)e.registerInstructions(t,n.instructions),this.logger.debug(`Registered instructions from ${t}`);let o=n.projectionRules??[];try{for(let i of o)this.projectionRegistry.registerRule(t,i)}catch(i){throw this.projectionRegistry.unregisterPlugin(t),i}if(o.length>0)this.logger.debug(`Registered ${o.length} projection rules from ${t}`)}}class MC{projections=new Map;rules=new Map;static createFresh(){return new MC}constructor(){}registerRule(e,t){if(!Object.isFrozen(t))throw Error(`Projection rule "${t.id}" must be created with defineProjectionRule`);let n=this.projections.get(t.id);if(n)throw Error(`Projection "${t.id}" is already registered by "${n.pluginId}"`);let r={id:t.id,pluginId:e,targetType:t.targetType,sources:t.sources.map((i)=>({kind:i.kind,types:[...i.types],...i.excludeTypes?{excludeTypes:[...i.excludeTypes]}:{}}))};this.projections.set(t.id,r),this.rules.set(t.id,t);let o=!0;return()=>{if(!o)return;if(o=!1,this.rules.get(t.id)===t)this.rules.delete(t.id);if(this.projections.get(t.id)===r)this.projections.delete(t.id)}}unregisterPlugin(e){for(let[t,n]of this.projections)if(n.pluginId===e)this.projections.delete(t),this.rules.delete(t)}list(){return Array.from(this.projections.values()).sort((e,t)=>e.id.localeCompare(t.id)).map(YAe)}listRules(){return[...this.rules.values()].sort((e,t)=>e.id.localeCompare(t.id))}validate(e){let t=this.list(),n=new Set(e.map(({type:s})=>s));for(let s of t)if(!n.has(s.targetType))throw Error(`Projection "${s.id}" targets unregistered entity type "${s.targetType}"`);let r=e.filter(({projectionSource:s})=>s).map(({type:s})=>s).sort(),o=XAe(t,r),i=tOe(t,o)[0];if(i){let s=nOe(i,o);throw Error(`Projection cycle is not supported: ${[...s,s[0]].join(" -> ")}`)}return KAe({projections:t,edges:o,unknownSourceTypes:QAe(t,n)})}}function QAe(e,t){let n=[];for(let r of e){let o=[...new Set(r.sources.flatMap((i)=>[...i.types,...i.excludeTypes??[]]).filter((i)=>i!=="*"&&!t.has(i)))].sort();if(o.length>0)n.push({projectionId:r.id,types:o})}return n}function KAe(e){for(let t of e.projections){for(let n of t.sources){if(Object.freeze(n.types),n.excludeTypes)Object.freeze(n.excludeTypes);Object.freeze(n)}Object.freeze(t.sources),Object.freeze(t)}for(let t of e.edges)Object.freeze(t.causes),Object.freeze(t);for(let t of e.unknownSourceTypes)Object.freeze(t.types),Object.freeze(t);return Object.freeze(e.unknownSourceTypes),Object.freeze(e.projections),Object.freeze(e.edges),Object.freeze(e)}function YAe(e){return{...e,sources:e.sources.map((t)=>({...t,types:[...t.types],...t.excludeTypes?{excludeTypes:[...t.excludeTypes]}:{}}))}}function XAe(e,t){let n=new Map;for(let r of e)for(let o of e){let i=eOe(r,o,t);if(i.length===0)continue;n.set(`${r.id}\x00${o.id}`,new Set(i))}return Array.from(n,([r,o])=>{let[i="",s=""]=r.split("\x00");return{from:i,to:s,causes:[...o].sort()}}).sort((r,o)=>r.from.localeCompare(o.from)||r.to.localeCompare(o.to))}function eOe(e,t,n){let r=[];for(let o of t.sources){let i=new Set(o.excludeTypes??[]);if((o.types.includes("*")?[...o.types.filter((c)=>c!=="*"),...n]:o.types).includes(e.targetType)&&!i.has(e.targetType))r.push(`entity:${e.targetType}`)}return[...new Set(r)]}function tOe(e,t){let n=e.map(({id:d})=>d).sort(),r=_7(n,t),o=new Map,i=new Map,s=[],c=new Set,l=[],u=0,p=(d)=>{o.set(d,u),i.set(d,u),u++,s.push(d),c.add(d);for(let T of r.get(d)??[])if(!o.has(T))p(T),i.set(d,Math.min(i.get(d)??0,i.get(T)??0));else if(c.has(T))i.set(d,Math.min(i.get(d)??0,o.get(T)??0));if(i.get(d)!==o.get(d))return;let g=[],f;do{if(f=s.pop(),!f)break;c.delete(f),g.push(f)}while(f!==d);let v=r.get(d)?.includes(d)??!1;if(g.length>1||v)l.push(g.sort())};for(let d of n)if(!o.has(d))p(d);return l.sort((d,g)=>(d[0]??"").localeCompare(g[0]??""))}function nOe(e,t){let n=new Set(e),r=_7(e,t),o=[...e].sort()[0];if(!o)return[];if(r.get(o)?.includes(o))return[o];let i=(s,c)=>{for(let l of r.get(s)??[]){if(!n.has(l))continue;if(l===o)return c;if(c.includes(l))continue;let u=i(l,[...c,l]);if(u)return u}return};return i(o,[o])??[...e].sort()}function _7(e,t){let n=new Map;for(let r of e)n.set(r,[]);for(let r of t){let o=n.get(r.from);if(o&&!o.includes(r.to))o.push(r.to)}for(let r of n.values())r.sort();return n}async function F7(e){let n=(await de.runPromise(de.all(e.map((r)=>de.either(de.tryPromise({try:r,catch:(o)=>o}))),{concurrency:"unbounded"}))).find(zr.isLeft);if(n)throw n.left}class _C{plugins=new Map;logger;events=new z7;daemonRegistry;shell=null;initializedPluginIds=[];pluginLifecycle;dependencyResolver;capabilityRegistrar;projectionRegistry=MC.createFresh();projectionGraph;static createFresh(e,t){return new _C(e,t)}setShell(e){this.shell=e}constructor(e,t){this.logger=e.child("PluginManager"),this.events=new z7,this.daemonRegistry=t,this.pluginLifecycle=new lz(this.plugins,this.events,this.daemonRegistry,this.projectionRegistry,e),this.dependencyResolver=new uz(this.plugins,this.events,e),this.capabilityRegistrar=new pz(e,this.projectionRegistry)}registerPlugin(e){if(!e.id)throw new xi("unknown","Registration failed: Plugin must have an id");if(this.logger.debug(`Registering plugin: ${e.id} (${e.version})`),this.plugins.has(e.id)){let o=this.plugins.get(e.id)?.plugin.version;throw new xi(e.id,`Registration failed: Plugin is already registered with version ${o}`)}let t=e.dependencies??[],n={plugin:e,status:sn.REGISTERED,dependencies:t};this.plugins.set(e.id,n),this.logger.debug(`Registered plugin: ${e.id} (${e.version})`),this.events.emit(bi.REGISTERED,e.id,e)}async initializePlugins(e){this.logger.debug("Initializing plugins..."),this.initializedPluginIds=[];let t=await this.dependencyResolver.resolveInitializationOrder(async(n)=>{await this.initializePlugin(n,e)});this.logger.debug(`Initialized ${t.initialized.size} of ${this.plugins.size} plugins`)}async initializePlugin(e,t){if(!this.shell)throw new xi(e,"Cannot initialize plugin: Shell not set. Call setShell() first.");let n=this.shell;try{let r=await this.pluginLifecycle.initializePlugin(e,n,t);await this.capabilityRegistrar.registerCapabilities(n,e,r,{executionOnly:t?.executionOnly}),this.initializedPluginIds.push(e)}catch(r){throw await this.pluginLifecycle.failPluginInitialization(e,r),r}}async finalizePluginRegistrations(){this.logger.debug("Finalizing plugin registrations...");for(let n of this.initializedPluginIds)await this.pluginLifecycle.finalizePluginRegistration(n);if(!this.shell)throw Error("Cannot validate projections before the shell is set");let e=this.shell.getEntityRegistry(),t=this.projectionRegistry.validate(e.getAllEntityTypes().map((n)=>{let r=e.getEntityTypeConfig(n);return{type:n,projectionSource:r.projectionSource!==!1&&r.projectionSourceRole!=="excluded"}}));this.projectionGraph=t;for(let n of t.unknownSourceTypes)this.logger.warn("Projection declares entity source types no installed plugin registers",{projectionId:n.projectionId,types:n.types});this.logger.debug("Validated projection graph",{projections:t.projections.length,edges:t.edges.length})}getProjectionGraphSnapshot(){if(!this.projectionGraph)throw Error("Projection graph has not been finalized");return this.projectionGraph}getProjectionRulesSnapshot(){if(!this.projectionGraph)throw Error("Projection graph has not been finalized");return Object.freeze(this.projectionRegistry.listRules())}async readyPlugins(){this.logger.debug("Dispatching plugin ready hooks...");try{await F7(this.initializedPluginIds.map((e)=>()=>this.pluginLifecycle.readyPlugin(e)))}catch(e){for(let t of this.initializedPluginIds){let n=this.plugins.get(t);if(n?.status===sn.ERROR)await this.pluginLifecycle.failPluginInitialization(t,n.error??e)}throw e}}async startPluginDaemons(){this.logger.debug("Starting plugin daemons..."),await F7(this.initializedPluginIds.map((e)=>()=>this.pluginLifecycle.startPluginDaemons(e)))}getPlugin(e){return this.plugins.get(e)?.plugin}getPluginStatus(e){return this.plugins.get(e)?.status}hasPlugin(e){return this.plugins.has(e)}isPluginInitialized(e){return this.plugins.get(e)?.status===sn.INITIALIZED}getAllPluginIds(){return Array.from(this.plugins.keys())}getAllPlugins(){return new Map(this.plugins)}getFailedPlugins(){return Array.from(this.plugins.entries()).filter((e)=>e[1].status===sn.ERROR&&e[1].error!==void 0).map(([e,t])=>({id:e,error:t.error}))}getPluginPackageName(e){return this.plugins.get(e)?.plugin.packageName}async disablePlugin(e){await this.pluginLifecycle.disablePlugin(e)}async shutdownPlugins(){let e=new Set;for(let t of[...this.initializedPluginIds].reverse())await this.disablePlugin(t),e.add(t);for(let t of[...this.plugins.keys()].reverse())if(!e.has(t))await this.disablePlugin(t)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}getEventEmitter(){return this.events}}var j7={public:0,trusted:1,admin:2},rOe=[{id:"dashboard",pluginId:"dashboard",label:"Dashboard",visibility:"public",requiresActiveSession:!1},{id:"web-chat",pluginId:"web-chat",label:"Chat",visibility:"trusted",requiresActiveSession:!0},{id:"studio",pluginId:"studio",label:"Studio",visibility:"public",requiresActiveSession:!0}];function oOe(e,t){let n=j7[t.permissionLevel??"public"],r=[];for(let{id:o,pluginId:i,label:s,visibility:c,requiresActiveSession:l}of rOe){let u=t.self?.id===o;if(!u&&(n<j7[c]||l&&t.hasActiveSession!==!0))continue;let p=e.filter((f)=>f.pluginId===i&&!(o==="studio"&&f.fullPath==="/chat")).map((f)=>f.fullPath).sort((f,v)=>f.length-v.length),d=o==="web-chat"&&p.length>0?e.find((f)=>f.pluginId==="studio"&&f.fullPath==="/chat")?.fullPath:void 0,g=u?t.self?.href:d??p[0];if(g!==void 0)r.push({id:o,label:s,href:g,isActive:o===t.activeId,...l?{requiresActiveSession:!0}:{}})}return r}export{Yd as ta,Yv as ua,x as va,Ah as wa,nm as xa,O as ya,ol as za,oe as Aa,fr as Ba,qa as Ca,RV as Da,Hr as Ea,It as Fa,rr as Ga,il as Ha,Zu as Ia,iT as Ja,st as Ka,dn as La,ZV as Ma,al as Na,qe as Oa,le as Pa,Nt as Qa,zt as Ra,gO as Sa,Oo as Ta,z as Ua,pi as Va,xT as Wa,Ui as Xa,Wi as Ya,ZQ as Za,XSe as _a,eve as $a,Fn as ab,hn as bb,mn as cb,Do as db,Za as eb,yt as fb,mi as gb,$Q as hb,Os as ib,Cs as jb,Es as kb,Qv as lb,ks as mb,Kd as nb,ci as ob,KG as pb,iOe as qb,sOe as rb,$s as sb,Vn as tb,Ly as ub,yp as vb,VG as wb,wT as xb,CT as yb,ZO as zb,$O as Ab,ET as Bb,IT as Cb,WO as Db,RT as Eb,cm as Fb,Ua as Gb,JO as Hb,Pt as Ib,$2e as Jb,Ms as Kb,Hi as Lb,sD as Mb,aD as Nb,Mve as Ob,_ve as Pb,zr as Qb,kt as Rb,An as Sb,oi as Tb,hu as Ub,jt as Vb,Xt as Wb,ii as Xb,de as Yb,Ur as Zb,Nu as _b,vh as $b,ws as ac,gqe as bc,dD as cc,fD as dc,Ha as ec,LT as fc,RK as gc,pl as hc,PK as ic,XGe as jc,eVe as kc,BT as lc,k as mc,Ja as nc,b as oc,ge as pc,y as qc,gr as rc,_K as sc,Ga as tc,_o as uc,Gr as vc,Uh as wc,Te as xc,kn as yc,Ye as zc,NK as Ac,LK as Bc,ot as Cc,dm as Dc,mm as Ec,ml as Fc,m3 as Gc,rw as Hc,xm as Ic,qD as Jc,ZD as Kc,YD as Lc,uw as Mc,lM as Nc,hw as Oc,b6 as Pc,x6 as Qc,tl as Rc,$A as Sc,MCe as Tc,pM as Uc,S6 as Vc,bw as Wc,dM as Xc,v6 as Yc,Th as Zc,jqe as _c,Nqe as $c,UA as ad,Lqe as bd,Bqe as cd,qqe as dd,Zqe as ed,$qe as fd,Uqe as gd,Wqe as hd,Hqe as id,fM as jd,T6 as kd,Qa as ld,km as md,o_ as nd,i_ as od,O5 as pd,D5 as qd,M5 as rd,_5 as sd,bEe as td,xEe as ud,ww as vd,vEe as wd,Em as xd,Im as yd,tEe as zd,nEe as Ad,wEe as Bd,j5 as Cd,EEe as Dd,Rm as Ed,Xet as Fd,zEe as Gd,Cw as Hd,G as Id,Ut as Jd,xl as Kd,h_ as Ld,y_ as Md,b_ as Nd,x_ as Od,ly as Pd,uy as Qd,S_ as Rd,v_ as Sd,XEe as Td,fo as Ud,Ew as Vd,Iw as Wd,hrt as Xd,yrt as Yd,eIe as Zd,brt as _d,Srt as $d,cIe as ae,vrt as be,Trt as ce,wrt as de,Crt as ee,Ert as fe,Irt as ge,krt as he,Rrt as ie,Prt as je,Art as ke,Ort as le,fIe as me,gIe as ne,Mrt as oe,_rt as pe,zrt as qe,Frt as re,jrt as se,Nrt as te,Lrt as ue,Brt as ve,Ie as we,jn as xe,ap as ye,Ya as ze,p9 as Ae,d9 as Be,xIe as Ce,Rw as De,gM as Ee,_Ce as Fe,zCe as Ge,hM as He,yM as Ie,my as Je,Aw as Ke,P_ as Le,CIe as Me,O_ as Ne,Mw as Oe,A_ as Pe,D_ as Qe,kIe as Re,_w as Se,RIe as Te,jw as Ue,P6 as Ve,F6 as We,kM as Xe,MM as Ye,k5 as Ze,Hw as _e,z_ as $e,fy as af,j_ as bf,iPe as cf,L_ as df,sPe as ef,aPe as ff,cPe as gf,fRe as hf,qm as if,l8 as jf,m8 as kf,z0 as lf,Qr as mf,lC as nf,g8 as of,N0 as pf,v8 as qf,Py as rf,T8 as sf,$m as tf,w8 as uf,TPe as vf,C8 as wf,E8 as xf,MPe as yf,k8 as zf,NPe as Af,LPe as Bf,BPe as Cf,qPe as Df,B0 as Ef,nc as Ff,GPe as Gf,q0 as Hf,W0 as If,QPe as Jf,sr as Kf,zIe as Lf,FIe as Mf,jIe as Nf,LIe as Of,V9 as Pf,Y9 as Qf,a4 as Rf,e0 as Sf,l4 as Tf,sY as Uf,oRe as Vf,cRe as Wf,p4 as Xf,m4 as Yf,J_ as Zf,mRe as _f,dat as $f,gY as ag,Vw as bg,g0 as cg,h0 as dg,RY as eg,Zm as fg,Yw as gg,Xw as hg,Ey as ig,eC as jg,FY as kg,Iy as lg,kRe as mg,RRe as ng,PRe as og,ARe as pg,ORe as qg,ky as rg,Ry as sg,YPe as tg,j8 as ug,Z8 as vg,HRe as wg,QRe as xg,iC as yg,HY as zg,JY as Ag,KRe as Bg,$8 as Cg,aC as Dg,D0 as Eg,oPe as Fg,U8 as Gg,Um as Hg,G8 as Ig,V8 as Jg,Q8 as Kg,K8 as Lg,X8 as Mg,G0 as Ng,V0 as Og,r7 as Pg,Q0 as Qg,yC as Rg,s7 as Sg,bC as Tg,K0 as Ug,a7 as Vg,c7 as Wg,u7 as Xg,p7 as Yg,xC as Zg,f7 as _g,g7 as $g,vC as ah,Dy as bh,My as ch,h7 as dh,y7 as eh,b7 as fh,rz as gh,_y as hh,S7 as ih,v7 as jh,T7 as kh,w7 as lh,C7 as mh,$Ae as nh,kC as oh,E7 as ph,RC as qh,PC as rh,AC as sh,I7 as th,pp as uh,OC as vh,jy as wh,k7 as xh,az as yh,P7 as zh,VAe as Ah,xi as Bh,_C as Ch,oOe as Dh};
205
205
 
206
- //# debugId=E533293BD58FB4EB64756E2164756E21
207
- //# sourceMappingURL=index-9xmz7sjy.js.map
206
+ //# debugId=05ED2FE66F6FCAA664756E2164756E21
207
+ //# sourceMappingURL=index-jv41j8zg.js.map