@rizom/brain 0.2.0-alpha.638 → 0.2.0-alpha.639
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/brain.js +47 -47
- package/dist/chunks/{app-xjww1k54.js → app-n4fn3452.js} +2 -2
- package/dist/chunks/{blog-post-adapter-hp1jpkh5.js → blog-post-adapter-wmaznez3.js} +2 -2
- package/dist/chunks/{index-6hm6arjn.js → index-3mkrcp93.js} +2 -2
- package/dist/chunks/{index-dssbcrs8.js → index-78z40h0p.js} +2 -2
- package/dist/chunks/{index-f3j9ts9d.js → index-agcfmyk2.js} +5 -5
- package/dist/chunks/{index-f3j9ts9d.js.map → index-agcfmyk2.js.map} +6 -6
- package/dist/chunks/{index-txh0swvr.js → index-bqxbzrs0.js} +3 -3
- package/dist/chunks/{index-4w2en9xb.js → index-ger37r63.js} +3 -3
- package/dist/chunks/{index-4w2en9xb.js.map → index-ger37r63.js.map} +1 -1
- package/dist/chunks/{index-6fezwyfd.js → index-x0ameew6.js} +2 -2
- package/dist/chunks/{linkedin-template-dy495kpt.js → linkedin-template-v2rav111.js} +2 -2
- package/dist/chunks/{rss-datasource-ezan9tme.js → rss-datasource-xdcpg5n7.js} +2 -2
- package/dist/entities.js +1 -1
- package/dist/git-broker.js +3 -3
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -1
- package/dist/interfaces.js +1 -1
- package/dist/model.d.ts +3 -0
- package/dist/model.js +44 -44
- package/dist/model.js.map +3 -3
- package/dist/plugins.d.ts +1 -0
- package/dist/plugins.js +1 -1
- package/dist/services.js +1 -1
- package/dist/ui/{studio-app-ndcrmfzm.js → studio-app-b7p35nrr.js} +2 -2
- package/dist/ui/studio-asset-manifest.json +13 -13
- package/dist/ui/studio-chunks/{account-view-bx624hra.js → account-view-06a2f2at.js} +1 -1
- package/dist/ui/studio-chunks/{main-epetgpas.js → main-2d5rbjdk.js} +1 -1
- package/dist/ui/studio-chunks/{main-xsp6hn6k.js → main-34qtzn9g.js} +1 -1
- package/dist/ui/studio-chunks/{main-spzjxcrk.js → main-3erzpfwb.js} +4 -4
- package/dist/ui/studio-chunks/{main-spzjxcrk.js.map → main-3erzpfwb.js.map} +6 -6
- package/dist/ui/studio-chunks/{studio-chat-workspace-fszz87y5.js → studio-chat-workspace-nyqph20k.js} +1 -1
- package/package.json +1 -1
- /package/dist/chunks/{app-xjww1k54.js.map → app-n4fn3452.js.map} +0 -0
- /package/dist/chunks/{blog-post-adapter-hp1jpkh5.js.map → blog-post-adapter-wmaznez3.js.map} +0 -0
- /package/dist/chunks/{index-6hm6arjn.js.map → index-3mkrcp93.js.map} +0 -0
- /package/dist/chunks/{index-dssbcrs8.js.map → index-78z40h0p.js.map} +0 -0
- /package/dist/chunks/{index-txh0swvr.js.map → index-bqxbzrs0.js.map} +0 -0
- /package/dist/chunks/{index-6fezwyfd.js.map → index-x0ameew6.js.map} +0 -0
- /package/dist/chunks/{linkedin-template-dy495kpt.js.map → linkedin-template-v2rav111.js.map} +0 -0
- /package/dist/chunks/{rss-datasource-ezan9tme.js.map → rss-datasource-xdcpg5n7.js.map} +0 -0
- /package/dist/ui/{studio-app-ndcrmfzm.js.map → studio-app-b7p35nrr.js.map} +0 -0
- /package/dist/ui/studio-chunks/{account-view-bx624hra.js.map → account-view-06a2f2at.js.map} +0 -0
- /package/dist/ui/studio-chunks/{main-epetgpas.js.map → main-2d5rbjdk.js.map} +0 -0
- /package/dist/ui/studio-chunks/{main-xsp6hn6k.js.map → main-34qtzn9g.js.map} +0 -0
- /package/dist/ui/studio-chunks/{studio-chat-workspace-fszz87y5.js.map → studio-chat-workspace-nyqph20k.js.map} +0 -0
|
@@ -106,7 +106,7 @@ params: ${t}`);if(this.query=e,this.params=t,this.cause=n,Error.captureStackTrac
|
|
|
106
106
|
`).slice(1).join(`
|
|
107
107
|
`).trim()}if(o){let s=o.replace(/\s+/g," ").trim(),l=s.length>500?s.substring(0,500)+"...":s;t.push(l)}}return t.join(`
|
|
108
108
|
|
|
109
|
-
`)}parse(e){throw Error("BaseEntityFormatter is for display only. Use BaseEntityAdapter for parsing operations.")}}class _m{cache=null;cacheParseError=null;logger;entityService;entityType;defaultBody;readScope;constructor(e,t,n,i,o="public"){this.entityService=e,this.logger=t.child(this.constructor.name),this.entityType=n,this.defaultBody=i,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 qH(e,t){let n=e.getAdapter(t.entityType);if(!n.buildStub)return;let i=n.buildStub({id:t.id,title:t.title}),o=new Date().toISOString();return{id:t.id,entityType:t.entityType,content:i.content,metadata:i.metadata,visibility:"public",created:o,updated:o,contentHash:""}}function LH(e){return"getEntityRaw"in e&&typeof e.getEntityRaw==="function"}function iu(e,t){let{publishedOnly:n,visibilityScope:i}=t;if(!n&&!i)return e;let o=(s)=>i?{...s,visibilityScope:i}:s,a=(s)=>{let l=o(s?.filter);return{...s,...n&&{publishedOnly:!0},...l&&{filter:l}}};return new Proxy(e,{get(s,l,c){if(l==="listEntities")return(d)=>s.listEntities({entityType:d.entityType,options:a(d.options)});if(l==="countEntities")return(d)=>s.countEntities({entityType:d.entityType,options:a(d.options)});if(l==="getEntity")return(d)=>s.getEntity({...d,visibilityScope:i,...n&&{publishedOnly:!0}});if(l==="getEntityRaw"&&LH(s))return(d)=>s.getEntityRaw({...d,visibilityScope:i,...n&&{publishedOnly:!0}});if(l==="search")return(d)=>s.search({...d,options:{...d.options,...i&&{visibilityScope:i},...n&&{publishedOnly:!0}}});if(l==="getEntityCounts")return async(d)=>{let p=i??d;if(!n)return s.getEntityCounts(p);return(await Promise.all(s.getEntityTypes().map(async(g)=>({entityType:g,count:await s.countEntities({entityType:g,options:{publishedOnly:!0,...p&&{filter:{visibilityScope:p}}}})})))).filter(({count:g})=>g>0)};let u=Reflect.get(s,l,c);return typeof u==="function"?u.bind(s):u}})}function rA(e,t){return t==="public"?e:`${e}-${t}`}function Cm(e,t,n,i){let o=i.getEntityTypeConfig(e).publish?.publishStatuses;if(!o?.length||typeof n!=="string")return"non-publish";let a=typeof t==="string"&&o.includes(t);if(!o.includes(n))return"non-publish";return a?"within-publish-set":"boundary"}class Jb{dataSources=new Map;logger;static createFresh(e){return new Jb(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)}}var iA=r.object({currentPage:r.number(),totalPages:r.number(),totalItems:r.number(),pageSize:r.number(),hasNextPage:r.boolean(),hasPrevPage:r.boolean()});function Vb(e,t,n){let i=Math.max(1,Math.ceil(e/n));return{currentPage:t,totalPages:i,totalItems:e,pageSize:n,hasNextPage:t<i,hasPrevPage:t>1}}async function Hb(e,t,n,i,o="public",a={}){let s={...a.signal&&{signal:a.signal},...a.publishedOnly&&{publishedOnly:!0}};try{s.signal?.throwIfAborted();let l=await e.getEntityRaw({entityType:t,id:n,visibilityScope:o,...s});if(s.signal?.throwIfAborted(),l)return l;let c=await e.listEntities({entityType:t,options:{limit:1,filter:{metadata:{slug:n},visibilityScope:o},...s}});if(s.signal?.throwIfAborted(),c[0])return c[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 d=await e.listEntities({entityType:t,options:{limit:1,filter:{metadata:{title:Oa(n)},visibilityScope:o},...s}});if(s.signal?.throwIfAborted(),d[0])return d[0];let p=await e.listEntities({entityType:t,options:{limit:200,filter:{visibilityScope:o},...s}});s.signal?.throwIfAborted();let m=Oa(n);return p.find((g)=>typeof g.metadata.title==="string"&&Oa(g.metadata.title)===m)??null}catch(l){if(i)i.error(`Failed to find entity ${t}:${n}`,{error:l});throw l}}async function oA(e,t,n,i,o="Entity",a="public",s={}){let l=await Hb(e,t,n,i,a,s);if(!l)return{ok:!1,error:`${o} not found: ${t}/${n}`};return{ok:!0,entity:l}}var Im=r.object({success:r.boolean(),data:r.unknown().optional(),error:r.string().optional()}),Em=r.object({id:r.string().min(1),timestamp:r.string(),type:r.string().min(1),source:r.string().min(1),target:r.string().optional(),metadata:r.record(r.string(),r.unknown()).optional()});var $H=r.object({id:r.string().min(1),requestId:r.string().min(1),success:r.boolean(),data:r.unknown().optional(),error:r.object({message:r.string(),code:r.string().optional()}).optional(),timestamp:r.string().datetime()});function cA(e){return{...e,...e.source!==void 0&&{source:sA(e.source)},...e.target!==void 0&&{target:sA(e.target)}}}function sA(e){if(e instanceof RegExp)return e;if(!e.includes("*"))return e;let t=e.split("*").map((n)=>n.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${t}$`)}function uA(e,t){if(!t)return!0;if(!lA(e.source,t.source))return!1;if(!lA(e.target,t.target,!0))return!1;if(!UH(e.metadata,t.metadata))return!1;return t.predicate?t.predicate(e):!0}function lA(e,t,n=!1){if(!t)return!0;if(n&&!e)return!1;return ZH(e,t)}function UH(e,t){if(!t)return!0;if(!e)return!1;return Object.entries(t).every(([n,i])=>e[n]===i)}function ZH(e,t){if(!e)return!1;if(t instanceof RegExp){t.lastIndex=0;let n=t.test(e);return t.lastIndex=0,n}return e===t}var GH=r.union([r.object({noop:r.literal(!0)}),Im]);function dA(e){let t=GH.safeParse(e);if(!t.success)throw Error("Invalid message response format");return t.data}function Kb(e,t,n,i,o){return{id:mA("msg"),type:e,timestamp:gA(),source:n,target:i,metadata:o,payload:t}}function km(e,t){let n=dA(t);if("noop"in n)return pA(e,!0);return pA(e,n.success,n.data,n.error)}function Qb(e,t){if(t?.success)return{success:!0,data:t.data};return{success:!1,error:t?.error?.message??`No handler found for message type: ${e}`}}function pA(e,t,n,i){return{id:mA("resp"),requestId:e,timestamp:gA(),success:t,data:n,error:i?{message:i}:void 0}}function mA(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function gA(){return new Date().toISOString()}class Rm{handlers=new Map;add(e,t,n){let i=this.createHandlerEntry(t,n);return this.getOrCreateHandlers(e).add(i),i}remove(e,t){let n=this.handlers.get(e);if(!n)return!1;let i=n.delete(t);return this.deleteEmptyHandlerSet(e,n),i}removeHandler(e,t){let n=this.handlers.get(e);if(!n)return;for(let i of Array.from(n))if(i.originalHandler===t)n.delete(i);this.deleteEmptyHandlerSet(e,n)}getMatchingHandlers(e,t){let n=this.handlers.get(e);if(!n||n.size===0)return;return{entries:Array.from(n).filter((i)=>uA(t,i.filter)),totalHandlers:n.size}}hasHandlers(e){let t=this.handlers.get(e);return t!==void 0&&t.size>0}clearHandlers(e){return this.handlers.delete(e)}clearAllHandlers(){this.handlers.clear()}getHandlerCount(e){return this.handlers.get(e)?.size??0}getTargetedHandlerCount(e,t){let n=this.handlers.get(e);if(!n)return 0;return Array.from(n).filter((i)=>i.filter?.target===t).length}createHandlerEntry(e,t){let n={handler:this.wrapHandler(e),originalHandler:e};return t?{...n,filter:cA(t)}:n}wrapHandler(e){return async(t)=>{let i=await e(t);return km(t.id,i)}}getOrCreateHandlers(e){let t=this.handlers.get(e);if(!t)t=new Set,this.handlers.set(e,t);return t}deleteEmptyHandlerSet(e,t){if(t.size===0)this.handlers.delete(e)}}async function fA(e,t,n){return await Promise.all(t.map((i)=>Yb(i,e,n))),null}async function hA(e,t,n){for(let i of t){let o=await Yb(i,e,n);if(o)return o}return null}async function yA(e,t,n){return(await Promise.all(t.map((o)=>Yb(o,e,n)))).map((o)=>o??km(e.id,{success:!1,error:`Message handler failed for message type: ${e.type}`}))}async function Yb(e,t,n){try{return await e.handler(t)}catch(i){return n.error(`Error in message handler for ${t.type}`,i),null}}class Am{registry;logger;constructor(e,t){this.registry=e,this.logger=t}async publish(e,t){let n=this.resolveMatchingHandlers(e);if(!n)return null;return t===!0?fA(e,n,this.logger):hA(e,n,this.logger)}async collect(e){let t=this.resolveMatchingHandlers(e);if(!t)return[];return yA(e,t,this.logger)}resolveMatchingHandlers(e){if(typeof e!=="object"||!e.type||!e.id){this.logger.error("Invalid message structure - missing required fields 'id' or 'type'");return}let{type:t}=e;this.logger.debug(`Publishing message of type: ${t}`,{source:e.source,target:e.target,hasMetadata:!!e.metadata});let n=this.registry.getMatchingHandlers(t,e);if(!n){this.logger.debug(`No handlers found for message type: ${t}`);return}if(n.entries.length===0){this.logger.debug(`No matching handlers for message type: ${t}`,{totalHandlers:n.totalHandlers,target:e.target});return}return n.entries}}var WH=r.looseObject({issues:r.array(r.looseObject({message:r.string()})).optional()});function Xb(e,t){try{return{valid:!0,data:t.parse(e)}}catch(n){let i=WH.safeParse(n);if(i.success)return{valid:!1,error:i.data.issues?.[0]?.message??"Validation failed"};return{valid:!1,error:"Unknown validation error"}}}import{AsyncLocalStorage as JH}from"async_hooks";class la{storage=new JH;static createFresh(){return new la}constructor(){}current(){return this.storage.getStore()}run(e,t,n){if(t.length===0)throw Error("Operation ID must not be empty");let i=Gi.parse(e),o=VH(i);return this.storage.run(Object.freeze({provenance:o,operationId:t}),n)}}function VH(e){if(Object.freeze(e.projectionLineage),e.sourceEntity)Object.freeze(e.sourceEntity);return Object.freeze(e)}class ev{registry=new Rm;publisher;peerRegistry=new Rm;peerPublisher;logger;operationContext;static createFresh(e,t){return new ev(e,t)}constructor(e,t){this.logger=e,this.operationContext=t??la.createFresh(),this.publisher=new Am(this.registry,e),this.peerPublisher=new Am(this.peerRegistry,e)}subscribe(e,t,n){let i=this.registry.add(e,t,n);return this.logger.debug(`Registered handler for message type: ${e}`,{hasFilter:!!n,filterTarget:n?.target}),()=>{this.registry.remove(e,i)}}observe(e,t){let n=this.subscribe(e,t),i=this.peerRegistry.add(e,t);return()=>{n(),this.peerRegistry.remove(e,i)}}async deliverPeer(e,t){await this.peerPublisher.publish(Kb(e,t,"peer"),!0)}async send(e){let t=await this.dispatchWithProvenance(e,(n)=>this.publisher.publish(n,e.broadcast));return Qb(e.type,t)}async collect(e){return(await this.dispatchWithProvenance(e,(n)=>this.publisher.collect(n))).map((n)=>Qb(e.type,n))}dispatchWithProvenance(e,t){let{type:n,payload:i,sender:o,target:a,metadata:s}=e,l=Kb(n,i,o,a,s),c=this.operationContext.current(),u=s?.provenance,d=u===void 0?c?.provenance:Gi.parse(u),p=Gi.parse(d?{...d,causationId:c?.operationId??d.causationId}:{rootJobId:l.id,causationId:l.id,projectionLineage:[],derivationDepth:0}),m={...l,metadata:{...s,provenance:p}};return this.operationContext.run(p,m.id,()=>t(m))}validateMessage(e,t){return Xb(e,t)}hasHandlers(e){return this.registry.hasHandlers(e)}unsubscribe(e,t){this.registry.removeHandler(e,t)}clearHandlers(e){if(this.registry.clearHandlers(e))this.logger.info(`Cleared all handlers for message type: ${e}`)}clearAllHandlers(){this.registry.clearAllHandlers(),this.logger.info("Cleared all message handlers")}getHandlerCount(e){return this.registry.getHandlerCount(e)}getTargetedHandlerCount(e,t){return this.registry.getTargetedHandlerCount(e,t)}}function tv(e){return`${e.name} answered outside its contract`}function bA(e){if("success"in e&&e.success)return;return("error"in e?e.error:void 0)??"No answer"}async function nv(e,t,n,i){let o=t.schema.parse(n);if(e.getHandlerCount(t.name)===0)return{status:"unavailable"};let a=await e.send({type:t.name,payload:o,sender:i}),s=bA(a);if(s!==void 0)return{status:"failed",error:s};let l=t.response.safeParse("data"in a?a.data:void 0);return l.success?{status:"answered",data:l.data}:{status:"failed",error:tv(t)}}async function rv(e,t,n,i){let o=t.schema.parse(n);if(e.getHandlerCount(t.name)===0)return{status:"unavailable"};let a=await e.collect({type:t.name,payload:o,sender:i}),s=[],l=[];for(let c of a){let u=bA(c);if(u!==void 0){l.push(u);continue}let d=t.response.safeParse("data"in c?c.data:void 0);if(d.success)s.push(d.data);else l.push(tv(t))}return{status:"answered",answers:s,failures:l}}async function iv(e,t,n,i){let o=t.schema.parse(n);await e.send({type:t.name,payload:o,sender:i,broadcast:!0})}function ov(e,t,n,i){let{owner:o,logger:a}=i;if(t.delivery==="request"&&e.getHandlerCount(t.name)>0)throw Error(`${o} cannot answer ${t.name}: ${t.name} already has an owner`);return e.subscribe(t.name,async(s)=>{let l=t.schema.safeParse(s.payload);if(!l.success)return a.warn(`Refused an invalid ${t.name} request`,{error:l.error.message}),{success:!1,error:`Invalid ${t.name} request`};let c={sender:s.source};try{if(t.delivery==="command")return await n(l.data,c),{success:!0};let u=t.response.safeParse(await n(l.data,c));if(u.success)return{success:!0,data:u.data};return a.error(`${o} answered ${t.name} outside its contract`,{error:u.error.message}),{success:!1,error:tv(t)}}catch(u){return{success:!1,error:ze(u)}}})}var av=r.record(r.string(),r.unknown());var HH=r.object({id:r.string(),sessionId:r.string(),interfaceType:r.string(),channelId:r.string(),personId:r.string().optional(),channelName:r.string().optional(),startedAt:r.string(),lastActiveAt:r.string(),createdAt:r.string(),updatedAt:r.string(),metadata:av}),KH=r.object({id:r.string(),conversationId:r.string(),role:pl,content:r.string(),timestamp:r.string(),metadata:av});var sv=r.object({name:r.string(),role:r.string(),purpose:r.string(),values:r.array(r.string())}),lv=r.object({name:r.string(),organization:r.string().optional(),description:r.string().optional(),avatar:r.string().optional(),website:r.string().optional(),email:r.string().optional(),socialLinks:r.array(ml).optional()});var ou=256,cv=1048576,uv=32;class Wi extends Error{constructor(e){super(e);this.name="GenerationLimitError"}}var QH=`"\\\b\f
|
|
109
|
+
`)}parse(e){throw Error("BaseEntityFormatter is for display only. Use BaseEntityAdapter for parsing operations.")}}class _m{cache=null;cacheParseError=null;logger;entityService;entityType;defaultBody;readScope;constructor(e,t,n,i,o="public"){this.entityService=e,this.logger=t.child(this.constructor.name),this.entityType=n,this.defaultBody=i,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 qH(e,t){let n=e.getAdapter(t.entityType);if(!n.buildStub)return;let i=n.buildStub({id:t.id,title:t.title}),o=new Date().toISOString();return{id:t.id,entityType:t.entityType,content:i.content,metadata:i.metadata,visibility:"public",created:o,updated:o,contentHash:""}}function LH(e){return"getEntityRaw"in e&&typeof e.getEntityRaw==="function"}function iu(e,t){let{publishedOnly:n,visibilityScope:i}=t;if(!n&&!i)return e;let o=(s)=>i?{...s,visibilityScope:i}:s,a=(s)=>{let l=o(s?.filter);return{...s,...n&&{publishedOnly:!0},...l&&{filter:l}}};return new Proxy(e,{get(s,l,c){if(l==="listEntities")return(d)=>s.listEntities({entityType:d.entityType,options:a(d.options)});if(l==="countEntities")return(d)=>s.countEntities({entityType:d.entityType,options:a(d.options)});if(l==="getEntity")return(d)=>s.getEntity({...d,visibilityScope:i,...n&&{publishedOnly:!0}});if(l==="getEntityRaw"&&LH(s))return(d)=>s.getEntityRaw({...d,visibilityScope:i,...n&&{publishedOnly:!0}});if(l==="search")return(d)=>s.search({...d,options:{...d.options,...i&&{visibilityScope:i},...n&&{publishedOnly:!0}}});if(l==="getEntityCounts")return async(d)=>{let p=i??d;if(!n)return s.getEntityCounts(p);return(await Promise.all(s.getEntityTypes().map(async(g)=>({entityType:g,count:await s.countEntities({entityType:g,options:{publishedOnly:!0,...p&&{filter:{visibilityScope:p}}}})})))).filter(({count:g})=>g>0)};let u=Reflect.get(s,l,c);return typeof u==="function"?u.bind(s):u}})}function rA(e,t){return t==="public"?e:`${e}-${t}`}function Cm(e,t,n,i){let o=i.getEntityTypeConfig(e).publish?.publishStatuses;if(!o?.length||typeof n!=="string")return"non-publish";let a=typeof t==="string"&&o.includes(t);if(!o.includes(n))return"non-publish";return a?"within-publish-set":"boundary"}class Jb{dataSources=new Map;logger;static createFresh(e){return new Jb(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)}}var iA=r.object({currentPage:r.number(),totalPages:r.number(),totalItems:r.number(),pageSize:r.number(),hasNextPage:r.boolean(),hasPrevPage:r.boolean()});function Vb(e,t,n){let i=Math.max(1,Math.ceil(e/n));return{currentPage:t,totalPages:i,totalItems:e,pageSize:n,hasNextPage:t<i,hasPrevPage:t>1}}async function Hb(e,t,n,i,o="public",a={}){let s={...a.signal&&{signal:a.signal},...a.publishedOnly&&{publishedOnly:!0}};try{s.signal?.throwIfAborted();let l=await e.getEntityRaw({entityType:t,id:n,visibilityScope:o,...s});if(s.signal?.throwIfAborted(),l)return l;let c=await e.listEntities({entityType:t,options:{limit:1,filter:{metadata:{slug:n},visibilityScope:o},...s}});if(s.signal?.throwIfAborted(),c[0])return c[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 d=await e.listEntities({entityType:t,options:{limit:1,filter:{metadata:{title:Oa(n)},visibilityScope:o},...s}});if(s.signal?.throwIfAborted(),d[0])return d[0];let p=await e.listEntities({entityType:t,options:{limit:200,filter:{visibilityScope:o},...s}});s.signal?.throwIfAborted();let m=Oa(n);return p.find((g)=>typeof g.metadata.title==="string"&&Oa(g.metadata.title)===m)??null}catch(l){if(i)i.error(`Failed to find entity ${t}:${n}`,{error:l});throw l}}async function oA(e,t,n,i,o="Entity",a="public",s={}){let l=await Hb(e,t,n,i,a,s);if(!l)return{ok:!1,error:`${o} not found: ${t}/${n}`};return{ok:!0,entity:l}}var Im=r.object({success:r.boolean(),data:r.unknown().optional(),error:r.string().optional()}),Em=r.object({id:r.string().min(1),timestamp:r.string(),type:r.string().min(1),source:r.string().min(1),target:r.string().optional(),metadata:r.record(r.string(),r.unknown()).optional()});var $H=r.object({id:r.string().min(1),requestId:r.string().min(1),success:r.boolean(),data:r.unknown().optional(),error:r.object({message:r.string(),code:r.string().optional()}).optional(),timestamp:r.string().datetime()});function cA(e){return{...e,...e.source!==void 0&&{source:sA(e.source)},...e.target!==void 0&&{target:sA(e.target)}}}function sA(e){if(e instanceof RegExp)return e;if(!e.includes("*"))return e;let t=e.split("*").map((n)=>n.replace(/[.+?^${}()|[\]\\]/g,"\\$&")).join(".*");return new RegExp(`^${t}$`)}function uA(e,t){if(!t)return!0;if(!lA(e.source,t.source))return!1;if(!lA(e.target,t.target,!0))return!1;if(!UH(e.metadata,t.metadata))return!1;return t.predicate?t.predicate(e):!0}function lA(e,t,n=!1){if(!t)return!0;if(n&&!e)return!1;return ZH(e,t)}function UH(e,t){if(!t)return!0;if(!e)return!1;return Object.entries(t).every(([n,i])=>e[n]===i)}function ZH(e,t){if(!e)return!1;if(t instanceof RegExp){t.lastIndex=0;let n=t.test(e);return t.lastIndex=0,n}return e===t}var GH=r.union([r.object({noop:r.literal(!0)}),Im]);function dA(e){let t=GH.safeParse(e);if(!t.success)throw Error("Invalid message response format");return t.data}function Kb(e,t,n,i,o){return{id:mA("msg"),type:e,timestamp:gA(),source:n,target:i,metadata:o,payload:t}}function km(e,t){let n=dA(t);if("noop"in n)return pA(e,!0);return pA(e,n.success,n.data,n.error)}function Qb(e,t){if(t?.success)return{success:!0,data:t.data};return{success:!1,error:t?.error?.message??`No handler found for message type: ${e}`}}function pA(e,t,n,i){return{id:mA("resp"),requestId:e,timestamp:gA(),success:t,data:n,error:i?{message:i}:void 0}}function mA(e){return`${e}-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function gA(){return new Date().toISOString()}class Rm{handlers=new Map;add(e,t,n){let i=this.createHandlerEntry(t,n);return this.getOrCreateHandlers(e).add(i),i}remove(e,t){let n=this.handlers.get(e);if(!n)return!1;let i=n.delete(t);return this.deleteEmptyHandlerSet(e,n),i}removeHandler(e,t){let n=this.handlers.get(e);if(!n)return;for(let i of Array.from(n))if(i.originalHandler===t)n.delete(i);this.deleteEmptyHandlerSet(e,n)}getMatchingHandlers(e,t){let n=this.handlers.get(e);if(!n||n.size===0)return;return{entries:Array.from(n).filter((i)=>uA(t,i.filter)),totalHandlers:n.size}}hasHandlers(e){let t=this.handlers.get(e);return t!==void 0&&t.size>0}clearHandlers(e){return this.handlers.delete(e)}clearAllHandlers(){this.handlers.clear()}getHandlerCount(e){return this.handlers.get(e)?.size??0}getTargetedHandlerCount(e,t){let n=this.handlers.get(e);if(!n)return 0;return Array.from(n).filter((i)=>i.filter?.target===t).length}createHandlerEntry(e,t){let n={handler:this.wrapHandler(e),originalHandler:e};return t?{...n,filter:cA(t)}:n}wrapHandler(e){return async(t)=>{let i=await e(t);return km(t.id,i)}}getOrCreateHandlers(e){let t=this.handlers.get(e);if(!t)t=new Set,this.handlers.set(e,t);return t}deleteEmptyHandlerSet(e,t){if(t.size===0)this.handlers.delete(e)}}async function fA(e,t,n){return await Promise.all(t.map((i)=>Yb(i,e,n))),null}async function hA(e,t,n){for(let i of t){let o=await Yb(i,e,n);if(o)return o}return null}async function yA(e,t,n){return(await Promise.all(t.map((o)=>Yb(o,e,n)))).map((o)=>o??km(e.id,{success:!1,error:`Message handler failed for message type: ${e.type}`}))}async function Yb(e,t,n){try{return await e.handler(t)}catch(i){return n.error(`Error in message handler for ${t.type}`,i),null}}class Am{registry;logger;constructor(e,t){this.registry=e,this.logger=t}async publish(e,t){let n=this.resolveMatchingHandlers(e);if(!n)return null;return t===!0?fA(e,n,this.logger):hA(e,n,this.logger)}async collect(e){let t=this.resolveMatchingHandlers(e);if(!t)return[];return yA(e,t,this.logger)}resolveMatchingHandlers(e){if(typeof e!=="object"||!e.type||!e.id){this.logger.error("Invalid message structure - missing required fields 'id' or 'type'");return}let{type:t}=e;this.logger.debug(`Publishing message of type: ${t}`,{source:e.source,target:e.target,hasMetadata:!!e.metadata});let n=this.registry.getMatchingHandlers(t,e);if(!n){this.logger.debug(`No handlers found for message type: ${t}`);return}if(n.entries.length===0){this.logger.debug(`No matching handlers for message type: ${t}`,{totalHandlers:n.totalHandlers,target:e.target});return}return n.entries}}var WH=r.looseObject({issues:r.array(r.looseObject({message:r.string()})).optional()});function Xb(e,t){try{return{valid:!0,data:t.parse(e)}}catch(n){let i=WH.safeParse(n);if(i.success)return{valid:!1,error:i.data.issues?.[0]?.message??"Validation failed"};return{valid:!1,error:"Unknown validation error"}}}import{AsyncLocalStorage as JH}from"async_hooks";class la{storage=new JH;static createFresh(){return new la}constructor(){}current(){return this.storage.getStore()}run(e,t,n){if(t.length===0)throw Error("Operation ID must not be empty");let i=Gi.parse(e),o=VH(i);return this.storage.run(Object.freeze({provenance:o,operationId:t}),n)}}function VH(e){if(Object.freeze(e.projectionLineage),e.sourceEntity)Object.freeze(e.sourceEntity);return Object.freeze(e)}class ev{registry=new Rm;publisher;peerRegistry=new Rm;peerPublisher;logger;operationContext;static createFresh(e,t){return new ev(e,t)}constructor(e,t){this.logger=e,this.operationContext=t??la.createFresh(),this.publisher=new Am(this.registry,e),this.peerPublisher=new Am(this.peerRegistry,e)}subscribe(e,t,n){let i=this.registry.add(e,t,n);return this.logger.debug(`Registered handler for message type: ${e}`,{hasFilter:!!n,filterTarget:n?.target}),()=>{this.registry.remove(e,i)}}observe(e,t){let n=this.subscribe(e,t),i=this.peerRegistry.add(e,t);return()=>{n(),this.peerRegistry.remove(e,i)}}async deliverPeer(e,t){await this.peerPublisher.publish(Kb(e,t,"peer"),!0)}async send(e){let t=await this.dispatchWithProvenance(e,(n)=>this.publisher.publish(n,e.broadcast));return Qb(e.type,t)}async collect(e){return(await this.dispatchWithProvenance(e,(n)=>this.publisher.collect(n))).map((n)=>Qb(e.type,n))}dispatchWithProvenance(e,t){let{type:n,payload:i,sender:o,target:a,metadata:s}=e,l=Kb(n,i,o,a,s),c=this.operationContext.current(),u=s?.provenance,d=u===void 0?c?.provenance:Gi.parse(u),p=Gi.parse(d?{...d,causationId:c?.operationId??d.causationId}:{rootJobId:l.id,causationId:l.id,projectionLineage:[],derivationDepth:0}),m={...l,metadata:{...s,provenance:p}};return this.operationContext.run(p,m.id,()=>t(m))}validateMessage(e,t){return Xb(e,t)}hasHandlers(e){return this.registry.hasHandlers(e)}unsubscribe(e,t){this.registry.removeHandler(e,t)}clearHandlers(e){if(this.registry.clearHandlers(e))this.logger.info(`Cleared all handlers for message type: ${e}`)}clearAllHandlers(){this.registry.clearAllHandlers(),this.logger.info("Cleared all message handlers")}getHandlerCount(e){return this.registry.getHandlerCount(e)}getTargetedHandlerCount(e,t){return this.registry.getTargetedHandlerCount(e,t)}}function tv(e){return`${e.name} answered outside its contract`}function bA(e){if("success"in e&&e.success)return;return("error"in e?e.error:void 0)??"No answer"}async function nv(e,t,n,i){let o=t.schema.parse(n);if(e.getHandlerCount(t.name)===0)return{status:"unavailable"};let a=await e.send({type:t.name,payload:o,sender:i}),s=bA(a);if(s!==void 0)return{status:"failed",error:s};let l=t.response.safeParse("data"in a?a.data:void 0);return l.success?{status:"answered",data:l.data}:{status:"failed",error:tv(t)}}async function rv(e,t,n,i){let o=t.schema.parse(n);if(e.getHandlerCount(t.name)===0)return{status:"unavailable"};let a=await e.collect({type:t.name,payload:o,sender:i}),s=[],l=[];for(let c of a){let u=bA(c);if(u!==void 0){l.push(u);continue}let d=t.response.safeParse("data"in c?c.data:void 0);if(d.success)s.push(d.data);else l.push(tv(t))}return{status:"answered",answers:s,failures:l}}async function iv(e,t,n,i){let o=t.schema.parse(n);await e.send({type:t.name,payload:o,sender:i,broadcast:!0})}function ov(e,t,n,i){let{owner:o,logger:a}=i;if(t.delivery==="request"&&e.getHandlerCount(t.name)>0)throw Error(`${o} cannot answer ${t.name}: ${t.name} already has an owner`);return e.subscribe(t.name,async(s)=>{let l=t.schema.safeParse(s.payload);if(!l.success)return a.warn(`Refused an invalid ${t.name} request`,{error:l.error.message}),{success:!1,error:`Invalid ${t.name} request`};let c={sender:s.source};try{if(t.delivery==="command")return await n(l.data,c),{success:!0};let u=t.response.safeParse(await n(l.data,c));if(u.success)return{success:!0,data:u.data};return a.error(`${o} answered ${t.name} outside its contract`,{error:u.error.message}),{success:!1,error:tv(t)}}catch(u){return{success:!1,error:ze(u)}}})}var av=r.record(r.string(),r.unknown());var HH=r.object({id:r.string(),sessionId:r.string(),interfaceType:r.string(),channelId:r.string(),personId:r.string().optional(),channelName:r.string().optional(),startedAt:r.string(),lastActiveAt:r.string(),createdAt:r.string(),updatedAt:r.string(),metadata:av}),KH=r.object({id:r.string(),conversationId:r.string(),role:pl,content:r.string(),timestamp:r.string(),metadata:av});var sv=r.object({name:r.string(),role:r.string(),purpose:r.string(),values:r.array(r.string())}),lv=r.object({name:r.string(),organization:r.string().optional(),description:r.string().optional(),avatar:r.string().optional(),photo:r.string().optional(),website:r.string().optional(),email:r.string().optional(),socialLinks:r.array(ml).optional()});var ou=256,cv=1048576,uv=32;class Wi extends Error{constructor(e){super(e);this.name="GenerationLimitError"}}var QH=`"\\\b\f
|
|
110
110
|
\r `;function YH(e){let t=e.codePointAt(0)??0;if(QH.includes(e))return 1;if(t<32)return 5;if(t>=55296&&t<=57343)return 3;return 0}function vA(e){let t=0;for(let n of e)t+=YH(n);return Buffer.byteLength(e,"utf8")+2+t}function dv(e){let t=0,n=new WeakSet,i=(a)=>{if(t+=a,t>cv)throw new Wi(`Content generation exceeds ${cv} UTF-8 JSON bytes`)},o=(a,s)=>{if(s>uv)throw new Wi(`Content generation exceeds JSON depth ${uv}`);if(typeof a==="string"){i(vA(a));return}if(a===null){i(4);return}if(typeof a==="boolean"){i(a?4:5);return}if(typeof a==="number"){i(JSON.stringify(a).length);return}if(typeof a!=="object")return;if(n.has(a))throw new Wi("Content generation cannot contain circular data");n.add(a),i(2);let l=0;if(Array.isArray(a))for(let c of a){if(l++>0)i(1);if(c===void 0)i(4);else o(c,s+1)}else for(let c of Object.keys(a)){let u=Reflect.get(a,c);if(u===void 0)continue;if(l++>0)i(1);i(vA(c)+1),o(u,s+1)}n.delete(a)};o(e,0)}function SA(e){if(!xr(e))return;let t=e.targets;if(Array.isArray(t)&&t.length>ou)throw new Wi(`Content generation exceeds ${ou} targets`);dv({targets:t,options:e.options})}var xA="generationLimit";function pv(e){return(t,n)=>{try{e(t)}catch(i){if(!(i instanceof Wi))throw i;return n.addIssue({code:"custom",message:i.message,params:{[xA]:!0}}),r.NEVER}return t}}function mv(e){let t=e.issues.find((n)=>n.code==="custom"&&n.params?.[xA]===!0);if(t)throw new Wi(t.message);throw e}var XH=r.object({actor:si,permissionLevel:es}),gv=r.object({actor:si,permissionCeiling:es,principalId:r.string().min(1).optional()}).superRefine((e,t)=>{let{actor:n,principalId:i}=e,o=n.kind==="user"||n.kind==="external";if(o&&!i||!o&&i!==void 0||n.kind==="user"&&n.userId!==i)t.addIssue({code:"custom",message:"Invalid generation account binding"})});class ai extends Error{constructor(){super("Content generation is not permitted");this.name="GenerationAuthorizationError"}}function TA(e,t){return _i.hasPermission(e,t)?t:e}function wA(e,t){let n=TA(e.permissionLevel,t.permissionCeiling);return{permissionLevel:n,visibilityScope:Hr(n)}}class _A{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 ai;return{permissionLevel:t.permissionLevel,principalId:t.userId}}async admit(e){let{actor:t,permissionLevel:n}=XH.parse(e),i=await this.current(t),o={actor:t,permissionCeiling:TA(i.permissionLevel,n),...i.principalId&&{principalId:i.principalId}};return{authority:o,access:wA(i,o)}}async resolve(e){let t=await this.current(e.actor);if(t.principalId!==e.principalId)throw new ai;return wA(t,e)}assertTarget(e,t,n,i,o){let a=i?["create","update","publish"]:["create"];if(t&&!this.permissions.hasPermission(e.permissionLevel,t.requiredPermission)||!a.some((s)=>this.permissions.canPerformEntityAction(e.permissionLevel,n,s))||o&&!Ls(e.permissionLevel,o))throw new ai}assertWrite(e,t,n,i){let o=Cm(t.entityType,void 0,t.metadata.status,i)!=="non-publish",a=n?o?"publish":"update":"create";if(!Ls(e.permissionLevel,t.visibility)||!this.permissions.canPerformEntityAction(e.permissionLevel,t.entityType,a)||!n&&o&&!this.permissions.canPerformEntityAction(e.permissionLevel,t.entityType,"publish"))throw new ai}}var Pm=r.object({prompt:r.string().optional(),conversationHistory:r.string().optional(),data:r.record(r.string(),r.unknown()).optional(),representedIdentity:r.enum(["brain","anchor","none"]).optional(),styleGuide:r.object({voice:r.string().optional(),visual:r.string().optional()}).optional()});var CA=Pm.extend({data:Xo.optional()}),IA=r.object({entityType:r.string().min(1),idPath:Ys,metadata:Xo,visibility:Ni.optional()}),Om=r.object({templateName:r.string().min(1),context:CA.default(()=>({})),destination:IA}),EA=r.object({dryRun:r.boolean().optional().default(!1),force:r.boolean().optional().default(!1)}),fv=r.preprocess(pv(SA),r.object({targets:r.array(Om),options:EA.default(()=>({dryRun:!1,force:!1}))})),kA=r.object({entityType:r.string().min(1),entityId:r.string().min(1),metadata:Xo,visibility:Ni}),au=r.preprocess(pv(dv),r.object({authority:gv,templateName:r.string().min(1,"Template name is required"),context:CA,destination:kA,expectedRevision:r.string().min(1).nullable()})),RA=["content-exists","template-not-found","template-cannot-generate"];function su(e){return`${e.entityType}/${Fi(e.idPath)}`}var eK=r.strictObject({entityType:r.string().min(1),idPath:Ys,entityId:r.string().min(1)}),hv={destination:eK,template:r.string().min(1)},tK=r.strictObject({...hv,status:r.literal("planned")}),nK=r.strictObject({...hv,status:r.literal("queued"),jobId:r.string().min(1)}),rK=r.strictObject({...hv,status:r.literal("skipped"),reason:r.enum(RA)}),iK=r.discriminatedUnion("status",[tK,nK,rK]),yv=r.strictObject({items:r.array(iK).max(ou),totalTargets:r.number().int().nonnegative(),plannedTargets:r.number().int().nonnegative(),queuedTargets:r.number().int().nonnegative(),skippedTargets:r.number().int().nonnegative(),batchId:r.string().min(1).optional()}).superRefine((e,t)=>{let n=e.items.filter((s)=>s.status==="planned"),i=e.items.filter((s)=>s.status==="queued"),o=e.items.filter((s)=>s.status==="skipped"),a=e.items.map((s)=>su(s.destination));if(e.items.some((s)=>Fi(s.destination.idPath)!==s.destination.entityId)||e.totalTargets!==e.items.length||e.plannedTargets!==n.length+i.length||e.queuedTargets!==i.length||e.skippedTargets!==o.length||i.length>0!==(e.batchId!==void 0)||n.length>0&&i.length>0||new Set(i.map((s)=>s.jobId)).size!==i.length||new Set(a).size!==a.length)t.addIssue({code:"custom",message:"Invalid generation admission counts or references"})});async function bv(e,t,n,i){let o=await e.planGeneration(t,i);i?.throwIfAborted();let s=o.planned.length>0&&!t.options?.dryRun?n.batchId??Bt():void 0,l=s?await Promise.all(o.planned.map(({jobData:u})=>n.enqueue(u,s))):[],c=Array.from({length:o.totalTargets});for(let{index:u,target:d,entityId:p,reason:m}of o.skipped)c[u]={destination:{...d.destination,entityId:p},templateName:d.templateName,status:"skipped",reason:m};return o.planned.forEach(({index:u,target:d,entityId:p},m)=>{let g=l[m],f={destination:{...d.destination,entityId:p},templateName:d.templateName};c[u]=g?{...f,status:"queued",jobId:g}:{...f,status:"planned"}}),{items:c.flatMap((u)=>u?[u]:[]),totalTargets:o.totalTargets,plannedTargets:o.planned.length,queuedTargets:l.length,skippedTargets:o.skipped.length,...s&&{batchId:s}}}function Ji(e,t){return!t||e.includes(":")?e:`${t}:${e}`}function vv(e,t){let n=`${t}:`;return e.startsWith(n)?e.slice(n.length):e}var Sv=(e)=>e!==void 0&&gl.canGenerate(e);async function xv(e,t,n){n?.throwIfAborted();let i=fv.safeParse({targets:t.targets.map((f)=>({...f,templateName:Ji(f.templateName,t.pluginId)})),options:t.options});if(!i.success)mv(i.error);let{targets:o,options:a}=i.data,s=new Set,l=o.map((f,h)=>{let y=su(f.destination);if(s.has(y))throw Error(`Duplicate content generation destination: ${y}`);if(s.add(y),!e.entityService.hasEntityType(f.destination.entityType))throw Error(`Unknown generation destination entity type: ${f.destination.entityType}`);let w=e.templateRegistry.get(f.templateName);if(Sv(w)&&!w.formatter)throw Error(`Generation template ${f.templateName} requires a formatter`);return{index:h,target:f,template:w,entityId:Fi(f.destination.idPath)}}),{authority:c,access:u}=await e.authorizer.admit(t.caller);n?.throwIfAborted();for(let{target:f,template:h}of l)e.authorizer.assertTarget(u,h,f.destination.entityType,a.force,f.destination.visibility);let d=new Map(await Promise.all(l.filter(({template:f})=>Sv(f)).map(async({index:f,target:h,entityId:y})=>[f,await e.entityService.getEntityWriteSnapshot({entityType:h.destination.entityType,id:y,visibilityScope:u.visibilityScope})])));n?.throwIfAborted();let p=[],m=[];for(let{index:f,target:h,template:y,entityId:w}of l){if(!y){m.push({index:f,target:h,entityId:w,reason:"template-not-found"});continue}if(!Sv(y)){m.push({index:f,target:h,entityId:w,reason:"template-cannot-generate"});continue}let I=d.get(f)??null;if(I&&h.destination.visibility!==void 0&&h.destination.visibility!==I.entity.visibility)throw new ai;let b={entityType:h.destination.entityType,entityId:w,metadata:h.destination.metadata,visibility:I?.entity.visibility??h.destination.visibility??"public"};if(I&&!a.force){m.push({index:f,target:h,entityId:w,reason:"content-exists"});continue}e.authorizer.assertWrite(u,b,I!==null,e.entityService);let v={authority:c,templateName:h.templateName,context:h.context,destination:b,expectedRevision:I?.revision??null},R=au.safeParse(v);if(!R.success)mv(R.error);p.push({index:f,target:h,entityId:w,jobData:R.data})}let g=await e.authorizer.resolve(c);if(n?.throwIfAborted(),g.permissionLevel!==u.permissionLevel)throw new ai;return{planned:p,skipped:m,totalTargets:o.length}}function AA(e,t,n){let i=Ni.parse(t.visibilityScope);return{visibilityScope:i,...n&&{signal:n},async getEntity(o,a){n?.throwIfAborted();let s=await e.getEntity({entityType:o,id:a,visibilityScope:i,...n&&{signal:n}});return n?.throwIfAborted(),s},async search(o,a){if(n?.throwIfAborted(),o.length>Uc)throw new Wi(`Content generation search query exceeds ${Uc} characters`);let s=await e.search({query:o,options:{...a,visibilityScope:i,...n&&{signal:n}}});return n?.throwIfAborted(),s}}}async function wv(e,t,n){if(n&&(n.id!==t.destination.entityId||n.entityType!==t.destination.entityType||n.visibility!==t.destination.visibility))throw new ai;let{authorizer:i}=e,o=t.expectedRevision!==null,a=await i.resolve(t.authority),s=e.templateRegistry.get(t.templateName);if(!s)throw new ai;return i.assertTarget(a,s,t.destination.entityType,o,t.destination.visibility),i.assertWrite(a,n??t.destination,o,e.entityService),a}class PA{dependencies;constructor(e){this.dependencies=e}async planGeneration(e,t){return xv({...this.dependencies,authorizer:this.dependencies.generationAuthorizer},e,t)}submitGeneration(e,t,n){return bv(this,e,t,n)}authorizeGenerationWrite(e,t){return wv({...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 i=Ji(e,n),o=this.dependencies.templateRegistry.get(i);if(!o)return this.dependencies.logger.debug(`Template not found: ${i}`),null;let a=iu(this.dependencies.entityService,{publishedOnly:t?.publishedOnly,visibilityScope:t?.visibilityScope});if(o.dataSourceId&&gl.canFetch(o)){let s=this.dependencies.dataSourceRegistry.get(o.dataSourceId);if(s)try{if(s.fetch){let l={...t?.publishedOnly!==void 0&&{publishedOnly:t.publishedOnly},entityService:a},c=await s.fetch(t?.dataParams,o.schema,l);if(c!==void 0){if(this.dependencies.logger.debug(`Resolved content via DataSource fetch for ${i}`),o.overlayFormatter&&t?.savedContent)return await this.applyContentOverlay(i,o,c,t.savedContent,a);return c}}}catch(l){this.dependencies.logger.debug(`DataSource operation failed for ${i}`,{error:l})}}if(t?.savedContent)if(!o.formatter)this.dependencies.logger.debug(`Template ${i} has no formatter; skipping saved content`);else try{let s=await a.getEntityRaw({entityType:t.savedContent.entityType,id:t.savedContent.entityId});if(s?.content)return this.dependencies.logger.debug(`Resolved content from saved entity for ${i}`),this.parseContent(i,s.content)}catch(s){this.dependencies.logger.debug(`No saved content found for ${i}: ${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 ${i}`),s}catch(s){this.dependencies.logger.debug(`Fallback content validation failed for ${i}`,{error:s})}return this.dependencies.logger.debug(`No content could be resolved for ${i}`),null}async applyContentOverlay(e,t,n,i,o){try{let a=await o.getEntityRaw({entityType:i.entityType,id:i.entityId});if(!a?.content)return n;let s=t.overlayFormatter?.parse(a.content);if(s===void 0||s===null)return n;if(!xr(n)||!xr(s))return n;let l={...n,...s},c=t.schema.parse(l);return this.dependencies.logger.debug(`Applied authored content overlay for ${e}`),c}catch(a){return this.dependencies.logger.debug(`Content overlay skipped for ${e}, using datasource base`,{error:a}),n}}async generateContent(e,t={},n={}){let{pluginId:i,signal:o,visibilityScope:a}=n;o?.throwIfAborted();let s=Ji(e,i),l=this.getTemplate(s);if(!l)throw Error(`Template not found: ${s}`);if(!l.dataSourceId)throw Error(`Template ${s} doesn't support content generation. Add dataSourceId to enable generation through DataSource pattern.`);let c=this.dependencies.dataSourceRegistry.get(l.dataSourceId);if(!c)throw Error(`DataSource ${l.dataSourceId} not found`);let u={...t,templateName:s};if(a){if(!c.generateScoped)throw Error(`DataSource ${l.dataSourceId} does not support visibility-scoped generation`);let p=await c.generateScoped(u,l.schema,AA(this.dependencies.entityService,{visibilityScope:a},o));return o?.throwIfAborted(),p}if(!c.generate)throw Error(`Template ${s} uses DataSource ${l.dataSourceId} which doesn't support content generation. This template is for data fetching only.`);let d=await c.generate(u,l.schema,o);return o?.throwIfAborted(),d}parseContent(e,t,n){let i=Ji(e,n),o=this.getTemplate(i);if(!o)throw Error(`Template not found: ${i}`);if(!o.formatter)throw Error(`Template ${i} does not have a formatter for parsing`);return o.formatter.parse(t)}formatContent(e,t,n){let i=Ji(e,n?.pluginId),o=this.getTemplate(i);if(!o)throw Error(`Template not found: ${i}`);if(!o.formatter)throw Error(`Template ${i} does not have a formatter`);let a=o.formatter.format(t);if(n?.truncate&&a.length>n.truncate)a=a.substring(0,n.truncate)+"...";return a}}var oK=r.object({name:r.string(),description:r.string(),schema:r.unknown(),basePrompt:r.string().optional(),requiredPermission:r.enum(["admin","trusted","public"]),formatter:r.unknown().optional(),dataSourceId:r.string().optional(),layout:r.object({component:r.unknown(),description:r.string().optional(),packageName:r.string().optional()}).optional()});class Tv{logger;contentService;entityService;static createFresh(e,t){return new Tv(e,t)}constructor(e,t){this.logger=ei.getInstance().child("ContentGenerationJobHandler"),this.contentService=e,this.entityService=t}async process(e,t,n,i){try{i?.throwIfAborted();let{destination:o}=e;await this.contentService.authorizeGenerationWrite(e),i?.throwIfAborted();let a=await this.entityService.getEntityWriteSnapshot({entityType:o.entityType,id:o.entityId,visibilityScope:o.visibility});if(i?.throwIfAborted(),(a?.revision??null)!==e.expectedRevision||a&&a.entity.visibility!==o.visibility)throw new jr(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}`}),i?.throwIfAborted();let l=await this.contentService.generateContent(e.templateName,e.context,{...i&&{signal:i},visibilityScope:o.visibility});i?.throwIfAborted(),await n.report({progress:1,total:3,message:`Formatting content for template: ${e.templateName}`}),i?.throwIfAborted();let c;try{c=this.contentService.formatContent(e.templateName,l)}catch(d){throw Error(ze(d,"Content formatting failed"),{cause:d})}i?.throwIfAborted();let u={beforeWrite:async(d)=>{i?.throwIfAborted(),await this.contentService.authorizeGenerationWrite(e,d)},...i&&{signal:i},conditionalWrite:{expectedRevision:e.expectedRevision}};if(a)await this.entityService.updateEntity({entity:{...a.entity,content:c,metadata:o.metadata},options:u});else await this.entityService.createEntity({entity:{id:o.entityId,entityType:o.entityType,content:c,metadata:o.metadata,visibility:o.visibility},options:u});try{await n.report({progress:3,total:3,message:`Completed content generation for: ${e.templateName}`})}catch(d){this.logger.warn("Completion report failed after commit",{jobId:t,error:d})}return{entityType:o.entityType,entityId:o.entityId}}catch(o){throw i?.throwIfAborted(),this.logger.error("Content generation job failed",{jobId:t,templateName:e.templateName,error:o}),o}}validateAndParse(e){let t=au.safeParse(e);if(!t.success)return this.logger.warn("Invalid content generation job data",{validationError:t.error.issues}),null;return t.data}}var aK=r.record(r.string(),r.unknown());function _v(e,t){let n=aK.safeParse(e);return n.success&&t.every((i)=>(i in n.data))}class fl{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(`
|
|
111
111
|
`)}formatTable(e,t){let n=`| ${e.join(" | ")} |`,i=`| ${e.map(()=>"---").join(" | ")} |`,o=t.map((a)=>`| ${a.map((s)=>String(s??"")).join(" | ")} |`).join(`
|
|
112
112
|
`);return`${n}
|
|
@@ -124,7 +124,7 @@ Instructions:
|
|
|
124
124
|
2. Search through available entities for relevant information
|
|
125
125
|
3. Provide accurate, contextual responses based on the data
|
|
126
126
|
4. If information is missing, clearly state what additional data might be helpful
|
|
127
|
-
5. Structure your response clearly and concisely`,dataSourceId:"shell:ai-content",requiredPermission:"public",useKnowledgeContext:!0,schema:MA,formatter:new lu};var hK=r.object({type:r.string().describe("Type of source (e.g., note, article)"),title:r.string().describe("Title or identifier of the source"),relevance:r.number().min(0).max(1).describe("Relevance score")}),DA=r.object({answer:r.string().describe("The answer to the user's query"),sources:r.array(hK).optional().describe("Sources used to generate the answer"),confidence:r.enum(["high","medium","low"]).optional().describe("Confidence level of the answer"),suggestions:r.array(r.string()).optional().describe("Related topics or follow-up questions")});function ho(e,t){return e.parse(t)}var bK=r.object({enabled:r.boolean().describe("Whether the plugin is enabled"),debug:r.boolean().describe("Enable debug logging for this plugin")});function vK(e,t){return t.reduce((n,i)=>typeof n==="object"&&n!==null?Reflect.get(n,i):void 0,e)}function SK(e){return e.map((t)=>`${t.path||"<root>"}: ${t.message}`).join("; ")}class hl extends Error{pluginId;issues;constructor(e,t){super(`Invalid plugin config for ${e} at ${SK(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 hl(e,t.issues.map((i)=>({path:i.path.map(String).join("."),code:i.code,message:i.message,missing:i.code==="custom"&&i.params?.missing===!0||(i.code==="invalid_type"||i.code==="custom")&&vK(n,i.path)===void 0})))}}var xK=r.object({toolName:r.string(),args:r.unknown(),progressToken:r.union([r.string(),r.number()]).optional(),sendProgress:r.custom((e)=>typeof e==="function").optional(),interfaceType:r.string(),actor:si,displayName:r.string().optional(),conversationId:r.string().optional(),channelId:r.string().optional(),channelName:r.string().optional(),runId:r.string().optional(),toolCallId:r.string().optional(),userPermissionLevel:r.enum(["admin","trusted","public"]).optional(),isAnchor:r.boolean().optional(),signal:r.custom((e)=>e instanceof AbortSignal).optional()});class ts{id;version;description;packageName;config;context;retryScope;get logger(){return this.context?.logger??ei.createFresh({context:this.id})}get retries(){return this.retryScope??=new Fc({logger:this.logger}),this.retryScope}constructor(e,t,n,i){this.id=e,this.packageName=t.name,this.version=t.version,this.description=t.description??`${t.name} plugin`;let o=i.safeParse(n);if(!o.success)throw hl.fromZod(e,o.error,n);this.config=o.data}setupMessageHandlers(e){e.messaging.subscribe(Mm.toolExecute(this.id),async(t)=>{try{let n=xK.safeParse(t.payload);if(!n.success)return{success:!1,error:"Invalid tool execution request format"};let{toolName:i,args:o,progressToken:a,sendProgress:s,interfaceType:l,actor:c,displayName:u,conversationId:d,channelId:p,channelName:m,runId:g,toolCallId:f,userPermissionLevel:h,isAnchor:y,signal:w}=n.data,b=(await this.getTools()).find((S)=>S.name===i);if(!b)return{success:!1,error:`Tool not found: ${i}`};let v={interfaceType:l,actor:c,...u&&{displayName:u},...d&&{conversationId:d},...p&&{channelId:p},...m&&{channelName:m},...g&&{runId:g},...f&&{toolCallId:f},...h&&{userPermissionLevel:h},...y!==void 0&&{isAnchor:y},...w&&{signal:w},...a!==void 0&&s&&{progressToken:a,sendProgress:s}};return{success:!0,data:await b.handler(o,v)}}catch(n){return this.logger.error("Tool execution error",n),{success:!1,error:ze(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.retryScope?.dispose(),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"}}var NA=["primary","secondary"];var wK=r.custom((e)=>typeof e==="function","Expected a React component"),TK=r.strictObject({show:r.boolean().optional(),label:r.string().min(1).optional(),slot:r.enum(NA).optional(),priority:r.number().optional()}),_K=r.strictObject({id:r.string().min(1),template:r.string().min(1),content:r.unknown().optional(),dataQuery:r.looseObject({entityType:r.string().optional(),template:r.string().optional(),query:r.record(r.string(),r.unknown()).optional()}).optional(),order:r.number().optional()}),ua=r.string().regex(/^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/,{message:"must be a language tag such as en or zh-TW"}),cu=r.strictObject({title:r.string().optional(),description:r.string().optional(),navigationLabel:r.string().optional()}),CK=r.strictObject({id:r.string().min(1),path:r.string().startsWith("/"),title:r.string().optional(),pageLabel:r.string().optional(),description:r.string().optional(),sections:r.array(_K).optional(),layout:r.string().min(1).optional(),fullscreen:r.boolean().optional(),pluginId:r.string().optional(),sourceEntityType:r.string().optional(),external:r.boolean().optional(),navigation:TK.optional(),translations:r.record(ua,cu).optional()}),Cv=r.strictObject({label:r.string().min(1),pluralName:r.string().min(1).optional(),layout:r.string().min(1).optional(),detailTemplate:r.string().min(1).optional(),paginate:r.boolean().optional(),pageSize:r.number().int().positive().optional(),citable:r.boolean().optional(),navigation:r.strictObject({show:r.boolean().optional(),slot:r.enum(NA).optional(),priority:r.number().optional()}).optional()}),IK=r.strictObject({schema:r.custom((e)=>e instanceof r.ZodType,"Expected a Zod schema"),component:r.custom((e)=>typeof e==="function","Expected a React component"),title:r.string().min(1),description:r.string(),requiredPermission:r.enum(["admin","trusted","public"]).optional(),fullscreen:r.boolean().optional()}),zA=r.strictObject({namespace:r.string().min(1),sections:r.record(r.string(),IK)}),EK=r.record(r.string(),r.json()),kK=r.record(r.string(),r.record(r.string(),EK));function BA(e,t,n){if(e.toLowerCase()===t.toLowerCase())return n;let i=`/${e.toLowerCase()}`;return n==="/"?i:`${i}${n}`}var qA={layouts:r.record(r.string(),wK).refine((e)=>typeof e.default==="function",{message:'Site layouts must include a "default" component'}),routes:r.array(CK),content:kK.optional(),sections:r.union([zA,r.array(zA)]).optional(),themeOverride:r.string().optional(),headScripts:r.array(r.string()).optional(),entityDisplay:r.record(r.string(),Cv),staticAssets:r.record(r.string(),r.string()).optional(),languages:r.array(ua).min(1).optional()},yqe=r.strictObject(qA).partial();var LA=r.strictObject(qA).superRefine((e,t)=>{let n=e.languages??[],i=new Set;for(let[c,u]of n.entries()){let d=u.toLowerCase();if(i.has(d))t.addIssue({code:"custom",path:["languages",c],message:`Language "${u}" is declared twice`});i.add(d)}let o=n.slice(1).map((c)=>`/${c.toLowerCase()}`),a=new Set;for(let[c,u]of e.routes.entries()){if(a.has(u.id))t.addIssue({code:"custom",path:["routes",c,"id"],message:`Duplicate route id "${u.id}"`});a.add(u.id);let d=u.path.toLowerCase(),p=o.find((g)=>d===g||d.startsWith(`${g}/`));if(p)t.addIssue({code:"custom",path:["routes",c,"path"],message:`Route path "${u.path}" is under ${p}, where another language's pages are built`});let m=u.layout??"default";if(!e.layouts[m])t.addIssue({code:"custom",path:["routes",c,"layout"],message:`Unknown layout "${m}"`});for(let[g,f]of(u.sections??[]).entries()){let h=/^([^:.\s]+)\.([^:.\s]+)$/.exec(f.template);if(h)t.addIssue({code:"custom",path:["routes",c,"sections",g,"template"],message:`Section template "${f.template}" is written "${h[1]}:${h[2]}"`})}}let s=Array.isArray(e.sections)?e.sections:e.sections?[e.sections]:[],l=new Map(s.map((c)=>[c.namespace,c]));if(l.size!==s.length)t.addIssue({code:"custom",path:["sections"],message:"Section group namespaces must be unique"});for(let[c,u]of Object.entries(e.content??{})){let d=l.get(c);if(!d){t.addIssue({code:"custom",path:["content",c],message:`Content namespace "${c}" has no section group`});continue}for(let[p,m]of Object.entries(u)){let g=d.sections[p];if(!g){t.addIssue({code:"custom",path:["content",c,p],message:`Content section "${c}:${p}" is not defined`});continue}let f=g.schema.safeParse(m);if(!f.success)t.addIssue({code:"custom",path:["content",c,p],message:`Content does not satisfy the "${c}:${p}" schema: ${r.prettifyError(f.error)}`})}}});var FA=r.object({id:r.string(),template:r.string(),content:r.unknown().optional(),dataQuery:r.looseObject({entityType:r.string().optional(),template:r.string().optional(),query:r.looseObject({id:r.string().optional(),limit:r.number().optional(),offset:r.number().optional()}).optional()}).optional(),order:r.number().optional()}),Iv=["primary","secondary"],$A=r.object({show:r.boolean().default(!1),label:r.string().optional(),slot:r.enum(Iv).default("primary"),priority:r.number().min(0).max(100).default(50)}).optional(),jm=r.object({id:r.string(),path:r.string(),title:r.string().default(""),pageLabel:r.string().optional(),description:r.string().default(""),sections:r.array(FA).default([]),layout:r.string().default("default"),fullscreen:r.boolean().optional(),pluginId:r.string().optional(),sourceEntityType:r.string().optional(),external:r.boolean().optional(),navigation:$A,translations:r.record(ua,cu).optional()}),Ev=r.object({routes:r.array(jm),pluginId:r.string()}),RK=or({channel:"plugin:site-builder:route:register",request:Ev,response:r.void(),delivery:"command"}),UA=r.strictObject({}),ZA=r.array(jm),AK=or({channel:"site-builder:routes:list",request:UA,response:ZA,delivery:"request"}),Dm=r.object({label:r.string(),href:r.string(),priority:r.number()});var GA=r.object({pluginId:r.string(),slotName:r.string(),render:r.custom((e)=>typeof e==="function"),priority:r.number().optional()}),WA=r.strictObject({}),JA=r.array(GA),PK=or({channel:"plugin:site-builder:slots",request:WA,response:JA,delivery:"collect"});var OK="site:metadata:updated",zm=r.object({heading:r.string().describe("Main CTA heading text"),buttonText:r.string().describe("Call-to-action button text"),buttonLink:r.string().describe("URL or anchor for the CTA button")}),VA=r.object({title:r.string().optional(),description:r.string().optional(),copyright:r.string().optional(),cta:zm.optional()}),HA=r.object({blurb:r.string().optional().describe("Short italic subtitle under the section title")}),uu=r.object({represents:r.enum(["brain","anchor"]).default("anchor").describe("Identity represented by the site"),title:r.string().describe("The site's title"),description:r.string().describe("The site's description"),url:r.string().optional().describe("Canonical site URL"),copyright:r.string().optional().describe("Copyright notice text"),logo:r.boolean().optional().describe("Whether to display logo instead of title text in header"),themeMode:r.enum(["light","dark"]).optional().describe("Default theme mode"),analyticsScript:r.string().optional().describe("Analytics script HTML"),cta:zm.optional().describe("Call-to-action configuration"),sections:r.record(r.string(),HA).optional().describe("Optional per-section blurbs, keyed by section id (e.g. 'essays', 'presentations', 'about'). Used by homepage templates that render editorial section headers."),translations:r.record(ua,VA).optional().describe("The site's title, description, copyright and call to action in its other languages, keyed by language tag. A site is built in a language only once it has one.")}),KA=r.strictObject({}),MK=or({channel:"site:metadata:get",request:KA,response:uu,delivery:"request"});var jK=uu.extend({copyright:r.string(),navigation:r.object({primary:r.array(Dm),secondary:r.array(Dm)}),socialLinks:r.array(ml).optional().describe("Social media links from profile metadata")});function du(e,t){return t?e.nullable().default(null):e}function Rv(e){switch(e.type){case"string":return du(r.string(),e.optional);case"number":return du(r.number(),e.optional);case"enum":return du(r.enum(e.options),e.optional);case"object":{let t={};for(let[n,i]of Object.entries(e.fields))t[n]=Rv(i);return du(r.object(t),e.optional)}case"array":{let t=r.array(DK(e));if(e.minItems!==void 0)t=t.min(e.minItems);if(e.length!==void 0)t=t.length(e.length);return du(t,e.optional)}}}function DK(e){let{items:t}=e;switch(t.type){case"string":return r.string();case"number":return r.number();case"enum":return r.enum(t.options);case"object":{let n={};for(let[i,o]of Object.entries(t.fields))n[i]=Rv(o);return r.object(n)}}}function kv(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,i])=>kv(n,i))};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(([i,o])=>kv(i,o)),n}}}}function QA(e,t){let n={};for(let[a,s]of Object.entries(t.fields))n[a]=Rv(s);let i=r.object(n),o=new ca(i,{title:t.title,mappings:Object.entries(t.fields).map(([a,s])=>kv(a,s))});return{name:e,description:t.description,schema:i,formatter:o,requiredPermission:t.requiredPermission??"public",layout:{component:t.layout,...t.fullscreen!==void 0?{fullscreen:t.fullscreen}:{}},...t.runtimeScripts?{runtimeScripts:t.runtimeScripts}:{}}}function zK(e){let t={};for(let[n,i]of Object.entries(e.sections))t[n]=QA(n,i);return t}import{useContext as Lqe}from"react";import{createContext as NK}from"react";var YA=NK(void 0);var BK=uu.omit({url:!0,analyticsScript:!0}),XA=BK.extend({title:r.string().optional().describe("Optional site title override"),description:r.string().optional().describe("Optional site description override")});function eP(e){return XA.parse(sa(e).frontmatter)}async function qK(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 eP(n.content)}function Av(e,t={}){let n=tP(e),i=tP(t.sharedDomain??"rizom.ai").replace(/^\./,""),o=`.${i}`;if(n.endsWith(o)){let a=n.slice(0,-o.length);if(a.length>0&&!a.includes("."))return`${a}-preview.${i}`}return`preview.${n}`}function tP(e){return e.trim().replace(/^https?:\/\//i,"").replace(/\/$/,"").toLowerCase()}class nP{entityDisplay;constructor(e){this.entityDisplay=e}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`/${wh(e)}/${t}`}}var LK=r.string(),FK=r.custom((e)=>{if(!On(e))return!1;let{plugin:t,...n}=e;if(t!==void 0&&typeof t!=="function")return!1;return LA.safeParse(n).success});var Pv=r.enum(["file_operations","content_operations","data_processing","batch_processing"]),$K=r.looseObject({pluginId:r.string().optional(),progressToken:r.union([r.string(),r.number()]).optional(),operationType:Pv,operationTarget:r.string().optional(),interfaceType:r.string().optional(),conversationId:r.string().optional(),channelId:r.string().optional(),requestedByActor:si.optional(),requestedByUserId:r.string().optional(),requestedByInterface:r.string().optional(),silent:r.boolean().optional(),provenance:Gi.optional()}),ns=r.looseObject({pluginId:r.string().optional(),progressToken:r.union([r.string(),r.number()]).optional(),operationType:Pv,operationTarget:r.string().optional(),interfaceType:r.string().optional(),conversationId:r.string().optional(),channelId:r.string().optional(),requestedByActor:si.optional(),requestedByUserId:r.string().optional(),requestedByInterface:r.string().optional(),silent:r.boolean().optional(),provenance:Gi.optional(),rootJobId:r.string()}),bLe=r.enum(["none","skip","replace","coalesce"]);var UK=r.object({id:r.string(),type:r.string(),data:r.string(),status:r.enum(["pending","processing","completed","failed"]),source:r.string().nullable(),priority:r.number(),retryCount:r.number(),maxRetries:r.number(),lastError:r.string().nullable(),createdAt:r.number(),scheduledFor:r.number(),startedAt:r.number().nullable(),completedAt:r.number().nullable(),attemptId:r.string().nullable(),workerSlotId:r.string().nullable(),workerSessionId:r.string().nullable(),leaseExpiresAt:r.number().nullable(),attemptHeartbeatAt:r.number().nullable(),runtimeUpdatedAt:r.number().nullable(),metadata:ns,progress:r.custom((e)=>typeof e==="object"&&e!==null&&("progress"in e)&&typeof e.progress==="number").nullable(),result:r.unknown().nullable().optional()}),yo=15000;var Ov=r.enum(["pending","processing","completed","failed"]),rP=r.enum(["completed","failed"]),Ve={PENDING:"pending",PROCESSING:"processing",COMPLETED:"completed",FAILED:"failed"},ZK=r.object({id:r.string(),type:r.string(),status:Ov,data:r.unknown(),result:r.unknown().optional(),lastError:r.string().optional().nullable(),attempts:r.number(),maxRetries:r.number(),priority:r.number(),createdAt:r.date(),updatedAt:r.date(),processedAt:r.date().optional().nullable(),completedAt:r.date().optional().nullable(),failedAt:r.date().optional().nullable()}),GK=r.object({jobId:r.string(),type:r.string(),status:rP,result:r.unknown().optional(),error:r.string().optional()}),Mv=r.object({success:r.literal(!1),error:r.string().optional()}),Nm=r.object({id:r.string(),type:r.enum(["job","batch"]),status:Ov,message:r.string().optional(),progress:r.object({current:r.number(),total:r.number(),percentage:r.number()}).optional(),aggregationKey:r.string().optional(),batchDetails:r.object({totalOperations:r.number(),completedOperations:r.number(),failedOperations:r.number(),currentOperation:r.string().optional(),errors:r.array(r.string()).optional()}).optional(),jobDetails:r.object({jobType:r.string(),priority:r.number(),retryCount:r.number()}).optional(),metadata:ns});var ce=Lt("job_queue",{id:be("id").primaryKey().$defaultFn(()=>Bt()),type:be("type").notNull(),data:be("data").notNull(),result:be("result",{mode:"json"}),progress:be("progress",{mode:"json"}).$type(),source:be("source"),metadata:be("metadata",{mode:"json"}).$type().notNull(),status:be("status",{enum:["pending","processing","completed","failed"]}).notNull().default("pending"),priority:tt("priority").notNull().default(0),retryCount:tt("retryCount").notNull().default(0),maxRetries:tt("maxRetries").notNull().default(3),lastError:be("lastError"),createdAt:tt("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:tt("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:tt("startedAt"),completedAt:tt("completedAt"),attemptId:be("attemptId"),workerSlotId:be("workerSlotId"),workerSessionId:be("workerSessionId"),leaseExpiresAt:tt("leaseExpiresAt"),attemptHeartbeatAt:tt("attemptHeartbeatAt"),runtimeUpdatedAt:tt("runtimeUpdatedAt"),brainVersion:be("brainVersion"),brainVersionSortKey:be("brainVersionSortKey")},(e)=>({queueReadyIdx:Mt("idx_job_queue_ready").on(e.status,e.priority,e.scheduledFor),jobTypeIdx:Mt("idx_job_queue_type").on(e.type,e.status),runtimeUpdatesIdx:Mt("idx_job_queue_runtime_updates").on(e.runtimeUpdatedAt,e.id),jobSourceIdx:Mt("idx_job_queue_source").on(e.source),rootJobIdx:Mt("idx_job_queue_root_job").on(E`json_extract(${e.metadata}, '$.rootJobId')`,e.createdAt,e.id),deduplicationIdx:Mt("idx_job_queue_deduplication").on(e.type,E`json_extract(${e.metadata}, '$.deduplicationKey')`,e.status)})),_t=Lt("job_worker_sessions",{slotId:be("slotId").primaryKey(),sessionId:be("sessionId").notNull().unique(),startedAt:tt("startedAt").notNull(),heartbeatAt:tt("heartbeatAt").notNull(),expiresAt:tt("expiresAt").notNull().default(0),brainVersion:be("brainVersion"),brainVersionSortKey:be("brainVersionSortKey"),stableSlotId:be("stableSlotId")},(e)=>({heartbeatIdx:Mt("idx_job_worker_sessions_heartbeat").on(e.heartbeatAt),expiresIdx:Mt("idx_job_worker_sessions_expires").on(e.expiresAt)}));function iP(e){return Si({url:e.url,schema:{jobQueue:ce,jobWorkerSessions:_t},authToken:e.authToken,authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",contentionRetryBudgetMs:0})}class jv{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(){return this.finalizedRegistrations}getRegisteredTypes(){return[...this.handlers.keys()]}getExclusiveTypes(){return[...this.handlers].filter(([,e])=>e.exclusive===!0).map(([e])=>e)}getHandler(e){return this.handlers.get(e)}getValidator(e){return this.validators.get(e)}}var WK=r.looseObject({deduplicationKey:r.string().optional()});class Dv{findDuplicate(e,t,n){if(!t||t==="none")return null;let i=this.filterByDeduplicationKey(e,n).sort((a,s)=>s.createdAt-a.createdAt||s.id.localeCompare(a.id)),o=i.find((a)=>a.status===Ve.PENDING)??null;if(t==="skip"||t==="replace")return o;return o??i[0]??null}filterByDeduplicationKey(e,t){if(!t)return e;return e.filter((n)=>{let i=WK.safeParse(n.metadata);return i.success&&i.data.deduplicationKey===t})}}var oP=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/u,JK=/^\d+$/u,aP=r.string().regex(oP,"Brain version must be a semver version");function sP(e){return`${String(e.length).padStart(2,"0")}${e}`}function VK(e){return JK.test(e)?`0${sP(e)}`:`1${e}`}function pu(e){let t=oP.exec(e);if(!t)throw Error(`Invalid brain version "${e}"`);let[,n="",i="",o="",a]=t,s=[n,i,o].map(sP).join("");return a===void 0?`${s}~`:`${s}-${a.split(".").map(VK).join("!")}`}var HK=2000,KK=5,QK=40,YK=r.number().int().min(0).max(1000),XK=new Zy;class zv{db;transactionClient;databaseUrl;logger;deduplicator=new Dv;writeRetryBudgetMs;constructor(e,t,n,i,o){this.db=e,this.transactionClient=t,this.databaseUrl=n,this.logger=i.child("JobQueueRepository"),this.writeRetryBudgetMs=o?.writeRetryBudgetMs??HK}async insert(e){await this.write("insert",async()=>this.db.insert(ce).values(e))}async enqueueAtomic(e){return XK.run(this.databaseUrl,async()=>{let t=Date.now()+this.writeRetryBudgetMs;return this.attemptEnqueue(e,t,1)})}async attemptEnqueue(e,t,n){let i=await this.runEnqueueTransaction(e,t,n);if(i.retry)return this.attemptEnqueue(e,t,n+1);return i.decision}async runEnqueueTransaction(e,t,n){let i=await this.acquireWriteTransaction(e,t),o={prepared:!1},a=!1;try{let s=await this.decideEnqueue(i,e,()=>{o.prepared=!0});return a=!0,await i.commit(),{retry:!1,decision:s}}catch(s){let l=a&&this.isSerializationConflict(s)&&!i.closed,c=!0;if(!i.closed)try{await i.rollback()}catch(u){c=!1,this.logger.error("Failed to roll back atomic enqueue",{type:e.jobData.type,rollbackError:u})}if(o.prepared)e.onInsertRollback?.();if(!l||!c)throw s;return await this.waitForConflictRetry("commit",e,t,n,s),{retry:!0}}finally{i.close()}}async decideEnqueue(e,t,n){let{jobData:i,strategy:o,deduplicationKey:a,beforeInsert:s}=t,l=o??"none",c=async()=>{await s?.(),n()},u=async()=>{await c(),await this.insertJob(e,i)};if(l==="none")return await u(),{kind:"inserted",jobId:i.id};let d=await this.getActiveDeduplicationCandidates(e,i.type,a),p=this.deduplicator.findDuplicate(d,l,a);if(!p)return await u(),{kind:"inserted",jobId:i.id};if(l==="skip")return await this.raiseBrainVersion(e,p.id,i),{kind:"skipped",jobId:p.id};if(l==="coalesce"){if(await this.raiseBrainVersion(e,p.id,i),(await e.execute({sql:"UPDATE `job_queue` SET `scheduledFor` = ? WHERE `id` = ? AND `status` = ?",args:[Date.now(),p.id,p.status]})).rowsAffected!==1)throw Error(`Atomic coalesce lost selected job ${p.id}`);return{kind:"coalesced",jobId:p.id}}await c();let m=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:[Ve.FAILED,"Replaced by newer job",m,m,p.id,Ve.PENDING]})).rowsAffected!==1)throw Error(`Atomic replace lost selected job ${p.id}`);return await this.insertJob(e,i),{kind:"replaced",jobId:i.id,replacedJobId:p.id}}async getActiveDeduplicationCandidates(e,t,n){return(await e.execute(n?{sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ?\n AND json_extract(`metadata`, '$.deduplicationKey') = ?\n AND `status` IN (?, ?)",args:[t,n,Ve.PENDING,Ve.PROCESSING]}:{sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ? AND `status` IN (?, ?)",args:[t,Ve.PENDING,Ve.PROCESSING]})).rows.map((o)=>this.parseDeduplicationCandidate(o))}parseDeduplicationCandidate(e){let{id:t,status:n,createdAt:i,metadata:o}=e;if(typeof t!=="string"||n!==Ve.PENDING&&n!==Ve.PROCESSING||typeof i!=="number"&&typeof i!=="bigint"||typeof o!=="string")throw Error("Invalid active job row returned during atomic enqueue");let a=JSON.parse(o);return{id:t,status:n,createdAt:Number(i),metadata:a}}async raiseBrainVersion(e,t,n){if(!n.brainVersion)return;let i=pu(n.brainVersion);await e.execute({sql:"UPDATE `job_queue`\n SET `brainVersion` = ?, `brainVersionSortKey` = ?\n WHERE `id` = ?\n AND (`brainVersionSortKey` IS NULL OR `brainVersionSortKey` < ?)",args:[n.brainVersion,i,t,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`, `brainVersion`, `brainVersionSortKey`\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,t.brainVersion??null,t.brainVersion?pu(t.brainVersion):null]})).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,i,o){let a=Math.min(KK*2**(i-1),QK),s=a/2+Math.random()*(a/2);if(Date.now()+s>=n)throw this.transactionConflictError(e,t,i,o);await new Promise((l)=>setTimeout(l,s))}async retryOnConflict(e,t,n,i,o=Date.now()+this.writeRetryBudgetMs,a=1){try{return await n()}catch(s){if(!i(s))throw s;return await this.waitForConflictRetry(e,t,o,a,s),this.retryOnConflict(e,t,n,i,o,a+1)}}transactionConflictError(e,t,n,i){if(typeof t==="string")return Error(`Failed job queue write "${t}" within ${this.writeRetryBudgetMs}ms after ${n} attempts`,{cause:i});let o=t.strategy??"none",a=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: ${a})`,{cause:i})}write(e,t){return this.retryOnConflict("write",e,t,(n)=>{let i=new Set;for(let o=n;o!==void 0&&!i.has(o);){if(i.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):"",i=ze(t,"");if(/SQLITE_(?:BUSY|LOCKED)/u.test(n)||/SQLITE_(?:BUSY|LOCKED)|database is locked|transaction (?:busy|conflict)/iu.test(i))return!0;t=t instanceof Error?t.cause:void 0}return!1}async startWorkerSession(e,t,n=Date.now(),i=yo,o,a){let s=n+i,l={brainVersion:o??null,brainVersionSortKey:o?pu(o):null,stableSlotId:a??null};await this.write("start worker session",async()=>{await this.db.insert(_t).values({slotId:e,sessionId:t,startedAt:n,heartbeatAt:n,expiresAt:s,...l}).onConflictDoUpdate({target:_t.slotId,set:{sessionId:t,startedAt:n,heartbeatAt:n,expiresAt:s,...l}}),await this.pruneDeadWorkerSessions(n,i)})}async heartbeatWorkerSession(e,t,n=Date.now(),i=yo){return(await this.write("heartbeat worker session",async()=>{let a=await this.db.update(_t).set({heartbeatAt:n,expiresAt:n+i}).where(ge(W(_t.slotId,e),W(_t.sessionId,t))).returning({slotId:_t.slotId});return await this.pruneDeadWorkerSessions(n,i),a})).length===1}async pruneDeadWorkerSessions(e,t){let n=this.db.select({id:ce.id}).from(ce).where(ge(W(ce.workerSlotId,_t.slotId),W(ce.workerSessionId,_t.sessionId),W(ce.status,Ve.PROCESSING),Zn(ce.leaseExpiresAt,e)));await this.db.delete(_t).where(ge(Qn(_t.expiresAt,e-t),Jo(n)))}async endWorkerSession(e,t){return(await this.write("end worker session",async()=>this.db.delete(_t).where(ge(W(_t.slotId,e),W(_t.sessionId,t))).returning({slotId:_t.slotId}))).length===1}async complete(e,t,n){let i=Date.now(),a=(await this.write("complete",async()=>this.db.update(ce).set({status:Ve.COMPLETED,result:t,lastError:null,completedAt:i,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i)}).where(this.attemptWriteGuard(e,n)).returning({id:ce.id}))).length===1;if(a)this.logger.debug("Job completed",{jobId:e,hasResult:t!==void 0});return a}async update(e,t,n){let o=(await this.write("update",async()=>this.db.update(ce).set({data:JSON.stringify(t)}).where(this.attemptWriteGuard(e,n)).returning({id:ce.id}))).length===1;if(o)this.logger.debug("Job data updated",{jobId:e});return o}async recordAttemptProgress(e,t,n,i=Date.now()){return(await this.write("record progress",async()=>this.db.update(ce).set({attemptHeartbeatAt:i,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i),progress:n}).where(this.attemptWriteGuard(e,t)).returning({id:ce.id}))).length===1}async renewAttemptLease(e,t,n,i){return(await this.write("renew attempt lease",async()=>this.db.update(ce).set({attemptHeartbeatAt:n,leaseExpiresAt:n+i}).where(this.attemptWriteGuard(e,t)).returning({id:ce.id}))).length===1}async fail(e,t,n,i=Date.now()){let a=(await this.db.select({retryCount:ce.retryCount,maxRetries:ce.maxRetries,type:ce.type,scheduledFor:ce.scheduledFor,startedAt:ce.startedAt,runtimeUpdatedAt:ce.runtimeUpdatedAt}).from(ce).where(this.attemptWriteGuard(e,n)).limit(1))[0];if(!a)return!1;let s=a.retryCount<a.maxRetries,l=s?a.retryCount+1:a.retryCount,c=Math.min(1000*2**a.retryCount,60000),u=s?i+c:a.scheduledFor;if((await this.write("fail",async()=>this.db.update(ce).set({status:s?Ve.PENDING:Ve.FAILED,retryCount:l,lastError:t.message,scheduledFor:u,completedAt:s?null:i,runtimeUpdatedAt:s?a.runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i),startedAt:s?null:a.startedAt,attemptId:null,workerSlotId:null,workerSessionId:null,leaseExpiresAt:null,attemptHeartbeatAt:null}).where(ge(this.attemptWriteGuard(e,n),W(ce.retryCount,a.retryCount))).returning({id:ce.id}))).length!==1)return!1;if(s)this.logger.debug("Job scheduled for retry",{jobId:e,retryCount:l,backoffMs:c,scheduledFor:new Date(u).toISOString()});else this.logger.error("Job failed after max retries",{jobId:e,type:a.type,retryCount:a.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 i=(await this.write("retire unowned job",async()=>this.db.update(ce).set({status:Ve.FAILED,lastError:t,completedAt:e.now,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(e.now)}).where(ge(W(ce.id,e.jobId),W(ce.type,e.expectedType),Rn(W(ce.status,Ve.PENDING),W(ce.status,Ve.PROCESSING)),Ln(ce.attemptId),Ln(ce.workerSlotId),Ln(ce.workerSessionId),Ln(ce.leaseExpiresAt),Ln(ce.attemptHeartbeatAt),Ln(ce.progress),Ln(ce.result))).returning()))[0]??null;if(i)this.logger.warn("Retired unowned legacy job",{jobId:i.id,type:i.type,reason:t});return i}async getStatus(e){return(await this.db.select().from(ce).where(W(ce.id,e)).limit(1))[0]??null}async getJobsByRootJobId(e){return this.db.select().from(ce).where(E`json_extract(${ce.metadata}, '$.rootJobId') = ${e}`).orderBy(yt(ce.createdAt),yt(ce.id))}async getStatusByEntityId(e){return(await this.db.select().from(ce).where(E`json_extract(${ce.data}, '$.id') = ${e}`).orderBy(en(ce.createdAt)).limit(1))[0]??null}async getStats(){let e=await this.db.select({status:ce.status,count:E`count(*)`}).from(ce).groupBy(ce.status),t={pending:0,processing:0,failed:0,completed:0,total:0};for(let n of e){let i=Number(n.count);t[n.status]=i,t.total+=i}return t}async getDiagnostics(e=Date.now()){let[t,n,i]=await Promise.all([this.db.select({type:ce.type,status:ce.status,count:E`count(*)`}).from(ce).groupBy(ce.type,ce.status),this.db.select({oldestPendingAt:E`min(case when ${ce.status} = ${Ve.PENDING} then ${ce.createdAt} end)`,duePending:E`coalesce(sum(case when ${ce.status} = ${Ve.PENDING} and ${ce.scheduledFor} <= ${e} then 1 else 0 end), 0)`,oldestDuePendingAt:E`min(case when ${ce.status} = ${Ve.PENDING} and ${ce.scheduledFor} <= ${e} then ${ce.scheduledFor} end)`,latestClaimAt:E`max(${ce.startedAt})`,oldestProcessingAt:E`min(case when ${ce.status} = ${Ve.PROCESSING} then ${ce.startedAt} end)`,staleLeaseCount:E`coalesce(sum(case when ${ce.status} = ${Ve.PROCESSING} and ${ce.leaseExpiresAt} is not null and ${ce.leaseExpiresAt} <= ${e} then 1 else 0 end), 0)`}).from(ce),this.db.select({total:E`count(*)`,active:E`coalesce(sum(case when ${_t.expiresAt} > ${e} then 1 else 0 end), 0)`,stale:E`coalesce(sum(case when ${_t.expiresAt} <= ${e} then 1 else 0 end), 0)`,latestHeartbeatAt:E`max(${_t.heartbeatAt})`}).from(_t)]),o={pending:0,processing:0,completed:0,failed:0},a=t.map((u)=>{let d=Number(u.count);return o[u.status]+=d,{type:u.type,status:u.status,count:d}}),s=n[0],l=i[0],c=(u)=>u===null||u===void 0?null:Math.max(0,e-Number(u));return{totals:o,byType:a,oldestPendingAgeMs:c(s?.oldestPendingAt),duePending:Number(s?.duePending??0),oldestDuePendingAgeMs:c(s?.oldestDuePendingAt),latestClaimAgeMs:c(s?.latestClaimAt),oldestProcessingAgeMs:c(s?.oldestProcessingAt),staleLeaseCount:Number(s?.staleLeaseCount??0),workerSessions:{total:Number(l?.total??0),active:Number(l?.active??0),stale:Number(l?.stale??0),latestHeartbeatAgeMs:c(l?.latestHeartbeatAt)}}}async getRuntimeUpdates(e,t){let n=YK.parse(t);if(n===0)return[];return(await this.db.select().from(ce).where(E`(${ce.runtimeUpdatedAt}, ${ce.id}) > (${e.updatedAt}, ${e.jobId})`).orderBy(yt(ce.runtimeUpdatedAt),yt(ce.id)).limit(n)).map((o)=>({job:o,cursor:{updatedAt:o.runtimeUpdatedAt??0,jobId:o.id}}))}async cleanup(e){let t=Date.now()-e;return(await this.write("cleanup",async()=>this.db.delete(ce).where(ge(Rn(W(ce.status,Ve.COMPLETED),W(ce.status,Ve.FAILED)),Qn(ce.completedAt,t))))).rowsAffected}async getActiveJobs(e){let t=Rn(W(ce.status,Ve.PENDING),W(ce.status,Ve.PROCESSING)),n=e&&e.length>0?ge(t,Rt(ce.type,e)):t;return this.db.select().from(ce).where(n).orderBy(en(ce.createdAt))}async getRecentJobs(e,t=20){let n=e&&e.length>0?Rt(ce.type,e):void 0;return this.db.select().from(ce).where(n).orderBy(en(ce.createdAt)).limit(t)}async getFailedJobs(e){let t=W(ce.status,Ve.FAILED),n=e&&e.length>0?ge(t,Rt(ce.type,e)):t;return this.db.select().from(ce).where(n).orderBy(en(ce.createdAt))}async claimNextReady(e){let{now:t,attemptId:n,workerSlotId:i,workerSessionId:o,leaseDurationMs:a,executableTypes:s,exclusiveTypes:l=[],brainVersion:c}=e,u=c?this.brainVersionGate(c,t):{admissible:void 0,noNewerWorker:void 0},d=this.db.select({slotId:_t.slotId}).from(_t).where(ge(W(_t.slotId,i),W(_t.sessionId,o),Zn(_t.expiresAt,t))),p=this.noNewerLiveInstance(i,o,t),m=this.db.select({slotId:_t.slotId}).from(_t).where(ge(W(_t.slotId,ce.workerSlotId),W(_t.sessionId,ce.workerSessionId))),g=ge(W(ce.status,Ve.PROCESSING),Rn(Ln(ce.attemptId),Jo(m),Qn(ce.leaseExpiresAt,t))),f=cp(ce,"running"),h=this.db.select({id:f.id}).from(f).where(ge(W(f.type,ce.type),W(f.status,Ve.PROCESSING),Zn(f.leaseExpiresAt,t),E`${f.id} <> ${ce.id}`)),y=l.length===0?void 0:Rn(sp(ce.type,[...l]),Jo(h)),w=E`${ce.status} = ${Ve.PROCESSING} AND ${ce.retryCount} + 1 > ${ce.maxRetries}`,I=this.db.select({id:ce.id}).from(ce).where(ge(Rt(ce.type,s),y,u.admissible,Rn(ge(W(ce.status,Ve.PENDING),Qn(ce.scheduledFor,t)),g))).orderBy(yt(ce.priority),yt(ce.createdAt)).limit(1),v=(await this.write("claim",async()=>this.db.update(ce).set({status:E`CASE WHEN ${w} THEN ${Ve.FAILED} ELSE ${Ve.PROCESSING} END`,retryCount:E`CASE WHEN ${ce.status} = ${Ve.PROCESSING} THEN ${ce.retryCount} + 1 ELSE ${ce.retryCount} END`,lastError:E`CASE WHEN ${ce.status} = ${Ve.PROCESSING} THEN 'Attempt lease expired' ELSE ${ce.lastError} END`,startedAt:E`CASE WHEN ${w} THEN ${ce.startedAt} ELSE ${t} END`,completedAt:E`CASE WHEN ${w} THEN ${t} ELSE NULL END`,attemptId:E`CASE WHEN ${w} THEN ${ce.attemptId} ELSE ${n} END`,workerSlotId:E`CASE WHEN ${w} THEN ${ce.workerSlotId} ELSE ${i} END`,workerSessionId:E`CASE WHEN ${w} THEN ${ce.workerSessionId} ELSE ${o} END`,leaseExpiresAt:E`CASE WHEN ${w} THEN ${ce.leaseExpiresAt} ELSE ${t+a} END`,attemptHeartbeatAt:E`CASE WHEN ${w} THEN ${ce.attemptHeartbeatAt} ELSE ${t} END`,runtimeUpdatedAt:E`CASE WHEN ${w} THEN ${this.nextRuntimeUpdatedAt(t)} ELSE ${ce.runtimeUpdatedAt} END`}).where(ge(Rt(ce.id,I),Na(d),p,u.noNewerWorker)).returning()))[0];if(!v)return null;if(v.status===Ve.FAILED)return v;return this.logger.debug("Job claimed",{jobId:v.id,attemptId:v.attemptId,workerSlotId:i,workerSessionId:o}),v}noNewerLiveInstance(e,t,n){let i=cp(_t,"claimer"),o=cp(_t,"peer"),a=this.db.select({slotId:o.slotId}).from(o).innerJoin(i,ge(W(i.slotId,e),W(i.sessionId,t))).where(ge(W(o.stableSlotId,i.stableSlotId),Zn(o.expiresAt,n),Rn(Zn(o.startedAt,i.startedAt),ge(W(o.startedAt,i.startedAt),Zn(o.slotId,i.slotId)))));return Jo(a)}brainVersionGate(e,t){let n=pu(e),i=this.db.select({slotId:_t.slotId}).from(_t).where(ge(Zn(_t.expiresAt,t),Zn(_t.brainVersionSortKey,n)));return{admissible:Rn(Ln(ce.brainVersionSortKey),Qn(ce.brainVersionSortKey,n)),noNewerWorker:Jo(i)}}nextRuntimeUpdatedAt(e){return E`max(${e}, coalesce((select max(${ce.runtimeUpdatedAt}) from ${ce}), 0) + 1)`}attemptWriteGuard(e,t){return t?ge(W(ce.id,e),W(ce.status,Ve.PROCESSING),W(ce.attemptId,t)):ge(W(ce.id,e),Ln(ce.attemptId),Rn(W(ce.status,Ve.PENDING),W(ce.status,Ve.PROCESSING)))}}class Nv{client;logger;handlerRegistry;repository;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;inFlightEnqueues=0;databaseUrl;operationContext;projectionAdmission;directWorkerSlotId=`direct:${Bt()}`;directWorkerSessionId=Bt();directLeaseDurationMs;directSessionStart=null;brainVersion;close(){this.closeRequested=!0,this.closeClientWhenReady()}static createFresh(e,t,n){return new Nv(e,t??ei.getInstance(),n)}constructor(e,t,n){this.brainVersion=e.brainVersion===void 0?void 0:aP.parse(e.brainVersion);let{db:i,client:o,url:a}=iP(e);this.client=o,this.databaseUrl=a,this.logger=t.child("JobQueueService"),this.operationContext=n?.operationContext??la.createFresh(),this.projectionAdmission=n?.projectionAdmission,this.handlerRegistry=new jv(this.logger,n?.handlerRegistrationMode??"combined"),this.repository=new zv(i,o,a,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 xi(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:i}=e,o=this.handlerRegistry.getValidator(t);if(!o)throw Error(`No job type declared: ${t}`);let a=o.validateAndParse(n);if(a===null)throw Error(`Invalid job data for type: ${t}`);let s=Date.now(),l=Bt(),c=i?.rootJobId??(i?.detached?l:this.operationContext.current()?.provenance.rootJobId)??l,u=this.createJobProvenance(l,c,i),d=i?.metadata??{operationType:"data_processing"},{provenance:p,...m}=d,g={id:l,type:t,data:JSON.stringify(a),status:Ve.PENDING,priority:i?.priority??0,maxRetries:i?.maxRetries??3,retryCount:0,source:i?.source??null,metadata:{...m,...i?.deduplicationKey&&{deduplicationKey:i.deduplicationKey},rootJobId:c,provenance:u},createdAt:s,scheduledFor:i?.delayMs?s+i.delayMs:s,result:null,lastError:null,startedAt:null,completedAt:null,brainVersion:this.brainVersion},f,h=()=>{f?.rollback(),f=void 0};try{let y=await this.repository.enqueueAtomic({jobData:g,strategy:i?.deduplication,deduplicationKey:i?.deduplicationKey,beforeInsert:async()=>{f=await this.projectionAdmission?.reserveJobAdmission(u)},onInsertRollback:h});if(f?.commit(),f=void 0,y.kind==="skipped")this.logger.debug("Skipping duplicate job (already pending)",{type:t,existingJobId:y.jobId});else if(y.kind==="coalesced")this.logger.debug("Coalescing with existing job",{type:t,existingJobId:y.jobId});else{if(y.kind==="replaced")this.logger.debug("Replacing duplicate job",{type:t,oldJobId:y.replacedJobId});this.logger.debug("Job enqueued",{id:y.jobId,type:t,priority:g.priority,rootJobId:g.metadata.rootJobId})}return y.jobId}catch(y){throw h(),this.logger.error("Failed to enqueue job",{type:t,error:ze(y)}),y}}createJobProvenance(e,t,n){let i=this.operationContext.current(),o=n?.metadata.provenance??i?.provenance,a=o?.rootJobId===t?o:void 0,s=i?.provenance.rootJobId===t?i.operationId:void 0,l=n?.projection,c=l?[...a?.projectionLineage??[],l.id]:[...a?.projectionLineage??[]],u=l?.id??a?.projectionId;return Gi.parse({rootJobId:t,causationId:s??a?.causationId??e,...u?{projectionId:u}:{},projectionLineage:c,...l?.sourceEntity?{sourceEntity:l.sourceEntity}:a?.sourceEntity?{sourceEntity:a.sourceEntity}:{},derivationDepth:c.length})}async dequeue(e){let t=this.handlerRegistry.getRegisteredTypes();if(t.length===0)return null;let{onTerminalReclaim:n,...i}=e??await this.getDirectClaimOptions(),o=Date.now(),a=await this.repository.claimNextReady({...i,workerSlotId:this.sessionSlotId(i.workerSlotId,i.workerSessionId),brainVersion:this.brainVersion,now:o,attemptId:Bt(),executableTypes:t,exclusiveTypes:this.handlerRegistry.getExclusiveTypes()});if(!a)return null;if(a.status===Ve.FAILED)return this.logger.warn("Expired attempt failed terminally on reclaim",{id:a.id,type:a.type,retryCount:a.retryCount}),await n?.(a),null;return this.logger.debug("Job dequeued",{id:a.id,type:a.type,priority:a.priority,retryCount:a.retryCount,attemptId:a.attemptId,workerSlotId:a.workerSlotId,workerSessionId:a.workerSessionId}),a}async startWorkerSession(e,t,n=yo){await this.repository.startWorkerSession(this.sessionSlotId(e,t),t,Date.now(),n,this.brainVersion,this.versionedSlotId(e))}heartbeatWorkerSession(e,t,n=yo){return this.repository.heartbeatWorkerSession(this.sessionSlotId(e,t),t,Date.now(),n)}endWorkerSession(e,t){return this.repository.endWorkerSession(this.sessionSlotId(e,t),t)}versionedSlotId(e){return this.brainVersion?`${e}@${this.brainVersion}`:e}sessionSlotId(e,t){return`${this.versionedSlotId(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.sessionSlotId(this.directWorkerSlotId,this.directWorkerSessionId),this.directWorkerSessionId,Date.now(),this.directLeaseDurationMs,this.brainVersion),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,i=Date.now()+(e.timeoutMs??30000),o=async(a)=>{e.signal?.throwIfAborted();let{totals:s}=await this.getDiagnostics(),c=s.pending===0&&s.processing===0?a??Date.now():null;if(c!==null&&Date.now()-c>=t)return;if(Date.now()>=i)throw Error(`Timed out waiting for the job queue to settle: ${s.pending} pending, ${s.processing} processing`);return await Bun.sleep(n),o(c)};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)}}function Bv(e){let t,n=()=>{return},i=!1,o=new Promise((s)=>{n=()=>{i=!0,s({kind:"timeout"})}}),a=()=>{if(i)return;if(t)clearTimeout(t);t=setTimeout(n,Math.max(1,e))};return a(),{expired:o,renew:a,cancel:()=>{if(i=!0,t)clearTimeout(t)}}}function lP(e,t){let n,i=(a)=>{let s=JSON.stringify([a.progress,a.total,a.message]);if(s===n)return;n=s,t()},o=(a)=>({createSub:(s)=>o(a.createSub(s)),report:async(s)=>{i(s),await a.report(s)},startHeartbeat:(s,l)=>a.startHeartbeat(s,l),stopHeartbeat:()=>a.stopHeartbeat(),toCallback:()=>{let s=a.toCallback();return async(l)=>{i(l),await s(l)}}});return o(e)}class cP extends Error{constructor(e,t){super(`Job ${e} exceeded its ${t}ms execution deadline`);this.name="JobDeadlineExceededError"}}class qv{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,i,o){return new qv(e,t,n,i,o)}constructor(e,t,n,i,o){if(this.logger=n.child("JobQueueWorker"),this.jobQueueService=e,this.progressMonitor=t,this.clock=o?.clock,this.operationContext=o?.operationContext??la.createFresh(),this.projectionBatchScope=o?.projectionBatchScope,this.config={concurrency:i?.concurrency??1,pollInterval:i?.pollInterval??1000,maxJobs:i?.maxJobs??0,autoStart:i?.autoStart??!1,workerSlotId:i?.workerSlotId??process.env.BRAIN_JOB_WORKER_SLOT_ID??"default",defaultExecutionTimeoutMs:i?.defaultExecutionTimeoutMs??300000,cancellationGraceMs:i?.cancellationGraceMs??5000,errorCallbackTimeoutMs:i?.errorCallbackTimeoutMs??1e4,leaseDurationMs:i?.leaseDurationMs??30000,attemptHeartbeatIntervalMs:i?.attemptHeartbeatIntervalMs??1e4,workerHeartbeatIntervalMs:i?.workerHeartbeatIntervalMs??5000,workerSessionTimeoutMs:i?.workerSessionTimeoutMs??yo,onUnhealthy:i?.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((a)=>{this.logger.error("Failed to auto-start JobQueueWorker",{error:a})})}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=Bt();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=we.runSync(Gt.make()),this.jobFibers=we.runSync(Gt.provide(ar.make(),this.workerScope)),this.pollFiber=we.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 we.runPromise(da.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 we.runPromise(ar.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,i=this.config.maxJobs-n-this.activeJobs.size;if(i<=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,i)}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 i=this.workerSessionId;if(!i)throw Error("Worker session is not available");let o=await this.jobQueueService.dequeue({workerSlotId:this.config.workerSlotId,workerSessionId:i,leaseDurationMs:this.config.leaseDurationMs,onTerminalReclaim:(a)=>this.emitTerminalReclaim(a)});if(!o)break;this.activeJobs.add(o.id),await we.runPromise(ar.run(t,o.id,we.promise(()=>this.processJobWrapper(o))))}}catch(e){this.logger.error("Error processing available jobs",{error:e}),this.stats.lastError=ze(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=ze(n)}finally{this.activeJobs.delete(t)}}runPollingLoop(){let t=we.suspend(()=>{if(!this.isWorkerRunning()||this.isStopRequested())return we.interrupt;return this.currentPoll=this.processAvailableJobs(),we.promise(()=>this.currentPoll??Promise.resolve()).pipe(we.andThen(we.suspend(()=>(this.currentPoll=null,!this.isWorkerRunning()||this.isStopRequested()?we.interrupt:we.void))))}).pipe(we.schedule(Ga.spaced(this.config.pollInterval)),we.asVoid);return ri(t,this.clock).pipe(we.ensuring(we.sync(()=>{this.pollFiber=null})))}requestTransition(e,t){let n=this.transitionQueue.at(-1)??this.activeTransition;if(n?.kind===e)return n.promise;let i=()=>{return},o=()=>{return},a=new Promise((l,c)=>{i=l,o=c}),s={kind:e,awaitInFlightPoll:t,promise:a,resolve:i,reject:o};return this.transitionQueue.push(s),this.runNextTransition(),a}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 we.runPromise(Gt.close(e,Qt.void))}startHeartbeatLoop(e){let t=null,n=!1,i=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(i),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: ${ze(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 i=Error("Job attempt was superseded");t.abort(i),this.markUnhealthy(i.message)},onError:(i)=>{let o=yl(i);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:ze(t)})}}async raceOutcome(e,t){let n,i=new Promise((o)=>{n=setTimeout(()=>o({kind:"timeout"}),Math.max(1,t))});try{return await Promise.race([e,i])}finally{if(n)clearTimeout(n)}}async executeWithDeadline(e,t,n,i,o=Bv(t)){let a=Promise.resolve().then(i).then((u)=>({kind:"success",value:u}),(u)=>({kind:"failure",error:u})),s=await Promise.race([a,o.expired]).finally(()=>o.cancel());if(s.kind!=="timeout"){if(s.kind==="failure")throw s.error;return s.value}let l=new cP(e,t);if(n.abort(l),(await this.raceOutcome(a,this.config.cancellationGraceMs)).kind!=="timeout")throw l;throw this.markUnhealthy(`${l.message}; handler ignored cancellation grace`),await a,l}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 l=Error(`Claimed job ${e.id} has no attempt fencing token`);return this.markUnhealthy(l.message),{jobId:e.id,type:e.type,status:Ve.FAILED,error:l.message}}let n=this.jobQueueService.getHandler(e.type);if(!n){let l=Error(`No handler registered for job type: ${e.type}`);return await this.jobQueueService.fail(e.id,l,t),{jobId:e.id,type:e.type,status:Ve.FAILED,error:l.message}}let i=new AbortController,o=this.startAttemptHeartbeat(e,i),a=!1,s=async()=>{if(a)return;a=!0,await o()};try{this.logger.debug("Processing job",{jobId:e.id,type:e.type,attemptId:t});let l=JSON.parse(e.data),c=n.validateAndParse(l);if(c===null)throw Error(`Invalid job data for type: ${e.type}`);let u=this.progressMonitor.createProgressReporter(e.id,t),d=n.executionTimeoutMs??this.config.defaultExecutionTimeoutMs,p=Bv(d),m=await this.executeWithDeadline(e.type,d,i,()=>n.process(c,e.id,lP(u,p.renew),i.signal),p);await s();let g=Mv.safeParse(m);if(g.success){let h=g.data.error??"Handler returned failure",y=Error(h);if(await this.jobQueueService.fail(e.id,y,t))await this.emitTerminalFailure(e,y,n,t);return{jobId:e.id,type:e.type,status:Ve.FAILED,error:h}}if(!await this.jobQueueService.complete(e.id,m,t))return{jobId:e.id,type:e.type,status:Ve.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:Ve.COMPLETED,result:m}}catch(l){let c=yl(l);if(await s(),await this.runHandlerErrorCallback("onError",n,e,c,t),await this.jobQueueService.fail(e.id,c,t))await this.emitTerminalFailure(e,c,n,t);return{jobId:e.id,type:e.type,status:Ve.FAILED,error:c.message}}}async runHandlerSuccessCallback(e,t,n){let i=e.onTerminalSuccess;if(!i)return;try{let o=e.validateAndParse(JSON.parse(t.data));if(o===null)return;let a=this.progressMonitor.createProgressReporter(t.id,n),s=new AbortController;await this.executeWithDeadline(`${t.type}:onTerminalSuccess`,this.config.errorCallbackTimeoutMs,s,()=>i.call(e,o,t.id,a,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,i){if((await this.jobQueueService.getStatus(e.id))?.status!==Ve.FAILED)return;await this.runHandlerErrorCallback("onTerminalError",n,e,t,i),await this.progressMonitor.handleJobStatusChange(e.id,"failed",e.metadata)}async emitTerminalReclaim(e){let t=this.jobQueueService.getHandler(e.type);if(t)await this.runHandlerErrorCallback("onTerminalError",t,e,Error(e.lastError??"Attempt lease expired"),e.attemptId??e.id);await this.progressMonitor.handleJobStatusChange(e.id,"failed",e.metadata)}async runHandlerErrorCallback(e,t,n,i,o){let a=t[e];if(!a)return;try{let s=t.validateAndParse(JSON.parse(n.data));if(s===null)return;let l=this.progressMonitor.createProgressReporter(n.id,o),c=new AbortController;await this.executeWithDeadline(`${n.type}:${e}`,this.config.errorCallbackTimeoutMs,c,()=>a.call(t,i,s,n.id,l,c.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 e4=86400000,uP=3600000;class Lv{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 Lv(e,t,n)}constructor(e,t,n){this.jobQueue=e,this.logger=t,this.clock=n?.clock}start(e=uP){return this.requestTransition("start",e)}stop(){return this.requestTransition("stop",uP)}async startCleanup(e){if(this.acceptingCleanup=!0,this.cleanupFiber)return;this.cleanupFiber=we.runFork(this.runCleanupLoop(e))}runCleanupLoop(e){let t=this.cleanupTerminalBatchMetadata().pipe(we.schedule(Ga.spaced(e)),we.asVoid);return ri(t,this.clock)}scheduleTerminalBatchCleanup(){if(!this.acceptingCleanup)return;this.cleanupSupervisor??=this.createCleanupSupervisor();let e=we.runFork(this.cleanupTerminalBatchMetadata());rs.addUnsafe(this.cleanupSupervisor.fibers,e)}async stopCleanup(){this.acceptingCleanup=!1;let e=this.cleanupFiber;if(this.cleanupFiber=null,e)await we.runPromise(da.interrupt(e));let t=this.cleanupSupervisor;if(t)await we.runPromise(rs.awaitEmpty(t.fibers));while(this.inFlightCleanups.size>0)await Promise.allSettled(this.inFlightCleanups);if(t)await we.runPromise(Gt.close(t.scope,Qt.void)),this.cleanupSupervisor=null}requestTransition(e,t){let n=this.transitionQueue.at(-1)??this.activeTransition;if(n?.kind===e)return n.promise;let i=()=>{return},o=()=>{return},a=new Promise((l,c)=>{i=l,o=c}),s={kind:e,intervalMs:t,promise:a,resolve:i,reject:o};return this.transitionQueue.push(s),this.runNextTransition(),a}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=we.runSync(Gt.make()),t=we.runSync(Gt.provide(rs.make(),e));return{scope:e,fibers:t}}cleanupTerminalBatchMetadata(){return we.tryPromise({try:()=>{let e=this.cleanup(e4);return this.inFlightCleanups.add(e),e.then(()=>this.inFlightCleanups.delete(e),()=>this.inFlightCleanups.delete(e)),e},catch:(e)=>e}).pipe(we.asVoid,we.catch((e)=>we.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,i){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 a of e){let s={...t,rootJobId:n,metadata:{...t.metadata,operationTarget:a.type}},l=await this.jobQueue.enqueue({type:a.type,data:a.data,options:s});o.push(l)}return this.logger.debug("Enqueued batch operations",{batchId:n,operationCount:e.length,jobIds:o,rootJobId:n}),this.scheduleTerminalBatchCleanup(),n}catch(a){throw this.batches.delete(n),this.logger.error("Failed to enqueue batch operations",{error:a,operationCount:e.length,enqueuedJobs:o.length}),a}}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))),i=0,o=0,a=0,s=[];for(let[u,d]of n.entries()){if(!d){o++;let p=t.operations[u],m=t.jobIds[u]??"unknown";s.push(`Missing job ${m}${p?` for ${p.type}`:""}`);continue}switch(d.status){case"completed":i++;break;case"failed":if(o++,d.lastError)s.push(d.lastError);break;case"processing":case"pending":a++;break}}a+=t.operations.length-t.jobIds.length;let l;if(a>0)l=Ve.PROCESSING;else if(o>0)l=Ve.FAILED;else l=Ve.COMPLETED;if(t.terminalAt===void 0&&(l===Ve.COMPLETED||l===Ve.FAILED))t.terminalAt=Date.now();let c;for(let u=0;u<t.jobIds.length;u++){let d=n[u];if(d&&d.status!=="completed"&&d.status!=="failed"){let p=t.operations[u];if(p)c=`Processing ${p.type}`;break}}return{batchId:e,totalOperations:t.operations.length,completedOperations:i,failedOperations:o,errors:s,status:l,currentOperation:c,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[i,o]of this.batches.entries()){if(o.terminalAt!==void 0){if(o.terminalAt<=t)this.batches.delete(i),n++;continue}if(new Date(o.startedAt).getTime()<=t){let s=await this.getBatchStatus(i);if(s&&(s.status===Ve.COMPLETED||s.status===Ve.FAILED))this.batches.delete(i),n++}}return this.logger.debug("Cleaned up batch metadata",{cleaned:n}),n}registerBatch(e,t,n,i,o){this.batches.set(e,{jobIds:t,operations:n,source:i,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 i=await this.getBatchStatus(t);if(i&&(i.status==="pending"||i.status==="processing"))e.push({batchId:t,status:i,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}}}class is{callback;heartbeatInterval;constructor(e){this.callback=e}static from(e){if(!e)return;return new is(e)}static noop(){return new is(async()=>{})}createSub(e){let{scale:t}=e??{};if(t){let{start:n,end:i}=t,o=i-n;return new is(async(a)=>{let s=n+a.progress/(a.total??100)*o;await this.callback({...a,progress:s,total:100})})}return new is(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 t4=r.preprocess((e)=>{if(typeof e!=="string")return e;return JSON.parse(e)},r.record(r.string(),r.unknown()));class Fv{jobQueueService;messageBus;batchJobManager;logger;mode;pollTimer;pollCursor={updatedAt:0,jobId:""};activePoll;stopPromise;stopped=!1;static createFresh(e,t,n,i,o="combined"){return new Fv(e,t,n,i,o)}constructor(e,t,n,i,o){this.jobQueueService=e,this.messageBus=t,this.batchJobManager=n,this.logger=i,this.mode=o}start(){if(this.stopped)throw Error("Cannot start a stopped job progress monitor");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(){return this.stopPromise??=this.stopMonitor(),this.stopPromise}async stopMonitor(){if(this.stopped=!0,this.pollTimer)clearInterval(this.pollTimer);this.pollTimer=void 0,await this.activePoll,this.logger.debug("Job progress monitor stopped")}pollDurableUpdates(){if(this.stopped)return Promise.resolve();if(this.activePoll)return this.activePoll;let e=Promise.resolve().then(()=>this.pollPage());this.activePoll=e;let t=()=>{this.activePoll=void 0};return e.then(t,t),e}async pollPage(){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})}}createProgressReporter(e,t){let n=is.from(async(i)=>{await this.emitJobProgress(e,i,t)});if(!n)throw Error("Failed to create ProgressReporter");return n}async emitBatchProgress(e,t,n){try{let i={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:i};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:mu.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(i){this.logger.error("Error emitting batch progress update",{batchId:e,error:i})}}isBatchChild(e,t){return!!t&&t!==e}get publishesEvents(){return this.mode!=="durable-writer"}async broadcastEvent(e){await this.messageBus.send({type:mu.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 i=await this.jobQueueService.getStatus(e);if(!i){this.logger.warn("Job not found for progress update",{jobId:e});return}await this.publishJobProgress(i,t)}catch(i){this.logger.error("Error emitting job progress",{jobId:e,error:i})}}async publishJobProgress(e,t){if(e.metadata.silent)return;if(this.isBatchChild(e.id,e.metadata.rootJobId))return;let n=t.total??0,i={id:e.id,type:"job",status:"processing",metadata:e.metadata,message:t.message};if(n>0)i.progress={current:t.progress,total:n,percentage:Math.round(t.progress/n*100)};await this.broadcastEvent(i)}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 i={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(i),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=t4.parse(e.result),i=n.message;if(i)return String(i);let o=n.routesBuilt;if(o!==void 0)return`${o} routes built`}catch{}return}getStats(){return{isRunning:!this.stopped&&(this.mode!=="durable-reader"||this.pollTimer!==void 0)}}async handleJobStatusChange(e,t,n){if(!this.publishesEvents)return;let i=n?ns.safeParse(n):void 0,o=i?.success?i.data:void 0;if(o?.silent)return;try{if(await this.emitJobStatusEvent(e,t),o&&this.isBatchChild(e,o.rootJobId))try{let a=o.rootJobId,s=await this.batchJobManager.getBatchStatus(a);if(s){let l=s.metadata??o;await this.emitBatchProgress(a,s,l)}}catch(a){this.logger.warn("Failed to emit batch progress",{jobId:e,rootJobId:o.rootJobId,error:a})}}catch(a){this.logger.error("Failed to handle job status change",{jobId:e,status:t,error:a})}}}var n4=r.record(r.string(),r.unknown());class gu{logger;schema;jobTypeName;executionTimeoutMs;exclusive;constructor(e,t){this.logger=e,this.schema=t.schema,this.jobTypeName=t.jobTypeName,this.executionTimeoutMs=t.executionTimeoutMs,this.exclusive=t.exclusive}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,i,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=n4.safeParse(e);return t.success?t.data:{}}}function fu(e,t,n){let i=async(a)=>{let{type:s,data:l,toolContext:c=null,options:u,projection:d}=a,p=c?dP(c):void 0,{metadata:m,...g}=u??{},f={operationType:"data_processing",pluginId:t,...m,...c&&{interfaceType:c.interfaceType,conversationId:c.conversationId,channelId:c.channelId,requestedByActor:c.actor,...p?{requestedByUserId:p}:{},requestedByInterface:c.interfaceType,...c.progressToken!==void 0&&{progressToken:c.progressToken}}};if(c&&!p)delete f.requestedByUserId;let h={...g,source:t,...u?.rootJobId&&{rootJobId:u.rootJobId},...d&&{projection:d},metadata:f},y=n&&!s.includes(":")?`${t}:${s}`:s;return e.enqueue({type:y,data:l,options:h})};async function o(a,s,l){if(!("input"in a))return i(a);let c=a.input.safeParse(s);if(!c.success)throw Error(`Invalid job data for ${a.type}: ${c.error.message}`);return i({...l,type:a.type,data:c.data})}return o}function $v(e){return(t)=>e.getValidator(t.type)!==void 0}function Uv(e,t){return async(n,i)=>{let o=i?.rootJobId??Bt(),a=n.map((l)=>({...l,type:l.type.includes(":")?l.type:`${t}:${l.type}`})),s={...i,source:t,rootJobId:o,metadata:{...i?.metadata,operationType:"batch_processing",pluginId:t}};return await e.enqueueBatch(a,s,o,t),o}}function Zv(e,t){return(n,i)=>{let o=n.includes(":")?n:`${t}:${n}`;e.registerHandler(o,i,t)}}var r4=r.custom((e)=>typeof e==="object"&&e!==null&&("safeParse"in e)),i4=r.object({name:r.string(),schema:r4});function pP(e){return i4.safeParse(e).success}function o4(e){if(!e)return;return{status:e.status,message:e.message,lastCheck:e.lastCheck?.toISOString(),details:e.details}}function mP(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:o4(t.health)})),endpoints:e.endpoints,interactions:e.interactions}}var a4="/api/chat",kt="web-chat-guest",Bm=r.strictObject({idleSeconds:r.number().int().positive().max(Math.floor(Number.MAX_SAFE_INTEGER/1000)),maxAgeSeconds:r.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"),qm=r.strictObject({visitorId:r.string().uuid(),retention:Bm}),ot=r.string().trim().min(1).max(256),IFe="x-brain-conversation-id",EFe=r.strictObject({expiresAt:r.number().int().positive(),provider:r.string().min(1),notice:r.string().min(1),deletionLimitations:r.string().min(1),retention:Bm,messageCharacters:r.number().int().positive(),canSend:r.boolean(),presentation:hP.optional()}),s4=r.strictObject({conversationId:ot,state:r.enum(["active","completed","failed","interrupted","uncertain"])}),vP=r.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),Jv=r.string().trim().min(1).max(48),Vv=r.string().datetime(),gP=r.string().regex(/^\/(?!\/)/).max(2048),bl=r.string().regex(/^(?:\/(?!\/)|https?:\/\/)/).max(2048),l4=r.looseObject({kind:r.literal("tool-approval"),id:ot,toolCallId:ot.optional(),toolName:r.string().trim().min(1).max(256),input:r.record(r.string(),r.unknown()).optional(),summary:r.string().max(4096),completionSummary:r.string().max(4096).optional(),preview:r.string().max(1e5).optional(),state:r.enum(["approval-requested","approval-responded","output-available","output-denied","output-error"]),output:r.unknown().optional(),error:r.string().max(4096).optional()}),c4=r.looseObject({entityType:r.string().trim().min(1).max(128).optional(),entityId:ot.optional(),attachmentType:r.string().trim().min(1).max(128).optional()}),u4=r.looseObject({mediaType:r.string().trim().min(1).max(255),url:bl,downloadUrl:bl.optional(),previewUrl:bl.optional(),filename:r.string().trim().min(1).max(255).optional(),sizeBytes:r.number().int().nonnegative().optional(),source:c4.optional()}),SP=r.looseObject({kind:r.literal("attachment"),id:ot,jobId:ot.optional(),title:r.string().max(4096),description:r.string().max(20000).optional(),attachment:u4}),d4=r.looseObject({id:ot,title:r.string().max(4096).optional(),source:r.string().trim().min(1).max(512),url:bl.optional(),entityType:r.string().trim().min(1).max(128).optional(),entityId:ot.optional(),excerpt:r.string().max(20000).optional(),provenance:r.record(r.string(),r.unknown()).optional(),brain:yP.optional()}),Hv=r.looseObject({kind:r.literal("sources"),id:ot,title:r.string().max(4096).optional(),sources:r.array(d4).min(1).max(100)}),p4=r.discriminatedUnion("type",[r.object({type:r.literal("prompt"),id:ot,label:r.string().trim().min(1).max(256),prompt:r.string().min(1).max(1e5),description:r.string().max(4096).optional()}),r.object({type:r.literal("event"),id:ot,label:r.string().trim().min(1).max(256),event:r.string().trim().min(1).max(256),fromState:r.string().trim().min(1).max(256).optional(),description:r.string().max(4096).optional()})]),xP=r.looseObject({kind:r.literal("actions"),id:ot,title:r.string().max(4096).optional(),actions:r.array(p4).min(1).max(100)}),wP=r.discriminatedUnion("kind",[l4,SP,Hv,xP]);function fP(e){if(!e||e.length>512)return;let t;try{t=new URL(e)}catch{return}return t.protocol==="https:"&&!t.username&&!t.password&&t.href.length<=512?t.href:void 0}function TP(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let i of e.slice(0,10)){let o=Hv.safeParse(i);if(!o.success||o.data.id!=="sources:tool-results")continue;for(let a of o.data.sources){if(t.length>=15)break;if(!a.entityType||!a.entityId||a.entityId.length>256||a.source!==a.entityType||a.id!==`${a.entityType}:${a.entityId}`||n.has(a.id))continue;n.add(a.id);let s=fP(a.url),l=fP(a.brain?.url);t.push({id:a.id,source:a.entityType,entityType:a.entityType,entityId:a.entityId,title:(a.title??a.entityId).slice(0,160),...a.excerpt?{excerpt:a.excerpt.slice(0,280)}:{},...s?{url:s}:{},...a.brain?{brain:{name:a.brain.name.slice(0,120),...l?{url:l}:{}}}:{}})}}return t.length?[{kind:"sources",id:"sources:tool-results",title:"Retrieved sources",sources:t}]:[]}var m4=r.object({id:ot,toolCallId:ot.optional(),toolName:r.string().trim().min(1).max(256),summary:r.string().max(4096),completionSummary:r.string().max(4096).optional(),preview:r.string().max(1e5).optional(),args:r.unknown()}),_P=r.object({toolName:r.string().trim().min(1).max(256),args:r.record(r.string(),r.unknown()).optional(),jobId:ot.optional(),data:r.unknown().optional(),error:r.object({message:r.string().max(4096),code:r.string().trim().min(1).max(256).optional()}).optional()}),kFe=r.looseObject({text:r.string().max(1e6),toolResults:r.array(_P).max(100).optional(),cards:r.array(wP).max(100).optional(),pendingConfirmations:r.array(m4).max(100).optional(),usage:r.object({promptTokens:r.number().int().nonnegative(),completionTokens:r.number().int().nonnegative(),totalTokens:r.number().int().nonnegative()})});function RFe(e=a4){let t=g4(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 g4(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 f4=r.strictObject({version:r.literal(1),sourceId:r.string().trim().regex(/^[a-z][a-z0-9-]*$/).max(64),itemId:r.string().trim().min(1).max(300),titleSeed:r.string().trim().min(1).max(160).refine((e)=>!/[\p{Cc}\p{Cf}]/u.test(e))}),AFe=r.object({query:r.string().trim().max(200).default(""),archived:r.boolean().default(!1),offset:r.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).default(0),limit:r.number().int().min(1).max(100).default(25)}),h4=r.looseObject({id:ot,title:Jv,lastActiveAt:Vv,archived:r.boolean().optional(),contextHandoff:f4.optional()}),PFe=r.looseObject({sessions:r.array(h4).max(100)}),y4=r.looseObject({kind:r.string().trim().min(1).max(64),id:ot}),b4=r.looseObject({kind:r.literal("text"),filename:r.string().trim().min(1).max(255),mediaType:r.string().trim().min(1).max(255),sizeBytes:r.number().int().nonnegative(),createdAt:Vv,source:y4.optional()}),CP=r.looseObject({id:ot,role:r.enum(["user","assistant"]),content:r.string().max(1e6),attachments:r.array(b4).max(100).optional(),cards:r.array(wP).max(100).optional(),askedBefore:Wv.optional()}),OFe=r.looseObject({messages:r.array(CP).max(100)}),MFe=r.string().min(1).max(256).refine((e)=>e.trim().length>0),jFe=r.strictObject({messages:r.array(CP).max(100),submission:s4.nullable()}),DFe=r.object({type:r.literal("text"),text:r.string().max(1e6)}),zFe=r.object({type:r.literal("file"),mediaType:r.string().trim().min(1).max(255).optional(),filename:r.string().trim().min(1).max(255).optional(),url:r.string().min(1).max(2000000)}),IP=r.object({kind:r.literal("upload"),id:vP}),NFe=r.object({type:r.literal("data-upload"),data:r.looseObject({ref:IP})}),v4=r.object({id:ot,approved:r.boolean(),toolCallId:ot.optional(),toolName:r.string().trim().min(1).max(256).optional(),input:r.record(r.string(),r.unknown()).optional(),title:r.string().max(4096).optional()}),BFe=r.looseObject({state:r.literal("approval-responded"),toolCallId:ot.optional(),toolName:r.string().trim().min(1).max(256).optional(),input:r.record(r.string(),r.unknown()).optional(),title:r.string().max(4096).optional(),approval:v4}),S4=r.object({id:ot.optional(),role:r.enum(["user","assistant","system"]),parts:r.array(r.unknown()).max(1000).optional(),content:r.string().max(1e6).optional()}),qFe=r.object({id:ot.optional(),messages:r.array(S4).min(1).max(200),trigger:r.string().trim().min(1).max(64).optional()}).strict(),LFe=r.strictObject({id:ot.optional(),messages:r.array(r.strictObject({id:ot,role:r.literal("user"),parts:r.array(r.strictObject({type:r.literal("text"),text:r.string()})).min(1).max(16)})).length(1)}),EP=r.enum(["pending","processing","completed","failed"]),x4=r.looseObject({type:r.enum(["job","batch"]),status:EP,operationType:r.enum(["file_operations","content_operations","data_processing","batch_processing"]),operationTarget:r.string().max(1024).optional(),message:r.string().max(4096).optional(),progress:r.object({current:r.number().nonnegative(),total:r.number().nonnegative(),percentage:r.number().min(0).max(100)}).optional()}),w4=r.looseObject({status:r.enum(["tool-running","tool-completed","tool-awaiting-approval","tool-failed"]),toolName:r.string().trim().min(1).max(256),error:r.string().max(4096).optional()}),FFe=r.discriminatedUnion("type",[r.looseObject({type:r.literal("start"),messageId:ot.optional()}),r.looseObject({type:r.literal("start-step")}),r.looseObject({type:r.literal("finish-step")}),r.looseObject({type:r.literal("finish"),finishReason:r.enum(["length","error","stop","content-filter","tool-calls","other"]).optional()}),r.looseObject({type:r.literal("abort"),reason:r.string().max(4096).optional()}),r.looseObject({type:r.literal("error"),errorText:r.string().max(20000)}),r.looseObject({type:r.literal("text-start"),id:ot}),r.looseObject({type:r.literal("text-delta"),id:ot,delta:r.string().max(1e6)}),r.looseObject({type:r.literal("text-end"),id:ot}),r.looseObject({type:r.literal("reasoning-start"),id:ot}),r.looseObject({type:r.literal("reasoning-delta"),id:ot,delta:r.string().max(1e6)}),r.looseObject({type:r.literal("reasoning-end"),id:ot}),r.looseObject({type:r.literal("tool-input-start"),toolCallId:ot,toolName:r.string().trim().min(1).max(256),title:r.string().max(4096).optional()}),r.looseObject({type:r.literal("tool-input-delta"),toolCallId:ot,inputTextDelta:r.string().max(1e6)}),r.looseObject({type:r.literal("tool-input-available"),toolCallId:ot,toolName:r.string().trim().min(1).max(256),input:r.unknown(),title:r.string().max(4096).optional()}),r.looseObject({type:r.literal("tool-input-error"),toolCallId:ot,toolName:r.string().trim().min(1).max(256),input:r.unknown(),errorText:r.string().max(20000),title:r.string().max(4096).optional()}),r.looseObject({type:r.literal("tool-approval-request"),approvalId:ot,toolCallId:ot}),r.looseObject({type:r.literal("tool-output-available"),toolCallId:ot,output:r.unknown(),preliminary:r.boolean().optional()}),r.looseObject({type:r.literal("tool-output-error"),toolCallId:ot,errorText:r.string().max(20000)}),r.looseObject({type:r.literal("tool-output-denied"),toolCallId:ot}),r.looseObject({type:r.literal("source-url"),sourceId:ot,url:bl,title:r.string().max(4096).optional()}),r.looseObject({type:r.literal("source-document"),sourceId:ot,mediaType:r.string().trim().min(1).max(255),title:r.string().max(4096),filename:r.string().trim().min(1).max(255).optional()}),r.looseObject({type:r.literal("file"),url:bl,mediaType:r.string().trim().min(1).max(255)}),r.looseObject({type:r.literal("data-progress"),id:ot.optional(),data:x4,transient:r.boolean().optional()}),r.looseObject({type:r.literal("data-status"),id:ot.optional(),data:w4,transient:r.boolean().optional()}),r.looseObject({type:r.literal("data-tool-result"),id:ot.optional(),data:_P,transient:r.boolean().optional()}),r.looseObject({type:r.literal("data-actions"),id:ot.optional(),data:xP,transient:r.boolean().optional()}),r.looseObject({type:r.literal("data-sources"),id:ot.optional(),data:Hv,transient:r.boolean().optional()}),r.looseObject({type:r.literal("data-asked-before"),id:ot.optional(),data:Wv,transient:r.boolean().optional()}),r.looseObject({type:r.literal("data-attachment"),id:ot.optional(),data:SP,transient:r.boolean().optional()})]),$Fe=r.strictObject({conversationId:ot}),UFe=r.object({title:Jv}).strict(),ZFe=r.object({renamed:r.boolean(),title:Jv}),GFe=r.object({archived:r.boolean()}),WFe=r.object({deleted:r.boolean()}),JFe=r.object({conversationId:ot,action:bP}).strict(),VFe=r.looseObject({id:ot,status:EP,message:r.string().max(4096).optional()}),HFe=r.looseObject({id:vP,ref:IP,filename:r.string().trim().min(1).max(255),mediaType:r.string().trim().min(1).max(255),sizeBytes:r.number().int().nonnegative(),createdAt:Vv,url:gP,downloadUrl:gP}).refine((e)=>e.id===e.ref.id,{path:["ref","id"],message:"Upload response ids must match"});var Ne=Lt("conversations",{id:be("id").primaryKey(),sessionId:be("session_id").notNull(),interfaceType:be("interface_type").notNull(),channelId:be("channel_id").notNull(),personId:be("person_id"),started:be("started").notNull(),lastActive:be("last_active").notNull(),metadata:be("metadata"),created:be("created").notNull(),updated:be("updated").notNull()},(e)=>({sessionIdx:Mt("idx_conversations_session").on(e.sessionId),channelIdx:Mt("idx_conversations_channel").on(e.channelId),personIdx:Mt("idx_conversations_person").on(e.personId),interfaceSessionIdx:Mt("idx_conversations_interface_session").on(e.interfaceType,e.sessionId),interfaceChannelIdx:Mt("idx_conversations_interface_channel").on(e.interfaceType,e.channelId)})),jn=Lt("messages",{id:be("id").primaryKey(),conversationId:be("conversation_id").notNull().references(()=>Ne.id,{onDelete:"cascade"}),role:be("role").notNull(),content:be("content").notNull(),timestamp:be("timestamp").notNull(),metadata:be("metadata")},(e)=>({conversationIdx:Mt("idx_messages_conversation").on(e.conversationId),timestampIdx:Mt("idx_messages_timestamp").on(e.timestamp)})),as=Lt("summary_tracking",{conversationId:be("conversation_id").primaryKey().references(()=>Ne.id,{onDelete:"cascade"}),lastSummarizedAt:be("last_summarized_at"),lastMessageId:be("last_message_id"),messagesSinceSummary:tt("messages_since_summary").default(0),updated:be("updated").notNull()});function kP(e){return Si({url:e.url,schema:{conversations:Ne,messages:jn,summaryTracking:as},authToken:e.authToken,authTokenEnv:"CONVERSATION_DATABASE_AUTH_TOKEN"})}var T4=r.preprocess((e)=>{if(typeof e!=="string")return e;try{return JSON.parse(e)}catch{return}},r.record(r.string(),r.unknown())).catch({});function bo(e){return T4.parse(e)}var Lm="conversation:messageAdded",Fm="conversation:guestMessageAdded",Kv="conversation:started",yu=r.object({identity:si,interfaceType:r.string(),role:pl,displayName:r.string().optional(),username:r.string().optional(),isBot:r.boolean().optional()}),_4=r.preprocess(C4,yu);function C4(e){if(!On(e)||"identity"in e)return e;let{actorId:t,interfaceType:n,role:i}=e;if(typeof t!=="string"||typeof n!=="string"||i!=="user"&&i!=="assistant")return e;let{userId:o,canonicalId:a}=e;return{identity:RP({actorId:t,interfaceType:n,role:i,...typeof o==="string"?{userId:o}:{},...typeof a==="string"?{canonicalId:a}:{}}),interfaceType:n,role:i,...typeof e.displayName==="string"?{displayName:e.displayName}:{},...typeof e.username==="string"?{username:e.username}:{},...typeof e.isBot==="boolean"?{isBot:e.isBot}:{}}}var bu=r.object({messageId:r.string().optional(),channelId:r.string().optional(),channelName:r.string().optional(),threadId:r.string().optional(),metadata:r.record(r.string(),r.unknown()).optional()}),AP=r.looseObject({actor:_4.optional(),source:bu.optional(),spaceId:r.string().min(1).optional()});function PP(e){if(typeof e==="string")try{let t=JSON.parse(e);return On(t)?t:null}catch{return null}return On(e)?e:null}function I4(e){if(e.role!=="assistant")return!1;if(e.content.trim().length===0)return!1;let t=PP(e.metadata),n=t?.entityMemoryRefs;if(Array.isArray(n)&&n.length>0)return!1;let i=t?.cards;if(!Array.isArray(i))return!0;return!i.some((o)=>{if(!On(o))return!1;if(o.kind==="tool-approval")return!0;return o.kind==="actions"&&o.id==="actions:upload-intent"})}var c$e=r.object({id:r.string(),conversationId:r.string(),role:r.string(),content:r.string(),timestamp:r.string(),metadata:r.string().nullable()});var Ci=E`strftime('%Y-%m-%dT%H:%M:%fZ', 'now')`;function Qv(){return MP(!1)}function OP(){return MP(!0)}function MP(e){let t=Bm.shape.maxAgeSeconds.maxValue,n=E`(
|
|
127
|
+
5. Structure your response clearly and concisely`,dataSourceId:"shell:ai-content",requiredPermission:"public",useKnowledgeContext:!0,schema:MA,formatter:new lu};var hK=r.object({type:r.string().describe("Type of source (e.g., note, article)"),title:r.string().describe("Title or identifier of the source"),relevance:r.number().min(0).max(1).describe("Relevance score")}),DA=r.object({answer:r.string().describe("The answer to the user's query"),sources:r.array(hK).optional().describe("Sources used to generate the answer"),confidence:r.enum(["high","medium","low"]).optional().describe("Confidence level of the answer"),suggestions:r.array(r.string()).optional().describe("Related topics or follow-up questions")});function ho(e,t){return e.parse(t)}var bK=r.object({enabled:r.boolean().describe("Whether the plugin is enabled"),debug:r.boolean().describe("Enable debug logging for this plugin")});function vK(e,t){return t.reduce((n,i)=>typeof n==="object"&&n!==null?Reflect.get(n,i):void 0,e)}function SK(e){return e.map((t)=>`${t.path||"<root>"}: ${t.message}`).join("; ")}class hl extends Error{pluginId;issues;constructor(e,t){super(`Invalid plugin config for ${e} at ${SK(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 hl(e,t.issues.map((i)=>({path:i.path.map(String).join("."),code:i.code,message:i.message,missing:i.code==="custom"&&i.params?.missing===!0||(i.code==="invalid_type"||i.code==="custom")&&vK(n,i.path)===void 0})))}}var xK=r.object({toolName:r.string(),args:r.unknown(),progressToken:r.union([r.string(),r.number()]).optional(),sendProgress:r.custom((e)=>typeof e==="function").optional(),interfaceType:r.string(),actor:si,displayName:r.string().optional(),conversationId:r.string().optional(),channelId:r.string().optional(),channelName:r.string().optional(),runId:r.string().optional(),toolCallId:r.string().optional(),userPermissionLevel:r.enum(["admin","trusted","public"]).optional(),isAnchor:r.boolean().optional(),signal:r.custom((e)=>e instanceof AbortSignal).optional()});class ts{id;version;description;packageName;config;context;retryScope;get logger(){return this.context?.logger??ei.createFresh({context:this.id})}get retries(){return this.retryScope??=new Fc({logger:this.logger}),this.retryScope}constructor(e,t,n,i){this.id=e,this.packageName=t.name,this.version=t.version,this.description=t.description??`${t.name} plugin`;let o=i.safeParse(n);if(!o.success)throw hl.fromZod(e,o.error,n);this.config=o.data}setupMessageHandlers(e){e.messaging.subscribe(Mm.toolExecute(this.id),async(t)=>{try{let n=xK.safeParse(t.payload);if(!n.success)return{success:!1,error:"Invalid tool execution request format"};let{toolName:i,args:o,progressToken:a,sendProgress:s,interfaceType:l,actor:c,displayName:u,conversationId:d,channelId:p,channelName:m,runId:g,toolCallId:f,userPermissionLevel:h,isAnchor:y,signal:w}=n.data,b=(await this.getTools()).find((S)=>S.name===i);if(!b)return{success:!1,error:`Tool not found: ${i}`};let v={interfaceType:l,actor:c,...u&&{displayName:u},...d&&{conversationId:d},...p&&{channelId:p},...m&&{channelName:m},...g&&{runId:g},...f&&{toolCallId:f},...h&&{userPermissionLevel:h},...y!==void 0&&{isAnchor:y},...w&&{signal:w},...a!==void 0&&s&&{progressToken:a,sendProgress:s}};return{success:!0,data:await b.handler(o,v)}}catch(n){return this.logger.error("Tool execution error",n),{success:!1,error:ze(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.retryScope?.dispose(),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"}}var NA=["primary","secondary"];var wK=r.custom((e)=>typeof e==="function","Expected a React component"),TK=r.strictObject({show:r.boolean().optional(),label:r.string().min(1).optional(),slot:r.enum(NA).optional(),priority:r.number().optional()}),_K=r.strictObject({id:r.string().min(1),template:r.string().min(1),content:r.unknown().optional(),dataQuery:r.looseObject({entityType:r.string().optional(),template:r.string().optional(),query:r.record(r.string(),r.unknown()).optional()}).optional(),order:r.number().optional()}),ua=r.string().regex(/^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/,{message:"must be a language tag such as en or zh-TW"}),cu=r.strictObject({title:r.string().optional(),description:r.string().optional(),navigationLabel:r.string().optional()}),CK=r.strictObject({id:r.string().min(1),path:r.string().startsWith("/"),title:r.string().optional(),pageLabel:r.string().optional(),description:r.string().optional(),sections:r.array(_K).optional(),layout:r.string().min(1).optional(),fullscreen:r.boolean().optional(),pluginId:r.string().optional(),sourceEntityType:r.string().optional(),external:r.boolean().optional(),navigation:TK.optional(),translations:r.record(ua,cu).optional()}),Cv=r.strictObject({label:r.string().min(1),pluralName:r.string().min(1).optional(),layout:r.string().min(1).optional(),detailTemplate:r.string().min(1).optional(),paginate:r.boolean().optional(),pageSize:r.number().int().positive().optional(),citable:r.boolean().optional(),navigation:r.strictObject({show:r.boolean().optional(),slot:r.enum(NA).optional(),priority:r.number().optional()}).optional()}),IK=r.strictObject({schema:r.custom((e)=>e instanceof r.ZodType,"Expected a Zod schema"),component:r.custom((e)=>typeof e==="function","Expected a React component"),title:r.string().min(1),description:r.string(),requiredPermission:r.enum(["admin","trusted","public"]).optional(),fullscreen:r.boolean().optional()}),zA=r.strictObject({namespace:r.string().min(1),sections:r.record(r.string(),IK)}),EK=r.record(r.string(),r.json()),kK=r.record(r.string(),r.record(r.string(),EK));function BA(e,t,n){if(e.toLowerCase()===t.toLowerCase())return n;let i=`/${e.toLowerCase()}`;return n==="/"?i:`${i}${n}`}var qA={layouts:r.record(r.string(),wK).refine((e)=>typeof e.default==="function",{message:'Site layouts must include a "default" component'}),routes:r.array(CK),content:kK.optional(),sections:r.union([zA,r.array(zA)]).optional(),themeOverride:r.string().optional(),headScripts:r.array(r.string()).optional(),entityDisplay:r.record(r.string(),Cv),staticAssets:r.record(r.string(),r.string()).optional(),languages:r.array(ua).min(1).optional()},yqe=r.strictObject(qA).partial();var LA=r.strictObject(qA).superRefine((e,t)=>{let n=e.languages??[],i=new Set;for(let[c,u]of n.entries()){let d=u.toLowerCase();if(i.has(d))t.addIssue({code:"custom",path:["languages",c],message:`Language "${u}" is declared twice`});i.add(d)}let o=n.slice(1).map((c)=>`/${c.toLowerCase()}`),a=new Set;for(let[c,u]of e.routes.entries()){if(a.has(u.id))t.addIssue({code:"custom",path:["routes",c,"id"],message:`Duplicate route id "${u.id}"`});a.add(u.id);let d=u.path.toLowerCase(),p=o.find((g)=>d===g||d.startsWith(`${g}/`));if(p)t.addIssue({code:"custom",path:["routes",c,"path"],message:`Route path "${u.path}" is under ${p}, where another language's pages are built`});let m=u.layout??"default";if(!e.layouts[m])t.addIssue({code:"custom",path:["routes",c,"layout"],message:`Unknown layout "${m}"`});for(let[g,f]of(u.sections??[]).entries()){let h=/^([^:.\s]+)\.([^:.\s]+)$/.exec(f.template);if(h)t.addIssue({code:"custom",path:["routes",c,"sections",g,"template"],message:`Section template "${f.template}" is written "${h[1]}:${h[2]}"`})}}let s=Array.isArray(e.sections)?e.sections:e.sections?[e.sections]:[],l=new Map(s.map((c)=>[c.namespace,c]));if(l.size!==s.length)t.addIssue({code:"custom",path:["sections"],message:"Section group namespaces must be unique"});for(let[c,u]of Object.entries(e.content??{})){let d=l.get(c);if(!d){t.addIssue({code:"custom",path:["content",c],message:`Content namespace "${c}" has no section group`});continue}for(let[p,m]of Object.entries(u)){let g=d.sections[p];if(!g){t.addIssue({code:"custom",path:["content",c,p],message:`Content section "${c}:${p}" is not defined`});continue}let f=g.schema.safeParse(m);if(!f.success)t.addIssue({code:"custom",path:["content",c,p],message:`Content does not satisfy the "${c}:${p}" schema: ${r.prettifyError(f.error)}`})}}});var FA=r.object({id:r.string(),template:r.string(),content:r.unknown().optional(),dataQuery:r.looseObject({entityType:r.string().optional(),template:r.string().optional(),query:r.looseObject({id:r.string().optional(),limit:r.number().optional(),offset:r.number().optional()}).optional()}).optional(),order:r.number().optional()}),Iv=["primary","secondary"],$A=r.object({show:r.boolean().default(!1),label:r.string().optional(),slot:r.enum(Iv).default("primary"),priority:r.number().min(0).max(100).default(50)}).optional(),jm=r.object({id:r.string(),path:r.string(),title:r.string().default(""),pageLabel:r.string().optional(),description:r.string().default(""),sections:r.array(FA).default([]),layout:r.string().default("default"),fullscreen:r.boolean().optional(),pluginId:r.string().optional(),sourceEntityType:r.string().optional(),external:r.boolean().optional(),navigation:$A,translations:r.record(ua,cu).optional()}),Ev=r.object({routes:r.array(jm),pluginId:r.string()}),RK=or({channel:"plugin:site-builder:route:register",request:Ev,response:r.void(),delivery:"command"}),UA=r.strictObject({}),ZA=r.array(jm),AK=or({channel:"site-builder:routes:list",request:UA,response:ZA,delivery:"request"}),Dm=r.object({label:r.string(),href:r.string(),priority:r.number()});var GA=r.object({pluginId:r.string(),slotName:r.string(),render:r.custom((e)=>typeof e==="function"),priority:r.number().optional()}),WA=r.strictObject({}),JA=r.array(GA),PK=or({channel:"plugin:site-builder:slots",request:WA,response:JA,delivery:"collect"});var OK="site:metadata:updated",zm=r.object({heading:r.string().describe("Main CTA heading text"),buttonText:r.string().describe("Call-to-action button text"),buttonLink:r.string().describe("URL or anchor for the CTA button")}),VA=r.object({title:r.string().optional(),description:r.string().optional(),copyright:r.string().optional(),cta:zm.optional()}),HA=r.object({blurb:r.string().optional().describe("Short italic subtitle under the section title")}),uu=r.object({represents:r.enum(["brain","anchor"]).default("anchor").describe("Identity represented by the site"),title:r.string().describe("The site's title"),description:r.string().describe("The site's description"),url:r.string().optional().describe("Canonical site URL"),copyright:r.string().optional().describe("Copyright notice text"),logo:r.boolean().optional().describe("Whether to display logo instead of title text in header"),themeMode:r.enum(["light","dark"]).optional().describe("Default theme mode"),analyticsScript:r.string().optional().describe("Analytics script HTML"),cta:zm.optional().describe("Call-to-action configuration"),sections:r.record(r.string(),HA).optional().describe("Optional per-section blurbs, keyed by section id (e.g. 'essays', 'presentations', 'about'). Used by homepage templates that render editorial section headers."),translations:r.record(ua,VA).optional().describe("The site's title, description, copyright and call to action in its other languages, keyed by language tag. A site is built in a language only once it has one.")}),KA=r.strictObject({}),MK=or({channel:"site:metadata:get",request:KA,response:uu,delivery:"request"});var jK=uu.extend({copyright:r.string(),navigation:r.object({primary:r.array(Dm),secondary:r.array(Dm)}),socialLinks:r.array(ml).optional().describe("Social media links from profile metadata"),photo:r.string().optional().describe("The anchor's photo, as ")});function du(e,t){return t?e.nullable().default(null):e}function Rv(e){switch(e.type){case"string":return du(r.string(),e.optional);case"number":return du(r.number(),e.optional);case"enum":return du(r.enum(e.options),e.optional);case"object":{let t={};for(let[n,i]of Object.entries(e.fields))t[n]=Rv(i);return du(r.object(t),e.optional)}case"array":{let t=r.array(DK(e));if(e.minItems!==void 0)t=t.min(e.minItems);if(e.length!==void 0)t=t.length(e.length);return du(t,e.optional)}}}function DK(e){let{items:t}=e;switch(t.type){case"string":return r.string();case"number":return r.number();case"enum":return r.enum(t.options);case"object":{let n={};for(let[i,o]of Object.entries(t.fields))n[i]=Rv(o);return r.object(n)}}}function kv(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,i])=>kv(n,i))};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(([i,o])=>kv(i,o)),n}}}}function QA(e,t){let n={};for(let[a,s]of Object.entries(t.fields))n[a]=Rv(s);let i=r.object(n),o=new ca(i,{title:t.title,mappings:Object.entries(t.fields).map(([a,s])=>kv(a,s))});return{name:e,description:t.description,schema:i,formatter:o,requiredPermission:t.requiredPermission??"public",layout:{component:t.layout,...t.fullscreen!==void 0?{fullscreen:t.fullscreen}:{}},...t.runtimeScripts?{runtimeScripts:t.runtimeScripts}:{}}}function zK(e){let t={};for(let[n,i]of Object.entries(e.sections))t[n]=QA(n,i);return t}import{useContext as Lqe}from"react";import{createContext as NK}from"react";var YA=NK(void 0);var BK=uu.omit({url:!0,analyticsScript:!0}),XA=BK.extend({title:r.string().optional().describe("Optional site title override"),description:r.string().optional().describe("Optional site description override")});function eP(e){return XA.parse(sa(e).frontmatter)}async function qK(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 eP(n.content)}function Av(e,t={}){let n=tP(e),i=tP(t.sharedDomain??"rizom.ai").replace(/^\./,""),o=`.${i}`;if(n.endsWith(o)){let a=n.slice(0,-o.length);if(a.length>0&&!a.includes("."))return`${a}-preview.${i}`}return`preview.${n}`}function tP(e){return e.trim().replace(/^https?:\/\//i,"").replace(/\/$/,"").toLowerCase()}class nP{entityDisplay;constructor(e){this.entityDisplay=e}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`/${wh(e)}/${t}`}}var LK=r.string(),FK=r.custom((e)=>{if(!On(e))return!1;let{plugin:t,...n}=e;if(t!==void 0&&typeof t!=="function")return!1;return LA.safeParse(n).success});var Pv=r.enum(["file_operations","content_operations","data_processing","batch_processing"]),$K=r.looseObject({pluginId:r.string().optional(),progressToken:r.union([r.string(),r.number()]).optional(),operationType:Pv,operationTarget:r.string().optional(),interfaceType:r.string().optional(),conversationId:r.string().optional(),channelId:r.string().optional(),requestedByActor:si.optional(),requestedByUserId:r.string().optional(),requestedByInterface:r.string().optional(),silent:r.boolean().optional(),provenance:Gi.optional()}),ns=r.looseObject({pluginId:r.string().optional(),progressToken:r.union([r.string(),r.number()]).optional(),operationType:Pv,operationTarget:r.string().optional(),interfaceType:r.string().optional(),conversationId:r.string().optional(),channelId:r.string().optional(),requestedByActor:si.optional(),requestedByUserId:r.string().optional(),requestedByInterface:r.string().optional(),silent:r.boolean().optional(),provenance:Gi.optional(),rootJobId:r.string()}),bLe=r.enum(["none","skip","replace","coalesce"]);var UK=r.object({id:r.string(),type:r.string(),data:r.string(),status:r.enum(["pending","processing","completed","failed"]),source:r.string().nullable(),priority:r.number(),retryCount:r.number(),maxRetries:r.number(),lastError:r.string().nullable(),createdAt:r.number(),scheduledFor:r.number(),startedAt:r.number().nullable(),completedAt:r.number().nullable(),attemptId:r.string().nullable(),workerSlotId:r.string().nullable(),workerSessionId:r.string().nullable(),leaseExpiresAt:r.number().nullable(),attemptHeartbeatAt:r.number().nullable(),runtimeUpdatedAt:r.number().nullable(),metadata:ns,progress:r.custom((e)=>typeof e==="object"&&e!==null&&("progress"in e)&&typeof e.progress==="number").nullable(),result:r.unknown().nullable().optional()}),yo=15000;var Ov=r.enum(["pending","processing","completed","failed"]),rP=r.enum(["completed","failed"]),Ve={PENDING:"pending",PROCESSING:"processing",COMPLETED:"completed",FAILED:"failed"},ZK=r.object({id:r.string(),type:r.string(),status:Ov,data:r.unknown(),result:r.unknown().optional(),lastError:r.string().optional().nullable(),attempts:r.number(),maxRetries:r.number(),priority:r.number(),createdAt:r.date(),updatedAt:r.date(),processedAt:r.date().optional().nullable(),completedAt:r.date().optional().nullable(),failedAt:r.date().optional().nullable()}),GK=r.object({jobId:r.string(),type:r.string(),status:rP,result:r.unknown().optional(),error:r.string().optional()}),Mv=r.object({success:r.literal(!1),error:r.string().optional()}),Nm=r.object({id:r.string(),type:r.enum(["job","batch"]),status:Ov,message:r.string().optional(),progress:r.object({current:r.number(),total:r.number(),percentage:r.number()}).optional(),aggregationKey:r.string().optional(),batchDetails:r.object({totalOperations:r.number(),completedOperations:r.number(),failedOperations:r.number(),currentOperation:r.string().optional(),errors:r.array(r.string()).optional()}).optional(),jobDetails:r.object({jobType:r.string(),priority:r.number(),retryCount:r.number()}).optional(),metadata:ns});var ce=Lt("job_queue",{id:be("id").primaryKey().$defaultFn(()=>Bt()),type:be("type").notNull(),data:be("data").notNull(),result:be("result",{mode:"json"}),progress:be("progress",{mode:"json"}).$type(),source:be("source"),metadata:be("metadata",{mode:"json"}).$type().notNull(),status:be("status",{enum:["pending","processing","completed","failed"]}).notNull().default("pending"),priority:tt("priority").notNull().default(0),retryCount:tt("retryCount").notNull().default(0),maxRetries:tt("maxRetries").notNull().default(3),lastError:be("lastError"),createdAt:tt("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:tt("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:tt("startedAt"),completedAt:tt("completedAt"),attemptId:be("attemptId"),workerSlotId:be("workerSlotId"),workerSessionId:be("workerSessionId"),leaseExpiresAt:tt("leaseExpiresAt"),attemptHeartbeatAt:tt("attemptHeartbeatAt"),runtimeUpdatedAt:tt("runtimeUpdatedAt"),brainVersion:be("brainVersion"),brainVersionSortKey:be("brainVersionSortKey")},(e)=>({queueReadyIdx:Mt("idx_job_queue_ready").on(e.status,e.priority,e.scheduledFor),jobTypeIdx:Mt("idx_job_queue_type").on(e.type,e.status),runtimeUpdatesIdx:Mt("idx_job_queue_runtime_updates").on(e.runtimeUpdatedAt,e.id),jobSourceIdx:Mt("idx_job_queue_source").on(e.source),rootJobIdx:Mt("idx_job_queue_root_job").on(E`json_extract(${e.metadata}, '$.rootJobId')`,e.createdAt,e.id),deduplicationIdx:Mt("idx_job_queue_deduplication").on(e.type,E`json_extract(${e.metadata}, '$.deduplicationKey')`,e.status)})),_t=Lt("job_worker_sessions",{slotId:be("slotId").primaryKey(),sessionId:be("sessionId").notNull().unique(),startedAt:tt("startedAt").notNull(),heartbeatAt:tt("heartbeatAt").notNull(),expiresAt:tt("expiresAt").notNull().default(0),brainVersion:be("brainVersion"),brainVersionSortKey:be("brainVersionSortKey"),stableSlotId:be("stableSlotId")},(e)=>({heartbeatIdx:Mt("idx_job_worker_sessions_heartbeat").on(e.heartbeatAt),expiresIdx:Mt("idx_job_worker_sessions_expires").on(e.expiresAt)}));function iP(e){return Si({url:e.url,schema:{jobQueue:ce,jobWorkerSessions:_t},authToken:e.authToken,authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",contentionRetryBudgetMs:0})}class jv{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(){return this.finalizedRegistrations}getRegisteredTypes(){return[...this.handlers.keys()]}getExclusiveTypes(){return[...this.handlers].filter(([,e])=>e.exclusive===!0).map(([e])=>e)}getHandler(e){return this.handlers.get(e)}getValidator(e){return this.validators.get(e)}}var WK=r.looseObject({deduplicationKey:r.string().optional()});class Dv{findDuplicate(e,t,n){if(!t||t==="none")return null;let i=this.filterByDeduplicationKey(e,n).sort((a,s)=>s.createdAt-a.createdAt||s.id.localeCompare(a.id)),o=i.find((a)=>a.status===Ve.PENDING)??null;if(t==="skip"||t==="replace")return o;return o??i[0]??null}filterByDeduplicationKey(e,t){if(!t)return e;return e.filter((n)=>{let i=WK.safeParse(n.metadata);return i.success&&i.data.deduplicationKey===t})}}var oP=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)?$/u,JK=/^\d+$/u,aP=r.string().regex(oP,"Brain version must be a semver version");function sP(e){return`${String(e.length).padStart(2,"0")}${e}`}function VK(e){return JK.test(e)?`0${sP(e)}`:`1${e}`}function pu(e){let t=oP.exec(e);if(!t)throw Error(`Invalid brain version "${e}"`);let[,n="",i="",o="",a]=t,s=[n,i,o].map(sP).join("");return a===void 0?`${s}~`:`${s}-${a.split(".").map(VK).join("!")}`}var HK=2000,KK=5,QK=40,YK=r.number().int().min(0).max(1000),XK=new Zy;class zv{db;transactionClient;databaseUrl;logger;deduplicator=new Dv;writeRetryBudgetMs;constructor(e,t,n,i,o){this.db=e,this.transactionClient=t,this.databaseUrl=n,this.logger=i.child("JobQueueRepository"),this.writeRetryBudgetMs=o?.writeRetryBudgetMs??HK}async insert(e){await this.write("insert",async()=>this.db.insert(ce).values(e))}async enqueueAtomic(e){return XK.run(this.databaseUrl,async()=>{let t=Date.now()+this.writeRetryBudgetMs;return this.attemptEnqueue(e,t,1)})}async attemptEnqueue(e,t,n){let i=await this.runEnqueueTransaction(e,t,n);if(i.retry)return this.attemptEnqueue(e,t,n+1);return i.decision}async runEnqueueTransaction(e,t,n){let i=await this.acquireWriteTransaction(e,t),o={prepared:!1},a=!1;try{let s=await this.decideEnqueue(i,e,()=>{o.prepared=!0});return a=!0,await i.commit(),{retry:!1,decision:s}}catch(s){let l=a&&this.isSerializationConflict(s)&&!i.closed,c=!0;if(!i.closed)try{await i.rollback()}catch(u){c=!1,this.logger.error("Failed to roll back atomic enqueue",{type:e.jobData.type,rollbackError:u})}if(o.prepared)e.onInsertRollback?.();if(!l||!c)throw s;return await this.waitForConflictRetry("commit",e,t,n,s),{retry:!0}}finally{i.close()}}async decideEnqueue(e,t,n){let{jobData:i,strategy:o,deduplicationKey:a,beforeInsert:s}=t,l=o??"none",c=async()=>{await s?.(),n()},u=async()=>{await c(),await this.insertJob(e,i)};if(l==="none")return await u(),{kind:"inserted",jobId:i.id};let d=await this.getActiveDeduplicationCandidates(e,i.type,a),p=this.deduplicator.findDuplicate(d,l,a);if(!p)return await u(),{kind:"inserted",jobId:i.id};if(l==="skip")return await this.raiseBrainVersion(e,p.id,i),{kind:"skipped",jobId:p.id};if(l==="coalesce"){if(await this.raiseBrainVersion(e,p.id,i),(await e.execute({sql:"UPDATE `job_queue` SET `scheduledFor` = ? WHERE `id` = ? AND `status` = ?",args:[Date.now(),p.id,p.status]})).rowsAffected!==1)throw Error(`Atomic coalesce lost selected job ${p.id}`);return{kind:"coalesced",jobId:p.id}}await c();let m=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:[Ve.FAILED,"Replaced by newer job",m,m,p.id,Ve.PENDING]})).rowsAffected!==1)throw Error(`Atomic replace lost selected job ${p.id}`);return await this.insertJob(e,i),{kind:"replaced",jobId:i.id,replacedJobId:p.id}}async getActiveDeduplicationCandidates(e,t,n){return(await e.execute(n?{sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ?\n AND json_extract(`metadata`, '$.deduplicationKey') = ?\n AND `status` IN (?, ?)",args:[t,n,Ve.PENDING,Ve.PROCESSING]}:{sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ? AND `status` IN (?, ?)",args:[t,Ve.PENDING,Ve.PROCESSING]})).rows.map((o)=>this.parseDeduplicationCandidate(o))}parseDeduplicationCandidate(e){let{id:t,status:n,createdAt:i,metadata:o}=e;if(typeof t!=="string"||n!==Ve.PENDING&&n!==Ve.PROCESSING||typeof i!=="number"&&typeof i!=="bigint"||typeof o!=="string")throw Error("Invalid active job row returned during atomic enqueue");let a=JSON.parse(o);return{id:t,status:n,createdAt:Number(i),metadata:a}}async raiseBrainVersion(e,t,n){if(!n.brainVersion)return;let i=pu(n.brainVersion);await e.execute({sql:"UPDATE `job_queue`\n SET `brainVersion` = ?, `brainVersionSortKey` = ?\n WHERE `id` = ?\n AND (`brainVersionSortKey` IS NULL OR `brainVersionSortKey` < ?)",args:[n.brainVersion,i,t,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`, `brainVersion`, `brainVersionSortKey`\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,t.brainVersion??null,t.brainVersion?pu(t.brainVersion):null]})).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,i,o){let a=Math.min(KK*2**(i-1),QK),s=a/2+Math.random()*(a/2);if(Date.now()+s>=n)throw this.transactionConflictError(e,t,i,o);await new Promise((l)=>setTimeout(l,s))}async retryOnConflict(e,t,n,i,o=Date.now()+this.writeRetryBudgetMs,a=1){try{return await n()}catch(s){if(!i(s))throw s;return await this.waitForConflictRetry(e,t,o,a,s),this.retryOnConflict(e,t,n,i,o,a+1)}}transactionConflictError(e,t,n,i){if(typeof t==="string")return Error(`Failed job queue write "${t}" within ${this.writeRetryBudgetMs}ms after ${n} attempts`,{cause:i});let o=t.strategy??"none",a=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: ${a})`,{cause:i})}write(e,t){return this.retryOnConflict("write",e,t,(n)=>{let i=new Set;for(let o=n;o!==void 0&&!i.has(o);){if(i.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):"",i=ze(t,"");if(/SQLITE_(?:BUSY|LOCKED)/u.test(n)||/SQLITE_(?:BUSY|LOCKED)|database is locked|transaction (?:busy|conflict)/iu.test(i))return!0;t=t instanceof Error?t.cause:void 0}return!1}async startWorkerSession(e,t,n=Date.now(),i=yo,o,a){let s=n+i,l={brainVersion:o??null,brainVersionSortKey:o?pu(o):null,stableSlotId:a??null};await this.write("start worker session",async()=>{await this.db.insert(_t).values({slotId:e,sessionId:t,startedAt:n,heartbeatAt:n,expiresAt:s,...l}).onConflictDoUpdate({target:_t.slotId,set:{sessionId:t,startedAt:n,heartbeatAt:n,expiresAt:s,...l}}),await this.pruneDeadWorkerSessions(n,i)})}async heartbeatWorkerSession(e,t,n=Date.now(),i=yo){return(await this.write("heartbeat worker session",async()=>{let a=await this.db.update(_t).set({heartbeatAt:n,expiresAt:n+i}).where(ge(W(_t.slotId,e),W(_t.sessionId,t))).returning({slotId:_t.slotId});return await this.pruneDeadWorkerSessions(n,i),a})).length===1}async pruneDeadWorkerSessions(e,t){let n=this.db.select({id:ce.id}).from(ce).where(ge(W(ce.workerSlotId,_t.slotId),W(ce.workerSessionId,_t.sessionId),W(ce.status,Ve.PROCESSING),Zn(ce.leaseExpiresAt,e)));await this.db.delete(_t).where(ge(Qn(_t.expiresAt,e-t),Jo(n)))}async endWorkerSession(e,t){return(await this.write("end worker session",async()=>this.db.delete(_t).where(ge(W(_t.slotId,e),W(_t.sessionId,t))).returning({slotId:_t.slotId}))).length===1}async complete(e,t,n){let i=Date.now(),a=(await this.write("complete",async()=>this.db.update(ce).set({status:Ve.COMPLETED,result:t,lastError:null,completedAt:i,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i)}).where(this.attemptWriteGuard(e,n)).returning({id:ce.id}))).length===1;if(a)this.logger.debug("Job completed",{jobId:e,hasResult:t!==void 0});return a}async update(e,t,n){let o=(await this.write("update",async()=>this.db.update(ce).set({data:JSON.stringify(t)}).where(this.attemptWriteGuard(e,n)).returning({id:ce.id}))).length===1;if(o)this.logger.debug("Job data updated",{jobId:e});return o}async recordAttemptProgress(e,t,n,i=Date.now()){return(await this.write("record progress",async()=>this.db.update(ce).set({attemptHeartbeatAt:i,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i),progress:n}).where(this.attemptWriteGuard(e,t)).returning({id:ce.id}))).length===1}async renewAttemptLease(e,t,n,i){return(await this.write("renew attempt lease",async()=>this.db.update(ce).set({attemptHeartbeatAt:n,leaseExpiresAt:n+i}).where(this.attemptWriteGuard(e,t)).returning({id:ce.id}))).length===1}async fail(e,t,n,i=Date.now()){let a=(await this.db.select({retryCount:ce.retryCount,maxRetries:ce.maxRetries,type:ce.type,scheduledFor:ce.scheduledFor,startedAt:ce.startedAt,runtimeUpdatedAt:ce.runtimeUpdatedAt}).from(ce).where(this.attemptWriteGuard(e,n)).limit(1))[0];if(!a)return!1;let s=a.retryCount<a.maxRetries,l=s?a.retryCount+1:a.retryCount,c=Math.min(1000*2**a.retryCount,60000),u=s?i+c:a.scheduledFor;if((await this.write("fail",async()=>this.db.update(ce).set({status:s?Ve.PENDING:Ve.FAILED,retryCount:l,lastError:t.message,scheduledFor:u,completedAt:s?null:i,runtimeUpdatedAt:s?a.runtimeUpdatedAt:this.nextRuntimeUpdatedAt(i),startedAt:s?null:a.startedAt,attemptId:null,workerSlotId:null,workerSessionId:null,leaseExpiresAt:null,attemptHeartbeatAt:null}).where(ge(this.attemptWriteGuard(e,n),W(ce.retryCount,a.retryCount))).returning({id:ce.id}))).length!==1)return!1;if(s)this.logger.debug("Job scheduled for retry",{jobId:e,retryCount:l,backoffMs:c,scheduledFor:new Date(u).toISOString()});else this.logger.error("Job failed after max retries",{jobId:e,type:a.type,retryCount:a.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 i=(await this.write("retire unowned job",async()=>this.db.update(ce).set({status:Ve.FAILED,lastError:t,completedAt:e.now,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(e.now)}).where(ge(W(ce.id,e.jobId),W(ce.type,e.expectedType),Rn(W(ce.status,Ve.PENDING),W(ce.status,Ve.PROCESSING)),Ln(ce.attemptId),Ln(ce.workerSlotId),Ln(ce.workerSessionId),Ln(ce.leaseExpiresAt),Ln(ce.attemptHeartbeatAt),Ln(ce.progress),Ln(ce.result))).returning()))[0]??null;if(i)this.logger.warn("Retired unowned legacy job",{jobId:i.id,type:i.type,reason:t});return i}async getStatus(e){return(await this.db.select().from(ce).where(W(ce.id,e)).limit(1))[0]??null}async getJobsByRootJobId(e){return this.db.select().from(ce).where(E`json_extract(${ce.metadata}, '$.rootJobId') = ${e}`).orderBy(yt(ce.createdAt),yt(ce.id))}async getStatusByEntityId(e){return(await this.db.select().from(ce).where(E`json_extract(${ce.data}, '$.id') = ${e}`).orderBy(en(ce.createdAt)).limit(1))[0]??null}async getStats(){let e=await this.db.select({status:ce.status,count:E`count(*)`}).from(ce).groupBy(ce.status),t={pending:0,processing:0,failed:0,completed:0,total:0};for(let n of e){let i=Number(n.count);t[n.status]=i,t.total+=i}return t}async getDiagnostics(e=Date.now()){let[t,n,i]=await Promise.all([this.db.select({type:ce.type,status:ce.status,count:E`count(*)`}).from(ce).groupBy(ce.type,ce.status),this.db.select({oldestPendingAt:E`min(case when ${ce.status} = ${Ve.PENDING} then ${ce.createdAt} end)`,duePending:E`coalesce(sum(case when ${ce.status} = ${Ve.PENDING} and ${ce.scheduledFor} <= ${e} then 1 else 0 end), 0)`,oldestDuePendingAt:E`min(case when ${ce.status} = ${Ve.PENDING} and ${ce.scheduledFor} <= ${e} then ${ce.scheduledFor} end)`,latestClaimAt:E`max(${ce.startedAt})`,oldestProcessingAt:E`min(case when ${ce.status} = ${Ve.PROCESSING} then ${ce.startedAt} end)`,staleLeaseCount:E`coalesce(sum(case when ${ce.status} = ${Ve.PROCESSING} and ${ce.leaseExpiresAt} is not null and ${ce.leaseExpiresAt} <= ${e} then 1 else 0 end), 0)`}).from(ce),this.db.select({total:E`count(*)`,active:E`coalesce(sum(case when ${_t.expiresAt} > ${e} then 1 else 0 end), 0)`,stale:E`coalesce(sum(case when ${_t.expiresAt} <= ${e} then 1 else 0 end), 0)`,latestHeartbeatAt:E`max(${_t.heartbeatAt})`}).from(_t)]),o={pending:0,processing:0,completed:0,failed:0},a=t.map((u)=>{let d=Number(u.count);return o[u.status]+=d,{type:u.type,status:u.status,count:d}}),s=n[0],l=i[0],c=(u)=>u===null||u===void 0?null:Math.max(0,e-Number(u));return{totals:o,byType:a,oldestPendingAgeMs:c(s?.oldestPendingAt),duePending:Number(s?.duePending??0),oldestDuePendingAgeMs:c(s?.oldestDuePendingAt),latestClaimAgeMs:c(s?.latestClaimAt),oldestProcessingAgeMs:c(s?.oldestProcessingAt),staleLeaseCount:Number(s?.staleLeaseCount??0),workerSessions:{total:Number(l?.total??0),active:Number(l?.active??0),stale:Number(l?.stale??0),latestHeartbeatAgeMs:c(l?.latestHeartbeatAt)}}}async getRuntimeUpdates(e,t){let n=YK.parse(t);if(n===0)return[];return(await this.db.select().from(ce).where(E`(${ce.runtimeUpdatedAt}, ${ce.id}) > (${e.updatedAt}, ${e.jobId})`).orderBy(yt(ce.runtimeUpdatedAt),yt(ce.id)).limit(n)).map((o)=>({job:o,cursor:{updatedAt:o.runtimeUpdatedAt??0,jobId:o.id}}))}async cleanup(e){let t=Date.now()-e;return(await this.write("cleanup",async()=>this.db.delete(ce).where(ge(Rn(W(ce.status,Ve.COMPLETED),W(ce.status,Ve.FAILED)),Qn(ce.completedAt,t))))).rowsAffected}async getActiveJobs(e){let t=Rn(W(ce.status,Ve.PENDING),W(ce.status,Ve.PROCESSING)),n=e&&e.length>0?ge(t,Rt(ce.type,e)):t;return this.db.select().from(ce).where(n).orderBy(en(ce.createdAt))}async getRecentJobs(e,t=20){let n=e&&e.length>0?Rt(ce.type,e):void 0;return this.db.select().from(ce).where(n).orderBy(en(ce.createdAt)).limit(t)}async getFailedJobs(e){let t=W(ce.status,Ve.FAILED),n=e&&e.length>0?ge(t,Rt(ce.type,e)):t;return this.db.select().from(ce).where(n).orderBy(en(ce.createdAt))}async claimNextReady(e){let{now:t,attemptId:n,workerSlotId:i,workerSessionId:o,leaseDurationMs:a,executableTypes:s,exclusiveTypes:l=[],brainVersion:c}=e,u=c?this.brainVersionGate(c,t):{admissible:void 0,noNewerWorker:void 0},d=this.db.select({slotId:_t.slotId}).from(_t).where(ge(W(_t.slotId,i),W(_t.sessionId,o),Zn(_t.expiresAt,t))),p=this.noNewerLiveInstance(i,o,t),m=this.db.select({slotId:_t.slotId}).from(_t).where(ge(W(_t.slotId,ce.workerSlotId),W(_t.sessionId,ce.workerSessionId))),g=ge(W(ce.status,Ve.PROCESSING),Rn(Ln(ce.attemptId),Jo(m),Qn(ce.leaseExpiresAt,t))),f=cp(ce,"running"),h=this.db.select({id:f.id}).from(f).where(ge(W(f.type,ce.type),W(f.status,Ve.PROCESSING),Zn(f.leaseExpiresAt,t),E`${f.id} <> ${ce.id}`)),y=l.length===0?void 0:Rn(sp(ce.type,[...l]),Jo(h)),w=E`${ce.status} = ${Ve.PROCESSING} AND ${ce.retryCount} + 1 > ${ce.maxRetries}`,I=this.db.select({id:ce.id}).from(ce).where(ge(Rt(ce.type,s),y,u.admissible,Rn(ge(W(ce.status,Ve.PENDING),Qn(ce.scheduledFor,t)),g))).orderBy(yt(ce.priority),yt(ce.createdAt)).limit(1),v=(await this.write("claim",async()=>this.db.update(ce).set({status:E`CASE WHEN ${w} THEN ${Ve.FAILED} ELSE ${Ve.PROCESSING} END`,retryCount:E`CASE WHEN ${ce.status} = ${Ve.PROCESSING} THEN ${ce.retryCount} + 1 ELSE ${ce.retryCount} END`,lastError:E`CASE WHEN ${ce.status} = ${Ve.PROCESSING} THEN 'Attempt lease expired' ELSE ${ce.lastError} END`,startedAt:E`CASE WHEN ${w} THEN ${ce.startedAt} ELSE ${t} END`,completedAt:E`CASE WHEN ${w} THEN ${t} ELSE NULL END`,attemptId:E`CASE WHEN ${w} THEN ${ce.attemptId} ELSE ${n} END`,workerSlotId:E`CASE WHEN ${w} THEN ${ce.workerSlotId} ELSE ${i} END`,workerSessionId:E`CASE WHEN ${w} THEN ${ce.workerSessionId} ELSE ${o} END`,leaseExpiresAt:E`CASE WHEN ${w} THEN ${ce.leaseExpiresAt} ELSE ${t+a} END`,attemptHeartbeatAt:E`CASE WHEN ${w} THEN ${ce.attemptHeartbeatAt} ELSE ${t} END`,runtimeUpdatedAt:E`CASE WHEN ${w} THEN ${this.nextRuntimeUpdatedAt(t)} ELSE ${ce.runtimeUpdatedAt} END`}).where(ge(Rt(ce.id,I),Na(d),p,u.noNewerWorker)).returning()))[0];if(!v)return null;if(v.status===Ve.FAILED)return v;return this.logger.debug("Job claimed",{jobId:v.id,attemptId:v.attemptId,workerSlotId:i,workerSessionId:o}),v}noNewerLiveInstance(e,t,n){let i=cp(_t,"claimer"),o=cp(_t,"peer"),a=this.db.select({slotId:o.slotId}).from(o).innerJoin(i,ge(W(i.slotId,e),W(i.sessionId,t))).where(ge(W(o.stableSlotId,i.stableSlotId),Zn(o.expiresAt,n),Rn(Zn(o.startedAt,i.startedAt),ge(W(o.startedAt,i.startedAt),Zn(o.slotId,i.slotId)))));return Jo(a)}brainVersionGate(e,t){let n=pu(e),i=this.db.select({slotId:_t.slotId}).from(_t).where(ge(Zn(_t.expiresAt,t),Zn(_t.brainVersionSortKey,n)));return{admissible:Rn(Ln(ce.brainVersionSortKey),Qn(ce.brainVersionSortKey,n)),noNewerWorker:Jo(i)}}nextRuntimeUpdatedAt(e){return E`max(${e}, coalesce((select max(${ce.runtimeUpdatedAt}) from ${ce}), 0) + 1)`}attemptWriteGuard(e,t){return t?ge(W(ce.id,e),W(ce.status,Ve.PROCESSING),W(ce.attemptId,t)):ge(W(ce.id,e),Ln(ce.attemptId),Rn(W(ce.status,Ve.PENDING),W(ce.status,Ve.PROCESSING)))}}class Nv{client;logger;handlerRegistry;repository;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;inFlightEnqueues=0;databaseUrl;operationContext;projectionAdmission;directWorkerSlotId=`direct:${Bt()}`;directWorkerSessionId=Bt();directLeaseDurationMs;directSessionStart=null;brainVersion;close(){this.closeRequested=!0,this.closeClientWhenReady()}static createFresh(e,t,n){return new Nv(e,t??ei.getInstance(),n)}constructor(e,t,n){this.brainVersion=e.brainVersion===void 0?void 0:aP.parse(e.brainVersion);let{db:i,client:o,url:a}=iP(e);this.client=o,this.databaseUrl=a,this.logger=t.child("JobQueueService"),this.operationContext=n?.operationContext??la.createFresh(),this.projectionAdmission=n?.projectionAdmission,this.handlerRegistry=new jv(this.logger,n?.handlerRegistrationMode??"combined"),this.repository=new zv(i,o,a,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 xi(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:i}=e,o=this.handlerRegistry.getValidator(t);if(!o)throw Error(`No job type declared: ${t}`);let a=o.validateAndParse(n);if(a===null)throw Error(`Invalid job data for type: ${t}`);let s=Date.now(),l=Bt(),c=i?.rootJobId??(i?.detached?l:this.operationContext.current()?.provenance.rootJobId)??l,u=this.createJobProvenance(l,c,i),d=i?.metadata??{operationType:"data_processing"},{provenance:p,...m}=d,g={id:l,type:t,data:JSON.stringify(a),status:Ve.PENDING,priority:i?.priority??0,maxRetries:i?.maxRetries??3,retryCount:0,source:i?.source??null,metadata:{...m,...i?.deduplicationKey&&{deduplicationKey:i.deduplicationKey},rootJobId:c,provenance:u},createdAt:s,scheduledFor:i?.delayMs?s+i.delayMs:s,result:null,lastError:null,startedAt:null,completedAt:null,brainVersion:this.brainVersion},f,h=()=>{f?.rollback(),f=void 0};try{let y=await this.repository.enqueueAtomic({jobData:g,strategy:i?.deduplication,deduplicationKey:i?.deduplicationKey,beforeInsert:async()=>{f=await this.projectionAdmission?.reserveJobAdmission(u)},onInsertRollback:h});if(f?.commit(),f=void 0,y.kind==="skipped")this.logger.debug("Skipping duplicate job (already pending)",{type:t,existingJobId:y.jobId});else if(y.kind==="coalesced")this.logger.debug("Coalescing with existing job",{type:t,existingJobId:y.jobId});else{if(y.kind==="replaced")this.logger.debug("Replacing duplicate job",{type:t,oldJobId:y.replacedJobId});this.logger.debug("Job enqueued",{id:y.jobId,type:t,priority:g.priority,rootJobId:g.metadata.rootJobId})}return y.jobId}catch(y){throw h(),this.logger.error("Failed to enqueue job",{type:t,error:ze(y)}),y}}createJobProvenance(e,t,n){let i=this.operationContext.current(),o=n?.metadata.provenance??i?.provenance,a=o?.rootJobId===t?o:void 0,s=i?.provenance.rootJobId===t?i.operationId:void 0,l=n?.projection,c=l?[...a?.projectionLineage??[],l.id]:[...a?.projectionLineage??[]],u=l?.id??a?.projectionId;return Gi.parse({rootJobId:t,causationId:s??a?.causationId??e,...u?{projectionId:u}:{},projectionLineage:c,...l?.sourceEntity?{sourceEntity:l.sourceEntity}:a?.sourceEntity?{sourceEntity:a.sourceEntity}:{},derivationDepth:c.length})}async dequeue(e){let t=this.handlerRegistry.getRegisteredTypes();if(t.length===0)return null;let{onTerminalReclaim:n,...i}=e??await this.getDirectClaimOptions(),o=Date.now(),a=await this.repository.claimNextReady({...i,workerSlotId:this.sessionSlotId(i.workerSlotId,i.workerSessionId),brainVersion:this.brainVersion,now:o,attemptId:Bt(),executableTypes:t,exclusiveTypes:this.handlerRegistry.getExclusiveTypes()});if(!a)return null;if(a.status===Ve.FAILED)return this.logger.warn("Expired attempt failed terminally on reclaim",{id:a.id,type:a.type,retryCount:a.retryCount}),await n?.(a),null;return this.logger.debug("Job dequeued",{id:a.id,type:a.type,priority:a.priority,retryCount:a.retryCount,attemptId:a.attemptId,workerSlotId:a.workerSlotId,workerSessionId:a.workerSessionId}),a}async startWorkerSession(e,t,n=yo){await this.repository.startWorkerSession(this.sessionSlotId(e,t),t,Date.now(),n,this.brainVersion,this.versionedSlotId(e))}heartbeatWorkerSession(e,t,n=yo){return this.repository.heartbeatWorkerSession(this.sessionSlotId(e,t),t,Date.now(),n)}endWorkerSession(e,t){return this.repository.endWorkerSession(this.sessionSlotId(e,t),t)}versionedSlotId(e){return this.brainVersion?`${e}@${this.brainVersion}`:e}sessionSlotId(e,t){return`${this.versionedSlotId(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.sessionSlotId(this.directWorkerSlotId,this.directWorkerSessionId),this.directWorkerSessionId,Date.now(),this.directLeaseDurationMs,this.brainVersion),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,i=Date.now()+(e.timeoutMs??30000),o=async(a)=>{e.signal?.throwIfAborted();let{totals:s}=await this.getDiagnostics(),c=s.pending===0&&s.processing===0?a??Date.now():null;if(c!==null&&Date.now()-c>=t)return;if(Date.now()>=i)throw Error(`Timed out waiting for the job queue to settle: ${s.pending} pending, ${s.processing} processing`);return await Bun.sleep(n),o(c)};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)}}function Bv(e){let t,n=()=>{return},i=!1,o=new Promise((s)=>{n=()=>{i=!0,s({kind:"timeout"})}}),a=()=>{if(i)return;if(t)clearTimeout(t);t=setTimeout(n,Math.max(1,e))};return a(),{expired:o,renew:a,cancel:()=>{if(i=!0,t)clearTimeout(t)}}}function lP(e,t){let n,i=(a)=>{let s=JSON.stringify([a.progress,a.total,a.message]);if(s===n)return;n=s,t()},o=(a)=>({createSub:(s)=>o(a.createSub(s)),report:async(s)=>{i(s),await a.report(s)},startHeartbeat:(s,l)=>a.startHeartbeat(s,l),stopHeartbeat:()=>a.stopHeartbeat(),toCallback:()=>{let s=a.toCallback();return async(l)=>{i(l),await s(l)}}});return o(e)}class cP extends Error{constructor(e,t){super(`Job ${e} exceeded its ${t}ms execution deadline`);this.name="JobDeadlineExceededError"}}class qv{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,i,o){return new qv(e,t,n,i,o)}constructor(e,t,n,i,o){if(this.logger=n.child("JobQueueWorker"),this.jobQueueService=e,this.progressMonitor=t,this.clock=o?.clock,this.operationContext=o?.operationContext??la.createFresh(),this.projectionBatchScope=o?.projectionBatchScope,this.config={concurrency:i?.concurrency??1,pollInterval:i?.pollInterval??1000,maxJobs:i?.maxJobs??0,autoStart:i?.autoStart??!1,workerSlotId:i?.workerSlotId??process.env.BRAIN_JOB_WORKER_SLOT_ID??"default",defaultExecutionTimeoutMs:i?.defaultExecutionTimeoutMs??300000,cancellationGraceMs:i?.cancellationGraceMs??5000,errorCallbackTimeoutMs:i?.errorCallbackTimeoutMs??1e4,leaseDurationMs:i?.leaseDurationMs??30000,attemptHeartbeatIntervalMs:i?.attemptHeartbeatIntervalMs??1e4,workerHeartbeatIntervalMs:i?.workerHeartbeatIntervalMs??5000,workerSessionTimeoutMs:i?.workerSessionTimeoutMs??yo,onUnhealthy:i?.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((a)=>{this.logger.error("Failed to auto-start JobQueueWorker",{error:a})})}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=Bt();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=we.runSync(Gt.make()),this.jobFibers=we.runSync(Gt.provide(ar.make(),this.workerScope)),this.pollFiber=we.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 we.runPromise(da.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 we.runPromise(ar.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,i=this.config.maxJobs-n-this.activeJobs.size;if(i<=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,i)}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 i=this.workerSessionId;if(!i)throw Error("Worker session is not available");let o=await this.jobQueueService.dequeue({workerSlotId:this.config.workerSlotId,workerSessionId:i,leaseDurationMs:this.config.leaseDurationMs,onTerminalReclaim:(a)=>this.emitTerminalReclaim(a)});if(!o)break;this.activeJobs.add(o.id),await we.runPromise(ar.run(t,o.id,we.promise(()=>this.processJobWrapper(o))))}}catch(e){this.logger.error("Error processing available jobs",{error:e}),this.stats.lastError=ze(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=ze(n)}finally{this.activeJobs.delete(t)}}runPollingLoop(){let t=we.suspend(()=>{if(!this.isWorkerRunning()||this.isStopRequested())return we.interrupt;return this.currentPoll=this.processAvailableJobs(),we.promise(()=>this.currentPoll??Promise.resolve()).pipe(we.andThen(we.suspend(()=>(this.currentPoll=null,!this.isWorkerRunning()||this.isStopRequested()?we.interrupt:we.void))))}).pipe(we.schedule(Ga.spaced(this.config.pollInterval)),we.asVoid);return ri(t,this.clock).pipe(we.ensuring(we.sync(()=>{this.pollFiber=null})))}requestTransition(e,t){let n=this.transitionQueue.at(-1)??this.activeTransition;if(n?.kind===e)return n.promise;let i=()=>{return},o=()=>{return},a=new Promise((l,c)=>{i=l,o=c}),s={kind:e,awaitInFlightPoll:t,promise:a,resolve:i,reject:o};return this.transitionQueue.push(s),this.runNextTransition(),a}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 we.runPromise(Gt.close(e,Qt.void))}startHeartbeatLoop(e){let t=null,n=!1,i=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(i),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: ${ze(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 i=Error("Job attempt was superseded");t.abort(i),this.markUnhealthy(i.message)},onError:(i)=>{let o=yl(i);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:ze(t)})}}async raceOutcome(e,t){let n,i=new Promise((o)=>{n=setTimeout(()=>o({kind:"timeout"}),Math.max(1,t))});try{return await Promise.race([e,i])}finally{if(n)clearTimeout(n)}}async executeWithDeadline(e,t,n,i,o=Bv(t)){let a=Promise.resolve().then(i).then((u)=>({kind:"success",value:u}),(u)=>({kind:"failure",error:u})),s=await Promise.race([a,o.expired]).finally(()=>o.cancel());if(s.kind!=="timeout"){if(s.kind==="failure")throw s.error;return s.value}let l=new cP(e,t);if(n.abort(l),(await this.raceOutcome(a,this.config.cancellationGraceMs)).kind!=="timeout")throw l;throw this.markUnhealthy(`${l.message}; handler ignored cancellation grace`),await a,l}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 l=Error(`Claimed job ${e.id} has no attempt fencing token`);return this.markUnhealthy(l.message),{jobId:e.id,type:e.type,status:Ve.FAILED,error:l.message}}let n=this.jobQueueService.getHandler(e.type);if(!n){let l=Error(`No handler registered for job type: ${e.type}`);return await this.jobQueueService.fail(e.id,l,t),{jobId:e.id,type:e.type,status:Ve.FAILED,error:l.message}}let i=new AbortController,o=this.startAttemptHeartbeat(e,i),a=!1,s=async()=>{if(a)return;a=!0,await o()};try{this.logger.debug("Processing job",{jobId:e.id,type:e.type,attemptId:t});let l=JSON.parse(e.data),c=n.validateAndParse(l);if(c===null)throw Error(`Invalid job data for type: ${e.type}`);let u=this.progressMonitor.createProgressReporter(e.id,t),d=n.executionTimeoutMs??this.config.defaultExecutionTimeoutMs,p=Bv(d),m=await this.executeWithDeadline(e.type,d,i,()=>n.process(c,e.id,lP(u,p.renew),i.signal),p);await s();let g=Mv.safeParse(m);if(g.success){let h=g.data.error??"Handler returned failure",y=Error(h);if(await this.jobQueueService.fail(e.id,y,t))await this.emitTerminalFailure(e,y,n,t);return{jobId:e.id,type:e.type,status:Ve.FAILED,error:h}}if(!await this.jobQueueService.complete(e.id,m,t))return{jobId:e.id,type:e.type,status:Ve.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:Ve.COMPLETED,result:m}}catch(l){let c=yl(l);if(await s(),await this.runHandlerErrorCallback("onError",n,e,c,t),await this.jobQueueService.fail(e.id,c,t))await this.emitTerminalFailure(e,c,n,t);return{jobId:e.id,type:e.type,status:Ve.FAILED,error:c.message}}}async runHandlerSuccessCallback(e,t,n){let i=e.onTerminalSuccess;if(!i)return;try{let o=e.validateAndParse(JSON.parse(t.data));if(o===null)return;let a=this.progressMonitor.createProgressReporter(t.id,n),s=new AbortController;await this.executeWithDeadline(`${t.type}:onTerminalSuccess`,this.config.errorCallbackTimeoutMs,s,()=>i.call(e,o,t.id,a,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,i){if((await this.jobQueueService.getStatus(e.id))?.status!==Ve.FAILED)return;await this.runHandlerErrorCallback("onTerminalError",n,e,t,i),await this.progressMonitor.handleJobStatusChange(e.id,"failed",e.metadata)}async emitTerminalReclaim(e){let t=this.jobQueueService.getHandler(e.type);if(t)await this.runHandlerErrorCallback("onTerminalError",t,e,Error(e.lastError??"Attempt lease expired"),e.attemptId??e.id);await this.progressMonitor.handleJobStatusChange(e.id,"failed",e.metadata)}async runHandlerErrorCallback(e,t,n,i,o){let a=t[e];if(!a)return;try{let s=t.validateAndParse(JSON.parse(n.data));if(s===null)return;let l=this.progressMonitor.createProgressReporter(n.id,o),c=new AbortController;await this.executeWithDeadline(`${n.type}:${e}`,this.config.errorCallbackTimeoutMs,c,()=>a.call(t,i,s,n.id,l,c.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 e4=86400000,uP=3600000;class Lv{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 Lv(e,t,n)}constructor(e,t,n){this.jobQueue=e,this.logger=t,this.clock=n?.clock}start(e=uP){return this.requestTransition("start",e)}stop(){return this.requestTransition("stop",uP)}async startCleanup(e){if(this.acceptingCleanup=!0,this.cleanupFiber)return;this.cleanupFiber=we.runFork(this.runCleanupLoop(e))}runCleanupLoop(e){let t=this.cleanupTerminalBatchMetadata().pipe(we.schedule(Ga.spaced(e)),we.asVoid);return ri(t,this.clock)}scheduleTerminalBatchCleanup(){if(!this.acceptingCleanup)return;this.cleanupSupervisor??=this.createCleanupSupervisor();let e=we.runFork(this.cleanupTerminalBatchMetadata());rs.addUnsafe(this.cleanupSupervisor.fibers,e)}async stopCleanup(){this.acceptingCleanup=!1;let e=this.cleanupFiber;if(this.cleanupFiber=null,e)await we.runPromise(da.interrupt(e));let t=this.cleanupSupervisor;if(t)await we.runPromise(rs.awaitEmpty(t.fibers));while(this.inFlightCleanups.size>0)await Promise.allSettled(this.inFlightCleanups);if(t)await we.runPromise(Gt.close(t.scope,Qt.void)),this.cleanupSupervisor=null}requestTransition(e,t){let n=this.transitionQueue.at(-1)??this.activeTransition;if(n?.kind===e)return n.promise;let i=()=>{return},o=()=>{return},a=new Promise((l,c)=>{i=l,o=c}),s={kind:e,intervalMs:t,promise:a,resolve:i,reject:o};return this.transitionQueue.push(s),this.runNextTransition(),a}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=we.runSync(Gt.make()),t=we.runSync(Gt.provide(rs.make(),e));return{scope:e,fibers:t}}cleanupTerminalBatchMetadata(){return we.tryPromise({try:()=>{let e=this.cleanup(e4);return this.inFlightCleanups.add(e),e.then(()=>this.inFlightCleanups.delete(e),()=>this.inFlightCleanups.delete(e)),e},catch:(e)=>e}).pipe(we.asVoid,we.catch((e)=>we.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,i){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 a of e){let s={...t,rootJobId:n,metadata:{...t.metadata,operationTarget:a.type}},l=await this.jobQueue.enqueue({type:a.type,data:a.data,options:s});o.push(l)}return this.logger.debug("Enqueued batch operations",{batchId:n,operationCount:e.length,jobIds:o,rootJobId:n}),this.scheduleTerminalBatchCleanup(),n}catch(a){throw this.batches.delete(n),this.logger.error("Failed to enqueue batch operations",{error:a,operationCount:e.length,enqueuedJobs:o.length}),a}}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))),i=0,o=0,a=0,s=[];for(let[u,d]of n.entries()){if(!d){o++;let p=t.operations[u],m=t.jobIds[u]??"unknown";s.push(`Missing job ${m}${p?` for ${p.type}`:""}`);continue}switch(d.status){case"completed":i++;break;case"failed":if(o++,d.lastError)s.push(d.lastError);break;case"processing":case"pending":a++;break}}a+=t.operations.length-t.jobIds.length;let l;if(a>0)l=Ve.PROCESSING;else if(o>0)l=Ve.FAILED;else l=Ve.COMPLETED;if(t.terminalAt===void 0&&(l===Ve.COMPLETED||l===Ve.FAILED))t.terminalAt=Date.now();let c;for(let u=0;u<t.jobIds.length;u++){let d=n[u];if(d&&d.status!=="completed"&&d.status!=="failed"){let p=t.operations[u];if(p)c=`Processing ${p.type}`;break}}return{batchId:e,totalOperations:t.operations.length,completedOperations:i,failedOperations:o,errors:s,status:l,currentOperation:c,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[i,o]of this.batches.entries()){if(o.terminalAt!==void 0){if(o.terminalAt<=t)this.batches.delete(i),n++;continue}if(new Date(o.startedAt).getTime()<=t){let s=await this.getBatchStatus(i);if(s&&(s.status===Ve.COMPLETED||s.status===Ve.FAILED))this.batches.delete(i),n++}}return this.logger.debug("Cleaned up batch metadata",{cleaned:n}),n}registerBatch(e,t,n,i,o){this.batches.set(e,{jobIds:t,operations:n,source:i,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 i=await this.getBatchStatus(t);if(i&&(i.status==="pending"||i.status==="processing"))e.push({batchId:t,status:i,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}}}class is{callback;heartbeatInterval;constructor(e){this.callback=e}static from(e){if(!e)return;return new is(e)}static noop(){return new is(async()=>{})}createSub(e){let{scale:t}=e??{};if(t){let{start:n,end:i}=t,o=i-n;return new is(async(a)=>{let s=n+a.progress/(a.total??100)*o;await this.callback({...a,progress:s,total:100})})}return new is(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 t4=r.preprocess((e)=>{if(typeof e!=="string")return e;return JSON.parse(e)},r.record(r.string(),r.unknown()));class Fv{jobQueueService;messageBus;batchJobManager;logger;mode;pollTimer;pollCursor={updatedAt:0,jobId:""};activePoll;stopPromise;stopped=!1;static createFresh(e,t,n,i,o="combined"){return new Fv(e,t,n,i,o)}constructor(e,t,n,i,o){this.jobQueueService=e,this.messageBus=t,this.batchJobManager=n,this.logger=i,this.mode=o}start(){if(this.stopped)throw Error("Cannot start a stopped job progress monitor");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(){return this.stopPromise??=this.stopMonitor(),this.stopPromise}async stopMonitor(){if(this.stopped=!0,this.pollTimer)clearInterval(this.pollTimer);this.pollTimer=void 0,await this.activePoll,this.logger.debug("Job progress monitor stopped")}pollDurableUpdates(){if(this.stopped)return Promise.resolve();if(this.activePoll)return this.activePoll;let e=Promise.resolve().then(()=>this.pollPage());this.activePoll=e;let t=()=>{this.activePoll=void 0};return e.then(t,t),e}async pollPage(){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})}}createProgressReporter(e,t){let n=is.from(async(i)=>{await this.emitJobProgress(e,i,t)});if(!n)throw Error("Failed to create ProgressReporter");return n}async emitBatchProgress(e,t,n){try{let i={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:i};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:mu.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(i){this.logger.error("Error emitting batch progress update",{batchId:e,error:i})}}isBatchChild(e,t){return!!t&&t!==e}get publishesEvents(){return this.mode!=="durable-writer"}async broadcastEvent(e){await this.messageBus.send({type:mu.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 i=await this.jobQueueService.getStatus(e);if(!i){this.logger.warn("Job not found for progress update",{jobId:e});return}await this.publishJobProgress(i,t)}catch(i){this.logger.error("Error emitting job progress",{jobId:e,error:i})}}async publishJobProgress(e,t){if(e.metadata.silent)return;if(this.isBatchChild(e.id,e.metadata.rootJobId))return;let n=t.total??0,i={id:e.id,type:"job",status:"processing",metadata:e.metadata,message:t.message};if(n>0)i.progress={current:t.progress,total:n,percentage:Math.round(t.progress/n*100)};await this.broadcastEvent(i)}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 i={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(i),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=t4.parse(e.result),i=n.message;if(i)return String(i);let o=n.routesBuilt;if(o!==void 0)return`${o} routes built`}catch{}return}getStats(){return{isRunning:!this.stopped&&(this.mode!=="durable-reader"||this.pollTimer!==void 0)}}async handleJobStatusChange(e,t,n){if(!this.publishesEvents)return;let i=n?ns.safeParse(n):void 0,o=i?.success?i.data:void 0;if(o?.silent)return;try{if(await this.emitJobStatusEvent(e,t),o&&this.isBatchChild(e,o.rootJobId))try{let a=o.rootJobId,s=await this.batchJobManager.getBatchStatus(a);if(s){let l=s.metadata??o;await this.emitBatchProgress(a,s,l)}}catch(a){this.logger.warn("Failed to emit batch progress",{jobId:e,rootJobId:o.rootJobId,error:a})}}catch(a){this.logger.error("Failed to handle job status change",{jobId:e,status:t,error:a})}}}var n4=r.record(r.string(),r.unknown());class gu{logger;schema;jobTypeName;executionTimeoutMs;exclusive;constructor(e,t){this.logger=e,this.schema=t.schema,this.jobTypeName=t.jobTypeName,this.executionTimeoutMs=t.executionTimeoutMs,this.exclusive=t.exclusive}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,i,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=n4.safeParse(e);return t.success?t.data:{}}}function fu(e,t,n){let i=async(a)=>{let{type:s,data:l,toolContext:c=null,options:u,projection:d}=a,p=c?dP(c):void 0,{metadata:m,...g}=u??{},f={operationType:"data_processing",pluginId:t,...m,...c&&{interfaceType:c.interfaceType,conversationId:c.conversationId,channelId:c.channelId,requestedByActor:c.actor,...p?{requestedByUserId:p}:{},requestedByInterface:c.interfaceType,...c.progressToken!==void 0&&{progressToken:c.progressToken}}};if(c&&!p)delete f.requestedByUserId;let h={...g,source:t,...u?.rootJobId&&{rootJobId:u.rootJobId},...d&&{projection:d},metadata:f},y=n&&!s.includes(":")?`${t}:${s}`:s;return e.enqueue({type:y,data:l,options:h})};async function o(a,s,l){if(!("input"in a))return i(a);let c=a.input.safeParse(s);if(!c.success)throw Error(`Invalid job data for ${a.type}: ${c.error.message}`);return i({...l,type:a.type,data:c.data})}return o}function $v(e){return(t)=>e.getValidator(t.type)!==void 0}function Uv(e,t){return async(n,i)=>{let o=i?.rootJobId??Bt(),a=n.map((l)=>({...l,type:l.type.includes(":")?l.type:`${t}:${l.type}`})),s={...i,source:t,rootJobId:o,metadata:{...i?.metadata,operationType:"batch_processing",pluginId:t}};return await e.enqueueBatch(a,s,o,t),o}}function Zv(e,t){return(n,i)=>{let o=n.includes(":")?n:`${t}:${n}`;e.registerHandler(o,i,t)}}var r4=r.custom((e)=>typeof e==="object"&&e!==null&&("safeParse"in e)),i4=r.object({name:r.string(),schema:r4});function pP(e){return i4.safeParse(e).success}function o4(e){if(!e)return;return{status:e.status,message:e.message,lastCheck:e.lastCheck?.toISOString(),details:e.details}}function mP(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:o4(t.health)})),endpoints:e.endpoints,interactions:e.interactions}}var a4="/api/chat",kt="web-chat-guest",Bm=r.strictObject({idleSeconds:r.number().int().positive().max(Math.floor(Number.MAX_SAFE_INTEGER/1000)),maxAgeSeconds:r.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"),qm=r.strictObject({visitorId:r.string().uuid(),retention:Bm}),ot=r.string().trim().min(1).max(256),IFe="x-brain-conversation-id",EFe=r.strictObject({expiresAt:r.number().int().positive(),provider:r.string().min(1),notice:r.string().min(1),deletionLimitations:r.string().min(1),retention:Bm,messageCharacters:r.number().int().positive(),canSend:r.boolean(),presentation:hP.optional()}),s4=r.strictObject({conversationId:ot,state:r.enum(["active","completed","failed","interrupted","uncertain"])}),vP=r.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),Jv=r.string().trim().min(1).max(48),Vv=r.string().datetime(),gP=r.string().regex(/^\/(?!\/)/).max(2048),bl=r.string().regex(/^(?:\/(?!\/)|https?:\/\/)/).max(2048),l4=r.looseObject({kind:r.literal("tool-approval"),id:ot,toolCallId:ot.optional(),toolName:r.string().trim().min(1).max(256),input:r.record(r.string(),r.unknown()).optional(),summary:r.string().max(4096),completionSummary:r.string().max(4096).optional(),preview:r.string().max(1e5).optional(),state:r.enum(["approval-requested","approval-responded","output-available","output-denied","output-error"]),output:r.unknown().optional(),error:r.string().max(4096).optional()}),c4=r.looseObject({entityType:r.string().trim().min(1).max(128).optional(),entityId:ot.optional(),attachmentType:r.string().trim().min(1).max(128).optional()}),u4=r.looseObject({mediaType:r.string().trim().min(1).max(255),url:bl,downloadUrl:bl.optional(),previewUrl:bl.optional(),filename:r.string().trim().min(1).max(255).optional(),sizeBytes:r.number().int().nonnegative().optional(),source:c4.optional()}),SP=r.looseObject({kind:r.literal("attachment"),id:ot,jobId:ot.optional(),title:r.string().max(4096),description:r.string().max(20000).optional(),attachment:u4}),d4=r.looseObject({id:ot,title:r.string().max(4096).optional(),source:r.string().trim().min(1).max(512),url:bl.optional(),entityType:r.string().trim().min(1).max(128).optional(),entityId:ot.optional(),excerpt:r.string().max(20000).optional(),provenance:r.record(r.string(),r.unknown()).optional(),brain:yP.optional()}),Hv=r.looseObject({kind:r.literal("sources"),id:ot,title:r.string().max(4096).optional(),sources:r.array(d4).min(1).max(100)}),p4=r.discriminatedUnion("type",[r.object({type:r.literal("prompt"),id:ot,label:r.string().trim().min(1).max(256),prompt:r.string().min(1).max(1e5),description:r.string().max(4096).optional()}),r.object({type:r.literal("event"),id:ot,label:r.string().trim().min(1).max(256),event:r.string().trim().min(1).max(256),fromState:r.string().trim().min(1).max(256).optional(),description:r.string().max(4096).optional()})]),xP=r.looseObject({kind:r.literal("actions"),id:ot,title:r.string().max(4096).optional(),actions:r.array(p4).min(1).max(100)}),wP=r.discriminatedUnion("kind",[l4,SP,Hv,xP]);function fP(e){if(!e||e.length>512)return;let t;try{t=new URL(e)}catch{return}return t.protocol==="https:"&&!t.username&&!t.password&&t.href.length<=512?t.href:void 0}function TP(e){if(!Array.isArray(e))return[];let t=[],n=new Set;for(let i of e.slice(0,10)){let o=Hv.safeParse(i);if(!o.success||o.data.id!=="sources:tool-results")continue;for(let a of o.data.sources){if(t.length>=15)break;if(!a.entityType||!a.entityId||a.entityId.length>256||a.source!==a.entityType||a.id!==`${a.entityType}:${a.entityId}`||n.has(a.id))continue;n.add(a.id);let s=fP(a.url),l=fP(a.brain?.url);t.push({id:a.id,source:a.entityType,entityType:a.entityType,entityId:a.entityId,title:(a.title??a.entityId).slice(0,160),...a.excerpt?{excerpt:a.excerpt.slice(0,280)}:{},...s?{url:s}:{},...a.brain?{brain:{name:a.brain.name.slice(0,120),...l?{url:l}:{}}}:{}})}}return t.length?[{kind:"sources",id:"sources:tool-results",title:"Retrieved sources",sources:t}]:[]}var m4=r.object({id:ot,toolCallId:ot.optional(),toolName:r.string().trim().min(1).max(256),summary:r.string().max(4096),completionSummary:r.string().max(4096).optional(),preview:r.string().max(1e5).optional(),args:r.unknown()}),_P=r.object({toolName:r.string().trim().min(1).max(256),args:r.record(r.string(),r.unknown()).optional(),jobId:ot.optional(),data:r.unknown().optional(),error:r.object({message:r.string().max(4096),code:r.string().trim().min(1).max(256).optional()}).optional()}),kFe=r.looseObject({text:r.string().max(1e6),toolResults:r.array(_P).max(100).optional(),cards:r.array(wP).max(100).optional(),pendingConfirmations:r.array(m4).max(100).optional(),usage:r.object({promptTokens:r.number().int().nonnegative(),completionTokens:r.number().int().nonnegative(),totalTokens:r.number().int().nonnegative()})});function RFe(e=a4){let t=g4(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 g4(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 f4=r.strictObject({version:r.literal(1),sourceId:r.string().trim().regex(/^[a-z][a-z0-9-]*$/).max(64),itemId:r.string().trim().min(1).max(300),titleSeed:r.string().trim().min(1).max(160).refine((e)=>!/[\p{Cc}\p{Cf}]/u.test(e))}),AFe=r.object({query:r.string().trim().max(200).default(""),archived:r.boolean().default(!1),offset:r.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).default(0),limit:r.number().int().min(1).max(100).default(25)}),h4=r.looseObject({id:ot,title:Jv,lastActiveAt:Vv,archived:r.boolean().optional(),contextHandoff:f4.optional()}),PFe=r.looseObject({sessions:r.array(h4).max(100)}),y4=r.looseObject({kind:r.string().trim().min(1).max(64),id:ot}),b4=r.looseObject({kind:r.literal("text"),filename:r.string().trim().min(1).max(255),mediaType:r.string().trim().min(1).max(255),sizeBytes:r.number().int().nonnegative(),createdAt:Vv,source:y4.optional()}),CP=r.looseObject({id:ot,role:r.enum(["user","assistant"]),content:r.string().max(1e6),attachments:r.array(b4).max(100).optional(),cards:r.array(wP).max(100).optional(),askedBefore:Wv.optional()}),OFe=r.looseObject({messages:r.array(CP).max(100)}),MFe=r.string().min(1).max(256).refine((e)=>e.trim().length>0),jFe=r.strictObject({messages:r.array(CP).max(100),submission:s4.nullable()}),DFe=r.object({type:r.literal("text"),text:r.string().max(1e6)}),zFe=r.object({type:r.literal("file"),mediaType:r.string().trim().min(1).max(255).optional(),filename:r.string().trim().min(1).max(255).optional(),url:r.string().min(1).max(2000000)}),IP=r.object({kind:r.literal("upload"),id:vP}),NFe=r.object({type:r.literal("data-upload"),data:r.looseObject({ref:IP})}),v4=r.object({id:ot,approved:r.boolean(),toolCallId:ot.optional(),toolName:r.string().trim().min(1).max(256).optional(),input:r.record(r.string(),r.unknown()).optional(),title:r.string().max(4096).optional()}),BFe=r.looseObject({state:r.literal("approval-responded"),toolCallId:ot.optional(),toolName:r.string().trim().min(1).max(256).optional(),input:r.record(r.string(),r.unknown()).optional(),title:r.string().max(4096).optional(),approval:v4}),S4=r.object({id:ot.optional(),role:r.enum(["user","assistant","system"]),parts:r.array(r.unknown()).max(1000).optional(),content:r.string().max(1e6).optional()}),qFe=r.object({id:ot.optional(),messages:r.array(S4).min(1).max(200),trigger:r.string().trim().min(1).max(64).optional()}).strict(),LFe=r.strictObject({id:ot.optional(),messages:r.array(r.strictObject({id:ot,role:r.literal("user"),parts:r.array(r.strictObject({type:r.literal("text"),text:r.string()})).min(1).max(16)})).length(1)}),EP=r.enum(["pending","processing","completed","failed"]),x4=r.looseObject({type:r.enum(["job","batch"]),status:EP,operationType:r.enum(["file_operations","content_operations","data_processing","batch_processing"]),operationTarget:r.string().max(1024).optional(),message:r.string().max(4096).optional(),progress:r.object({current:r.number().nonnegative(),total:r.number().nonnegative(),percentage:r.number().min(0).max(100)}).optional()}),w4=r.looseObject({status:r.enum(["tool-running","tool-completed","tool-awaiting-approval","tool-failed"]),toolName:r.string().trim().min(1).max(256),error:r.string().max(4096).optional()}),FFe=r.discriminatedUnion("type",[r.looseObject({type:r.literal("start"),messageId:ot.optional()}),r.looseObject({type:r.literal("start-step")}),r.looseObject({type:r.literal("finish-step")}),r.looseObject({type:r.literal("finish"),finishReason:r.enum(["length","error","stop","content-filter","tool-calls","other"]).optional()}),r.looseObject({type:r.literal("abort"),reason:r.string().max(4096).optional()}),r.looseObject({type:r.literal("error"),errorText:r.string().max(20000)}),r.looseObject({type:r.literal("text-start"),id:ot}),r.looseObject({type:r.literal("text-delta"),id:ot,delta:r.string().max(1e6)}),r.looseObject({type:r.literal("text-end"),id:ot}),r.looseObject({type:r.literal("reasoning-start"),id:ot}),r.looseObject({type:r.literal("reasoning-delta"),id:ot,delta:r.string().max(1e6)}),r.looseObject({type:r.literal("reasoning-end"),id:ot}),r.looseObject({type:r.literal("tool-input-start"),toolCallId:ot,toolName:r.string().trim().min(1).max(256),title:r.string().max(4096).optional()}),r.looseObject({type:r.literal("tool-input-delta"),toolCallId:ot,inputTextDelta:r.string().max(1e6)}),r.looseObject({type:r.literal("tool-input-available"),toolCallId:ot,toolName:r.string().trim().min(1).max(256),input:r.unknown(),title:r.string().max(4096).optional()}),r.looseObject({type:r.literal("tool-input-error"),toolCallId:ot,toolName:r.string().trim().min(1).max(256),input:r.unknown(),errorText:r.string().max(20000),title:r.string().max(4096).optional()}),r.looseObject({type:r.literal("tool-approval-request"),approvalId:ot,toolCallId:ot}),r.looseObject({type:r.literal("tool-output-available"),toolCallId:ot,output:r.unknown(),preliminary:r.boolean().optional()}),r.looseObject({type:r.literal("tool-output-error"),toolCallId:ot,errorText:r.string().max(20000)}),r.looseObject({type:r.literal("tool-output-denied"),toolCallId:ot}),r.looseObject({type:r.literal("source-url"),sourceId:ot,url:bl,title:r.string().max(4096).optional()}),r.looseObject({type:r.literal("source-document"),sourceId:ot,mediaType:r.string().trim().min(1).max(255),title:r.string().max(4096),filename:r.string().trim().min(1).max(255).optional()}),r.looseObject({type:r.literal("file"),url:bl,mediaType:r.string().trim().min(1).max(255)}),r.looseObject({type:r.literal("data-progress"),id:ot.optional(),data:x4,transient:r.boolean().optional()}),r.looseObject({type:r.literal("data-status"),id:ot.optional(),data:w4,transient:r.boolean().optional()}),r.looseObject({type:r.literal("data-tool-result"),id:ot.optional(),data:_P,transient:r.boolean().optional()}),r.looseObject({type:r.literal("data-actions"),id:ot.optional(),data:xP,transient:r.boolean().optional()}),r.looseObject({type:r.literal("data-sources"),id:ot.optional(),data:Hv,transient:r.boolean().optional()}),r.looseObject({type:r.literal("data-asked-before"),id:ot.optional(),data:Wv,transient:r.boolean().optional()}),r.looseObject({type:r.literal("data-attachment"),id:ot.optional(),data:SP,transient:r.boolean().optional()})]),$Fe=r.strictObject({conversationId:ot}),UFe=r.object({title:Jv}).strict(),ZFe=r.object({renamed:r.boolean(),title:Jv}),GFe=r.object({archived:r.boolean()}),WFe=r.object({deleted:r.boolean()}),JFe=r.object({conversationId:ot,action:bP}).strict(),VFe=r.looseObject({id:ot,status:EP,message:r.string().max(4096).optional()}),HFe=r.looseObject({id:vP,ref:IP,filename:r.string().trim().min(1).max(255),mediaType:r.string().trim().min(1).max(255),sizeBytes:r.number().int().nonnegative(),createdAt:Vv,url:gP,downloadUrl:gP}).refine((e)=>e.id===e.ref.id,{path:["ref","id"],message:"Upload response ids must match"});var Ne=Lt("conversations",{id:be("id").primaryKey(),sessionId:be("session_id").notNull(),interfaceType:be("interface_type").notNull(),channelId:be("channel_id").notNull(),personId:be("person_id"),started:be("started").notNull(),lastActive:be("last_active").notNull(),metadata:be("metadata"),created:be("created").notNull(),updated:be("updated").notNull()},(e)=>({sessionIdx:Mt("idx_conversations_session").on(e.sessionId),channelIdx:Mt("idx_conversations_channel").on(e.channelId),personIdx:Mt("idx_conversations_person").on(e.personId),interfaceSessionIdx:Mt("idx_conversations_interface_session").on(e.interfaceType,e.sessionId),interfaceChannelIdx:Mt("idx_conversations_interface_channel").on(e.interfaceType,e.channelId)})),jn=Lt("messages",{id:be("id").primaryKey(),conversationId:be("conversation_id").notNull().references(()=>Ne.id,{onDelete:"cascade"}),role:be("role").notNull(),content:be("content").notNull(),timestamp:be("timestamp").notNull(),metadata:be("metadata")},(e)=>({conversationIdx:Mt("idx_messages_conversation").on(e.conversationId),timestampIdx:Mt("idx_messages_timestamp").on(e.timestamp)})),as=Lt("summary_tracking",{conversationId:be("conversation_id").primaryKey().references(()=>Ne.id,{onDelete:"cascade"}),lastSummarizedAt:be("last_summarized_at"),lastMessageId:be("last_message_id"),messagesSinceSummary:tt("messages_since_summary").default(0),updated:be("updated").notNull()});function kP(e){return Si({url:e.url,schema:{conversations:Ne,messages:jn,summaryTracking:as},authToken:e.authToken,authTokenEnv:"CONVERSATION_DATABASE_AUTH_TOKEN"})}var T4=r.preprocess((e)=>{if(typeof e!=="string")return e;try{return JSON.parse(e)}catch{return}},r.record(r.string(),r.unknown())).catch({});function bo(e){return T4.parse(e)}var Lm="conversation:messageAdded",Fm="conversation:guestMessageAdded",Kv="conversation:started",yu=r.object({identity:si,interfaceType:r.string(),role:pl,displayName:r.string().optional(),username:r.string().optional(),isBot:r.boolean().optional()}),_4=r.preprocess(C4,yu);function C4(e){if(!On(e)||"identity"in e)return e;let{actorId:t,interfaceType:n,role:i}=e;if(typeof t!=="string"||typeof n!=="string"||i!=="user"&&i!=="assistant")return e;let{userId:o,canonicalId:a}=e;return{identity:RP({actorId:t,interfaceType:n,role:i,...typeof o==="string"?{userId:o}:{},...typeof a==="string"?{canonicalId:a}:{}}),interfaceType:n,role:i,...typeof e.displayName==="string"?{displayName:e.displayName}:{},...typeof e.username==="string"?{username:e.username}:{},...typeof e.isBot==="boolean"?{isBot:e.isBot}:{}}}var bu=r.object({messageId:r.string().optional(),channelId:r.string().optional(),channelName:r.string().optional(),threadId:r.string().optional(),metadata:r.record(r.string(),r.unknown()).optional()}),AP=r.looseObject({actor:_4.optional(),source:bu.optional(),spaceId:r.string().min(1).optional()});function PP(e){if(typeof e==="string")try{let t=JSON.parse(e);return On(t)?t:null}catch{return null}return On(e)?e:null}function I4(e){if(e.role!=="assistant")return!1;if(e.content.trim().length===0)return!1;let t=PP(e.metadata),n=t?.entityMemoryRefs;if(Array.isArray(n)&&n.length>0)return!1;let i=t?.cards;if(!Array.isArray(i))return!0;return!i.some((o)=>{if(!On(o))return!1;if(o.kind==="tool-approval")return!0;return o.kind==="actions"&&o.id==="actions:upload-intent"})}var c$e=r.object({id:r.string(),conversationId:r.string(),role:r.string(),content:r.string(),timestamp:r.string(),metadata:r.string().nullable()});var Ci=E`strftime('%Y-%m-%dT%H:%M:%fZ', 'now')`;function Qv(){return MP(!1)}function OP(){return MP(!0)}function MP(e){let t=Bm.shape.maxAgeSeconds.maxValue,n=E`(
|
|
128
128
|
CAST(round((julianday(${Ci}) - julianday(${Ne.started})) * 86400000) AS INTEGER) >= json_extract(${Ne.metadata}, '$.guest.retention.maxAgeSeconds') * 1000
|
|
129
129
|
OR CAST(round((julianday(${Ci}) - julianday(${Ne.lastActive})) * 86400000) AS INTEGER) >= json_extract(${Ne.metadata}, '$.guest.retention.idleSeconds') * 1000
|
|
130
130
|
)`;return E`CASE WHEN json_valid(${Ne.metadata}) THEN coalesce(
|
|
@@ -328,9 +328,9 @@ Result:`);if(n===-1)return;let i=e.slice(n+9).trim();if(!i)return;try{return JSO
|
|
|
328
328
|
`)}function Hfe(e,t){let n=[`Sources: ${e.title??"Retrieved context"}`];for(let i of e.sources){let o=t.resolveUrl(i.url),a=o&&!t.isHiddenUrl(o)?` \u2014 ${o}`:"";n.push(`- ${i.title??i.source}${a}`)}return n.join(`
|
|
329
329
|
`)}function Kfe(e,t){let n=[`Actions: ${e.title??"Suggested actions"}`];for(let i of e.actions){let o=i.type==="event"&&t.eventActionUnavailableLabel?` (${t.eventActionUnavailableLabel})`:"";n.push(`- ${i.label}${o}`)}return n.join(`
|
|
330
330
|
`)}function O2(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:Qfe(e.isBot)}:{}}}function Qfe(e){if(typeof e==="boolean")return e;return e.toLowerCase()==="true"}function M2(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 j2(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(Yfe),"","Latest message to answer:",e.message].join(`
|
|
331
|
-
`),metadata:{supersededMessageCount:e.skippedMessages.length,supersededMessageIds:e.skippedMessages.map((i)=>i.id).filter((i)=>i!==void 0)}}}function Yfe(e){let t=e.text.trim(),n=e.authorName?.trim();return n?`- ${n}: ${t}`:`- ${t}`}async function she(e){let{entityType:t,title:n,deriveId:i,regeneratePrompt:o,context:a}=e,s=i(n),l=await a.entityService.getEntity({entityType:t,id:s});if(!l||l.metadata.status==="generating")return n;a.logger.debug(`Entity ID collision: ${t}/${s}, asking AI for a new title`);let c=r.object({title:r.string().max(80).describe("A short, unique title (2-6 words)")}),{object:u}=await a.ai.generateObject(`The title "${n}" is already taken. ${o}`,c),d=u.title;return a.logger.debug(`AI suggested new title: "${d}"`),d}var lhe=r.string().refine((e)=>!Number.isNaN(Date.parse(e)),{message:"Expected a date such as 2025-03-12"}).transform((e)=>new Date(e).toISOString()),che=/^(?:[ \t]*\r?\n)*#[ \t]+(.+?)(?:[ \t]+#+)?[ \t]*(?:\r?\n|$)/;function uhe(e,t){let n=(i)=>i.trim().replace(/\s+/g," ").toLowerCase();return n(e)===n(t)}function D2(e,t,n){let i=che.exec(t),o=i?.[1]?.trim();if(!i||!o)return{title:e,body:t};if(e&&!uhe(e,o))return{title:e,body:t};return{title:e??o,body:n?t:t.slice(i[0].length).replace(/^(?:[ \t]*\r?\n)+/,"")}}function z2(e,t){return e.issues.map((n)=>n.code==="unrecognized_keys"?`not ${t} fields: ${n.keys.join(", ")}`:`${n.path.join(".")}: ${n.message}`).join("; ")}function dhe(e,t){return[e.title,t.title].find((i)=>typeof i==="string"&&!!i.trim())?.trim()}function phe(e,t){if(e.prompt||e.from||e.url||!e.content)return{kind:"not-text"};let{noun:n}=t,i;try{i=sa(e.content)}catch(u){return{kind:"error",error:ze(u,`Unreadable ${n} frontmatter`)}}if(t.isComplete(i.frontmatter,i.content))return{kind:"not-text"};let o=t.fieldsSchema.safeParse(i.frontmatter);if(!o.success)return{kind:"error",error:`Invalid ${n} frontmatter (${z2(o.error,n)}).`};let a=t.fieldsSchema.strict().safeParse(e.fields??{});if(!a.success)return{kind:"error",error:`Invalid ${n} fields (${z2(a.error,n)}).`};let{title:s,body:l}=D2(dhe(e,i.frontmatter),i.content,t.keepTitleHeading===!0);if(!s)return{kind:"question",asks:"fields",question:`What should this ${n} be called?`,answerWith:"Pass the answer as `title`."};if(!(t.keepTitleHeading?D2(void 0,l,!1).body:l).trim())return{kind:"error",error:`The ${n} has no text besides its title.`};return{kind:"text",text:{title:s,body:l,fields:{...o.data,...a.data}}}}function mhe(e,t){let{fields:n,...i}=e;return{kind:"continue",input:{...i,title:t.title,content:hi(Object.fromEntries(Object.entries(t.frontmatter).filter(([,o])=>o!==void 0)),t.body)}}}function ghe(e,t){switch(e.kind){case"not-text":return{kind:"ready"};case"text":return{kind:"ready",...t(e.text)};default:return e}}function fhe(e){return{kind:"handled",result:{success:!1,error:typeof e==="string"?e:e.kind==="error"?e.error:`${e.question} ${e.answerWith}`}}}class eh{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 hhe="current",yhe=20;class N2{store;schema;createEmpty;key;queue=new eh;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??hhe}mutate(e){return this.queue.run(()=>this.apply(e,1))}async snapshot(){await this.settle();let e=await this.store.get(this.key);return e===null?this.createEmpty():structuredClone(e)}settle(){return this.queue.settle()}async apply(e,t){let n=await this.store.get(this.key),i=n===null?this.createEmpty():structuredClone(n),o=await e(i),a=this.schema.parse(i);if(n===null?await this.store.setIfNotExists(this.key,a):await this.store.compareAndSet(this.key,n,a))return o;if(t>=yhe)throw Error(`Status record "${this.key}" kept changing under ${t} writes`);return this.apply(e,t+1)}}var dC=Kr.extend({id:r.literal("brain-character"),entityType:r.literal("brain-character")}),th=r.object({name:r.string().describe("The brain's friendly display name"),role:r.string().describe("The brain's primary role"),purpose:r.string().describe("The brain's purpose and goals"),values:r.array(r.string()).describe("Core values that guide behavior")});var B2=r.record(r.string(),r.unknown());class Bd extends Uo{toMarkdown(e){let{metadata:t,content:n}=wn(e.content,B2);return this.buildMarkdown(n,t)}generateFrontMatter(e){let t=this.parseFrontmatter(e.content);return this.buildMarkdown("",B2.parse(t))}}class nh extends Bd{constructor(){super({entityType:"brain-character",purpose:"The brain's own identity, character, and purpose (singleton).",schema:dC,frontmatterSchema:th,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{name:t.name,role:t.role,values:t.values}}}class qd extends _m{codec;constructor(e,t,n,i,o,a){super(e,t,n,i,rn(o));this.codec=a}parseBody(e){return this.codec.parse(e)}createContent(e){return this.codec.create(e)}}class rh extends qd{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 rh(e,t,n)}constructor(e,t,n){let i=new nh;super(e,t,"brain-character",n??rh.getDefaultCharacter(),"brain character is loaded at bootstrap before any user is in scope",{parse:(o)=>i.parseCharacterBody(o),create:(o)=>i.createCharacterContent(o)})}getCharacter(){return this.get()}getCharacterContent(){return this.getContent()}}var pC=Kr.extend({id:r.literal("anchor-profile"),entityType:r.literal("anchor-profile")}),q2=r.enum(["person","team","organization"]),As=r.object({name:r.string().describe("Name of the anchor"),organization:r.string().optional().describe("Organization the anchor belongs to"),description:r.string().optional().describe("Short description or biography"),avatar:r.string().optional().describe("URL or asset path to avatar/logo"),website:r.string().optional().describe("Primary website URL"),email:r.string().optional().describe("Contact email"),socialLinks:r.array(ml).optional().describe("Social media and contact links")});class ih extends Bd{constructor(){super({entityType:"anchor-profile",purpose:"The profile of the brain's Anchor (singleton).",schema:pC,frontmatterSchema:As,isSingleton:!0,hasBody:!0})}createProfileContent(e){let t=As.parse(e);return this.buildMarkdown("",t)}parseProfileBody(e,t){if(t){let{metadata:n,content:i}=wn(e,t);return i?{...n,story:i}: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 Ld extends qd{static getDefaultProfile(){return{name:"Unknown"}}static createFresh(e,t,n){return new Ld(e,t,n)}constructor(e,t,n){let i=new ih;super(e,t,"anchor-profile",n??Ld.getDefaultProfile(),"anchor profile is loaded at bootstrap before any user is in scope",{parse:(o)=>i.parseProfileBody(o),create:(o)=>i.createProfileContent(o)})}getProfile(){return this.get()}getProfileContent(){return this.getContent()}}var oh=r.enum(["person","team","organization"]),bhe=r.object({kind:r.string().trim().min(1),category:oh,labels:r.object({singular:r.string().trim().min(1),plural:r.string().trim().min(1)})});function vhe(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 L2{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=bhe.parse(t);vhe(t.fields);let i=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:i}),this.registrations.set(n.kind,o)}unregisterPlugin(e){for(let[t,n]of this.registrations){let i=n.filter((o)=>o.pluginId!==e);if(i.length===0)this.registrations.delete(t);else this.registrations.set(t,i)}}finalize(){if(this.finalized)return this.resolved;let t=[...this.registrations.entries()].filter(([,i])=>i.length>1).sort(([i],[o])=>i.localeCompare(o))[0];if(t){let[i,o]=t,a=o.map((s)=>s.pluginId).sort().join(", ");throw Error(`Profile kind "${i}" is registered by multiple plugins: ${a}`)}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 F2=30000;class mC{logger;resolver;links=[];actorIndex=new Map;negativeActorIndex=new Map;static createFresh(e,t){return new mC(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=ks(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=ks(e.identity),i=this.negativeActorIndex.get(n);if(i&&i>Date.now())return e;this.negativeActorIndex.delete(n);let o=await this.resolver?.(e.identity);if(!o)return this.negativeActorIndex.set(n,Date.now()+F2),e;let a={identity:e.identity,...e.displayName?{label:e.displayName}:{}},s={...o,actors:[a],matchedActor:a};return this.actorIndex.set(n,{resolution:s,expiresAt:Date.now()+F2}),this.links=[...this.links.filter((l)=>l.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 $2="https://rizom.ai/ext/anchor-profile/v1",U2=r.looseObject({id:r.string(),description:r.string(),name:r.string().optional(),tags:r.array(r.string()).optional().default([])}),Z2=As.extend({kind:r.string().trim().min(1).optional(),category:oh.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"})}),She=r.looseObject({uri:r.string(),params:r.record(r.string(),r.unknown()).optional()}),G2=r.looseObject({name:r.string(),url:r.string(),description:r.string().optional(),skills:r.array(U2).optional().default([]),capabilities:r.looseObject({extensions:r.array(She).optional().default([])}).optional()});function xhe(e){let t=G2.safeParse(e);if(!t.success)return null;let n=t.data,o=(n.capabilities?.extensions??[]).find((s)=>s.uri===$2),a=null;if(o?.params){let s=Z2.safeParse(o.params);if(s.success)a=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:a}}var gC=r.object({name:r.string(),description:r.string(),tags:r.array(r.string())}),ah=r.object({about:r.string().default(""),skills:r.array(gC).default([]),notes:r.string().default("")}),whe=/^- (.+?): (.+?)(?:\s+\[(.+?)\])?$/;function The(e){let t=r.array(gC).safeParse(e);if(!t.success)return"";return t.data.map((n)=>{let i=n.tags.length>0?` [${n.tags.join(", ")}]`:"";return`- ${n.name}: ${n.description}${i}`}).join(`
|
|
331
|
+
`),metadata:{supersededMessageCount:e.skippedMessages.length,supersededMessageIds:e.skippedMessages.map((i)=>i.id).filter((i)=>i!==void 0)}}}function Yfe(e){let t=e.text.trim(),n=e.authorName?.trim();return n?`- ${n}: ${t}`:`- ${t}`}async function she(e){let{entityType:t,title:n,deriveId:i,regeneratePrompt:o,context:a}=e,s=i(n),l=await a.entityService.getEntity({entityType:t,id:s});if(!l||l.metadata.status==="generating")return n;a.logger.debug(`Entity ID collision: ${t}/${s}, asking AI for a new title`);let c=r.object({title:r.string().max(80).describe("A short, unique title (2-6 words)")}),{object:u}=await a.ai.generateObject(`The title "${n}" is already taken. ${o}`,c),d=u.title;return a.logger.debug(`AI suggested new title: "${d}"`),d}var lhe=r.string().refine((e)=>!Number.isNaN(Date.parse(e)),{message:"Expected a date such as 2025-03-12"}).transform((e)=>new Date(e).toISOString()),che=/^(?:[ \t]*\r?\n)*#[ \t]+(.+?)(?:[ \t]+#+)?[ \t]*(?:\r?\n|$)/;function uhe(e,t){let n=(i)=>i.trim().replace(/\s+/g," ").toLowerCase();return n(e)===n(t)}function D2(e,t,n){let i=che.exec(t),o=i?.[1]?.trim();if(!i||!o)return{title:e,body:t};if(e&&!uhe(e,o))return{title:e,body:t};return{title:e??o,body:n?t:t.slice(i[0].length).replace(/^(?:[ \t]*\r?\n)+/,"")}}function z2(e,t){return e.issues.map((n)=>n.code==="unrecognized_keys"?`not ${t} fields: ${n.keys.join(", ")}`:`${n.path.join(".")}: ${n.message}`).join("; ")}function dhe(e,t){return[e.title,t.title].find((i)=>typeof i==="string"&&!!i.trim())?.trim()}function phe(e,t){if(e.prompt||e.from||e.url||!e.content)return{kind:"not-text"};let{noun:n}=t,i;try{i=sa(e.content)}catch(u){return{kind:"error",error:ze(u,`Unreadable ${n} frontmatter`)}}if(t.isComplete(i.frontmatter,i.content))return{kind:"not-text"};let o=t.fieldsSchema.safeParse(i.frontmatter);if(!o.success)return{kind:"error",error:`Invalid ${n} frontmatter (${z2(o.error,n)}).`};let a=t.fieldsSchema.strict().safeParse(e.fields??{});if(!a.success)return{kind:"error",error:`Invalid ${n} fields (${z2(a.error,n)}).`};let{title:s,body:l}=D2(dhe(e,i.frontmatter),i.content,t.keepTitleHeading===!0);if(!s)return{kind:"question",asks:"fields",question:`What should this ${n} be called?`,answerWith:"Pass the answer as `title`."};if(!(t.keepTitleHeading?D2(void 0,l,!1).body:l).trim())return{kind:"error",error:`The ${n} has no text besides its title.`};return{kind:"text",text:{title:s,body:l,fields:{...o.data,...a.data}}}}function mhe(e,t){let{fields:n,...i}=e;return{kind:"continue",input:{...i,title:t.title,content:hi(Object.fromEntries(Object.entries(t.frontmatter).filter(([,o])=>o!==void 0)),t.body)}}}function ghe(e,t){switch(e.kind){case"not-text":return{kind:"ready"};case"text":return{kind:"ready",...t(e.text)};default:return e}}function fhe(e){return{kind:"handled",result:{success:!1,error:typeof e==="string"?e:e.kind==="error"?e.error:`${e.question} ${e.answerWith}`}}}class eh{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 hhe="current",yhe=20;class N2{store;schema;createEmpty;key;queue=new eh;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??hhe}mutate(e){return this.queue.run(()=>this.apply(e,1))}async snapshot(){await this.settle();let e=await this.store.get(this.key);return e===null?this.createEmpty():structuredClone(e)}settle(){return this.queue.settle()}async apply(e,t){let n=await this.store.get(this.key),i=n===null?this.createEmpty():structuredClone(n),o=await e(i),a=this.schema.parse(i);if(n===null?await this.store.setIfNotExists(this.key,a):await this.store.compareAndSet(this.key,n,a))return o;if(t>=yhe)throw Error(`Status record "${this.key}" kept changing under ${t} writes`);return this.apply(e,t+1)}}var dC=Kr.extend({id:r.literal("brain-character"),entityType:r.literal("brain-character")}),th=r.object({name:r.string().describe("The brain's friendly display name"),role:r.string().describe("The brain's primary role"),purpose:r.string().describe("The brain's purpose and goals"),values:r.array(r.string()).describe("Core values that guide behavior")});var B2=r.record(r.string(),r.unknown());class Bd extends Uo{toMarkdown(e){let{metadata:t,content:n}=wn(e.content,B2);return this.buildMarkdown(n,t)}generateFrontMatter(e){let t=this.parseFrontmatter(e.content);return this.buildMarkdown("",B2.parse(t))}}class nh extends Bd{constructor(){super({entityType:"brain-character",purpose:"The brain's own identity, character, and purpose (singleton).",schema:dC,frontmatterSchema:th,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{name:t.name,role:t.role,values:t.values}}}class qd extends _m{codec;constructor(e,t,n,i,o,a){super(e,t,n,i,rn(o));this.codec=a}parseBody(e){return this.codec.parse(e)}createContent(e){return this.codec.create(e)}}class rh extends qd{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 rh(e,t,n)}constructor(e,t,n){let i=new nh;super(e,t,"brain-character",n??rh.getDefaultCharacter(),"brain character is loaded at bootstrap before any user is in scope",{parse:(o)=>i.parseCharacterBody(o),create:(o)=>i.createCharacterContent(o)})}getCharacter(){return this.get()}getCharacterContent(){return this.getContent()}}var pC=Kr.extend({id:r.literal("anchor-profile"),entityType:r.literal("anchor-profile")}),q2=r.enum(["person","team","organization"]),As=r.object({name:r.string().describe("Name of the anchor"),organization:r.string().optional().describe("Organization the anchor belongs to"),description:r.string().optional().describe("Short description or biography"),avatar:r.string().optional().describe("URL or asset path to avatar/logo"),photo:r.string().optional().describe("A photo of the people behind the anchor, as "),website:r.string().optional().describe("Primary website URL"),email:r.string().optional().describe("Contact email"),socialLinks:r.array(ml).optional().describe("Social media and contact links")});class ih extends Bd{constructor(){super({entityType:"anchor-profile",purpose:"The profile of the brain's Anchor (singleton).",schema:pC,frontmatterSchema:As,isSingleton:!0,hasBody:!0})}createProfileContent(e){let t=As.parse(e);return this.buildMarkdown("",t)}parseProfileBody(e,t){if(t){let{metadata:n,content:i}=wn(e,t);return i?{...n,story:i}: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 Ld extends qd{static getDefaultProfile(){return{name:"Unknown"}}static createFresh(e,t,n){return new Ld(e,t,n)}constructor(e,t,n){let i=new ih;super(e,t,"anchor-profile",n??Ld.getDefaultProfile(),"anchor profile is loaded at bootstrap before any user is in scope",{parse:(o)=>i.parseProfileBody(o),create:(o)=>i.createProfileContent(o)})}getProfile(){return this.get()}getProfileContent(){return this.getContent()}}var oh=r.enum(["person","team","organization"]),bhe=r.object({kind:r.string().trim().min(1),category:oh,labels:r.object({singular:r.string().trim().min(1),plural:r.string().trim().min(1)})});function vhe(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 L2{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=bhe.parse(t);vhe(t.fields);let i=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:i}),this.registrations.set(n.kind,o)}unregisterPlugin(e){for(let[t,n]of this.registrations){let i=n.filter((o)=>o.pluginId!==e);if(i.length===0)this.registrations.delete(t);else this.registrations.set(t,i)}}finalize(){if(this.finalized)return this.resolved;let t=[...this.registrations.entries()].filter(([,i])=>i.length>1).sort(([i],[o])=>i.localeCompare(o))[0];if(t){let[i,o]=t,a=o.map((s)=>s.pluginId).sort().join(", ");throw Error(`Profile kind "${i}" is registered by multiple plugins: ${a}`)}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 F2=30000;class mC{logger;resolver;links=[];actorIndex=new Map;negativeActorIndex=new Map;static createFresh(e,t){return new mC(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=ks(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=ks(e.identity),i=this.negativeActorIndex.get(n);if(i&&i>Date.now())return e;this.negativeActorIndex.delete(n);let o=await this.resolver?.(e.identity);if(!o)return this.negativeActorIndex.set(n,Date.now()+F2),e;let a={identity:e.identity,...e.displayName?{label:e.displayName}:{}},s={...o,actors:[a],matchedActor:a};return this.actorIndex.set(n,{resolution:s,expiresAt:Date.now()+F2}),this.links=[...this.links.filter((l)=>l.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 $2="https://rizom.ai/ext/anchor-profile/v1",U2=r.looseObject({id:r.string(),description:r.string(),name:r.string().optional(),tags:r.array(r.string()).optional().default([])}),Z2=As.extend({kind:r.string().trim().min(1).optional(),category:oh.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"})}),She=r.looseObject({uri:r.string(),params:r.record(r.string(),r.unknown()).optional()}),G2=r.looseObject({name:r.string(),url:r.string(),description:r.string().optional(),skills:r.array(U2).optional().default([]),capabilities:r.looseObject({extensions:r.array(She).optional().default([])}).optional()});function xhe(e){let t=G2.safeParse(e);if(!t.success)return null;let n=t.data,o=(n.capabilities?.extensions??[]).find((s)=>s.uri===$2),a=null;if(o?.params){let s=Z2.safeParse(o.params);if(s.success)a=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:a}}var gC=r.object({name:r.string(),description:r.string(),tags:r.array(r.string())}),ah=r.object({about:r.string().default(""),skills:r.array(gC).default([]),notes:r.string().default("")}),whe=/^- (.+?): (.+?)(?:\s+\[(.+?)\])?$/;function The(e){let t=r.array(gC).safeParse(e);if(!t.success)return"";return t.data.map((n)=>{let i=n.tags.length>0?` [${n.tags.join(", ")}]`:"";return`- ${n.name}: ${n.description}${i}`}).join(`
|
|
332
332
|
`)}function _he(e){return e.split(`
|
|
333
333
|
`).flatMap((t)=>{let n=t.match(whe);if(!n)return[];let i=(n[3]??"").split(",").map((o)=>o.trim()).filter(Boolean);return[{name:n[1]??"",description:n[2]??"",tags:i}]})}var W2=new ca(ah,{title:"Agent",mappings:[{key:"about",label:"About",type:"string"},{key:"skills",label:"Skills",type:"custom",formatter:The,parser:_he},{key:"notes",label:"Notes",type:"string"}]});function Che(e){return W2.format(e)}function Ihe(e){if(!e.trim())return ah.parse({});try{return W2.parse(e)}catch{return ah.parse({})}}import{EventEmitter as Y2}from"events";var an={REGISTERED:"registered",INITIALIZED:"initialized",ERROR:"error",DISABLED:"disabled"},ci={REGISTERED:"plugin:registered",BEFORE_INITIALIZE:"plugin:before_initialize",INITIALIZED:"plugin:initialized",ERROR:"plugin:error",DISABLED:"plugin:disabled"};class ui extends Error{pluginId;constructor(e,t){super(`Plugin ${e}: ${t}`);this.name="PluginError",this.pluginId=e}}function V2(e,t){return Reflect.get(e,t,e)}function H2(e,t,n){if(typeof e!=="function")throw TypeError("Cannot apply a non-callable trapped member");return Reflect.apply(e,t,n)}class fC{scope;ingress=new Set;closePromise=null;closed=!1;constructor(){this.scope=we.runSync(Gt.make())}assertOpen(){if(this.closed)throw Error("Cannot register a resource after plugin teardown")}acquire(e,t){this.assertOpen();let n=e();try{this.addFinalizer(()=>t(n))}catch(i){try{t(n)}catch(o){throw AggregateError([i,o],"Plugin acquisition rollback failed",{cause:o})}throw i}return n}addFinalizer(e){this.assertOpen(),we.runSync(Gt.addFinalizer(this.scope,we.promise(async()=>{await e()})))}addIngress(e){this.assertOpen(),this.ingress.add(e)}close(e=Qt.void){return this.closed=!0,this.closePromise??=this.closeScope(e),this.closePromise}async closeScope(e){let t,n=!1,i=[...this.ingress].reverse();for(let l of i)try{l.stopAdmission()}catch(c){if(!n)t=c;n=!0}let o=await Promise.allSettled(i.map((l)=>Promise.resolve().then(()=>l.drain())));this.ingress.clear();let a=o.find((l)=>l.status==="rejected");if(!n&&a)t=a.reason,n=!0;let s=await we.runPromiseExit(Gt.close(this.scope,e));if(!n&&Qt.isFailure(s))t=ni.squash(s.cause),n=!0;if(n)throw t}}function Ps(e,t,n,i){return new Proxy(e,{get(o,a){let s=V2(o,a);if(typeof a==="string"&&t.some((l)=>l===a)&&typeof s==="function")return(...l)=>n.acquire(()=>H2(s,o,l),(c)=>i(l,c));return typeof s==="function"?s.bind(o):s}})}function J2(e){return typeof e==="function"}function Fd(e,t,n){return Ps(e,t,n,(i)=>{let o=i[0];if(typeof o==="string")e.unregisterPlugin(o)})}function K2(e,t){let n=e.getMessageBus(),i=new Set,o=(z,j,x)=>{t.assertOpen();let P=!0,L=new Set,N=x((oe)=>{if(!P)return{noop:!0};let J,re=new Promise((q)=>{J=q});L.add(re);let Se=()=>{L.delete(re),J()},A;try{A=Promise.resolve(j(oe))}catch(q){throw Se(),q}return A.then((q)=>(Se(),q),(q)=>{throw Se(),q})}),K={type:z,originalHandler:j,stopAdmission:()=>{if(!P)return;P=!1,N(),i.delete(K)}};i.add(K);try{t.addIngress({stopAdmission:K.stopAdmission,drain:async()=>{await Promise.all(L)}})}catch(oe){throw K.stopAdmission(),oe}return K.stopAdmission},a={send:(z)=>n.send(z),hasHandlers:(z)=>n.hasHandlers?.(z)??!1,subscribe:(z,j,x)=>o(z,j,(P)=>n.subscribe(z,P,x)),observe:(z,j)=>o(z,j,(x)=>n.observe(z,x)),deliverPeer:(z,j)=>n.deliverPeer(z,j),unsubscribe:(z,j)=>{let x=[...i].filter((P)=>P.type===z&&P.originalHandler===j);if(x.length===0){n.unsubscribe(z,j);return}for(let P of x)P.stopAdmission()},collect:(z)=>n.collect(z),validateMessage:(z,j)=>n.validateMessage(z,j),getHandlerCount:(z)=>n.getHandlerCount(z),getTargetedHandlerCount:(z,j)=>n.getTargetedHandlerCount(z,j),clearHandlers:(z)=>n.clearHandlers(z),clearAllHandlers:()=>n.clearAllHandlers()},s=e.getAttachmentRegistry(),l={...s,register:(z,j,x)=>t.acquire(()=>s.register(z,j,x),(P)=>P())},c=e.getEntityRegistry(),u=Ps(c,["registerEntityType"],t,(z)=>{let j=z[0];if(typeof j==="string")c.unregisterEntityType(j)}),d=Fd(e.getProfileKindRegistry(),["register"],t),p=Fd(e.getChannelRegistry(),["registerDescriptor","registerDeliveryProvider"],t),m=Fd(e.getInboxRegistry(),["registerSource"],t),g=Fd(e.getInboxFollowUpRegistry(),["registerKind"],t),f=e.getAccountSettingsRegistry(),h=Ps(f,["register"],t,(z,j)=>{H2(f.unregister,f,[j])}),y=Ps(e.getAuthRegistry(),["bindBackend"],t,(z,j)=>{if(J2(j))j()}),w=Ps(e.getAtprotoProjectionRegistry(),["register"],t,(z,j)=>{if(J2(j))j()}),I=Fd(e.getOperationalHealthRegistry(),["register"],t),b=e.getDataSourceRegistry(),v=Ps(b,["register"],t,(z)=>{let j=z[0];if(typeof j==="object"&&j!==null&&"id"in j&&typeof j.id==="string"){let x=j.id.includes(":")?j.id:`shell:${j.id}`;b.unregister(x)}}),R=e.getAnalyticsRegistry(),S=Ps(R,["register"],t,(z)=>{let j=z[0];if(typeof j==="object"&&j!==null&&"type"in j&&typeof j.type==="string")R.unregister(j.type)}),M=new Proxy(e,{get(z,j){if(j==="getMessageBus")return()=>a;if(j==="getAttachmentRegistry")return()=>l;if(j==="getEntityRegistry")return()=>u;if(j==="getDataSourceRegistry")return()=>v;if(j==="getProfileKindRegistry")return()=>d;if(j==="getChannelRegistry")return()=>p;if(j==="getInboxRegistry")return()=>m;if(j==="getInboxFollowUpRegistry")return()=>g;if(j==="getOperationalHealthRegistry")return()=>I;if(j==="getAccountSettingsRegistry")return()=>h;if(j==="getAuthRegistry")return()=>y;if(j==="getAtprotoProjectionRegistry")return()=>w;if(j==="getAnalyticsRegistry")return()=>S;let x=V2(z,j);return typeof x==="function"?x.bind(z):x}});return HO(e,M),M}class hC{plugins;events;daemonRegistry;logger;projectionRegistry;resourceScopes=new Map;releasePromises=new Map;constructor(e,t,n,i,o){this.plugins=e,this.events=t,this.daemonRegistry=n,this.projectionRegistry=i,this.logger=o.child("PluginLifecycle")}async initializePlugin(e,t,n){let i=this.plugins.get(e);if(!i)throw new ui(e,"Registration failed: Plugin is not registered");let o=i.plugin,a=new fC;a.addFinalizer(()=>t.unregisterPluginCapabilities?.(e)),a.addFinalizer(()=>t.getJobQueueService().unregisterPluginHandlers(e)),a.addFinalizer(()=>this.projectionRegistry.unregisterPlugin(e)),this.resourceScopes.set(e,a),this.releasePromises.delete(e),this.logger.debug(`Initializing plugin: ${e}`);try{this.events.emit(ci.BEFORE_INITIALIZE,e,o);let s=await o.register(K2(t,a),n);return i.status=an.INITIALIZED,this.logger.debug(`Initialized plugin: ${e}`),this.events.emit(ci.INITIALIZED,e,o),s}catch(s){throw this.logger.error(`Error initializing plugin ${e}: ${ze(s)}`),await this.failPluginInitialization(e,s),s}}async finalizePluginRegistration(e){let t=this.plugins.get(e);if(!t)throw new ui(e,"Registration finalization failed: Plugin is not registered");if(t.status!==an.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 ui(e,"Ready failed: Plugin is not registered");if(t.status!==an.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 i=yl(n);t.status=an.ERROR,t.error=i;try{this.events.emit(ci.ERROR,e,i)}catch(o){this.logger.error(`Plugin error listener failed for ${e}`,o)}throw i}}async startPluginDaemons(e){let t=this.plugins.get(e);if(t?.status!==an.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: ${ze(n)}`)}}async failPluginInitialization(e,t){let n=this.plugins.get(e);if(!n)return;let i=n.status!==an.ERROR,o=yl(t);if(n.status=an.ERROR,n.error=o,await this.releasePluginResources(e,Qt.fail(t)),i)try{this.events.emit(ci.ERROR,e,o)}catch(a){this.logger.error(`Plugin error listener failed for ${e}`,a)}}async disablePlugin(e){let t=this.plugins.get(e);if(!t){this.logger.warn(`Cannot disable plugin ${e}: not registered`);return}if(t.status===an.DISABLED)return;this.logger.debug(`Disabling plugin: ${e}`);let n=t.status===an.ERROR;await this.releasePluginResources(e,Qt.void);let i=this.plugins.get(e);if(!n&&i&&i.status!==an.DISABLED)i.status=an.DISABLED,this.events.emit(ci.DISABLED,e,i.plugin);this.logger.debug(`Disabled plugin: ${e}`)}releasePluginResources(e,t){let n=this.releasePromises.get(e);if(n)return n;let i=this.releasePluginResourcesOnce(e,t);return this.releasePromises.set(e,i),i}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 i=this.resourceScopes.get(e);if(this.resourceScopes.delete(e),i)try{await i.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(a){this.logger.error(`Failed to unregister daemon ${o.name} for plugin ${e}`,a)}}}class yC{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,i=!0;while(i&&n.size<t.length){i=!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),i=!0}catch(u){let d=ze(u);this.logger.error(`Failed to initialize plugin ${s}: ${d}`),n.add(s),i=!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 l of o){let c=this.getUnmetDependencies(l);this.logger.error(`Plugin ${l} has unmet dependencies: ${c.join(", ")}`);let u=this.plugins.get(l);if(u)u.status=an.ERROR,u.error=new ui(l,`Unmet dependencies: ${c.join(", ")}`);this.events.emit(ci.ERROR,l,u?.error)}}let a=new Set;for(let[s,l]of this.plugins)if(l.status===an.INITIALIZED)a.add(s);return this.logger.debug(`Resolved ${a.size} of ${t.length} plugins`),{initialized:a,failed:o}}getUnmetDependencies(e){let t=this.plugins.get(e);if(!t)return[];let{dependencies:n}=t,i=[];for(let o of n){let a=this.plugins.get(o);if(!a){i.push(o);continue}if(a.status!==an.INITIALIZED)i.push(o)}return i}}class bC{logger;projectionRegistry;constructor(e,t){this.logger=e.child("CapabilityRegistrar"),this.projectionRegistry=t}async registerCapabilities(e,t,n,i){if(!i?.executionOnly&&n.tools.length>0)e.registerTools(t,n.tools),this.logger.debug(`Registered ${n.tools.length} tools from ${t}`);if(!i?.executionOnly&&n.resources.length>0)e.registerResources(t,n.resources),this.logger.debug(`Registered ${n.resources.length} resources from ${t}`);if(!i?.executionOnly&&n.instructions)e.registerInstructions(t,n.instructions),this.logger.debug(`Registered instructions from ${t}`);let o=n.projectionRules??[];try{for(let a of o)this.projectionRegistry.registerRule(t,a)}catch(a){throw this.projectionRegistry.unregisterPlugin(t),a}if(o.length>0)this.logger.debug(`Registered ${o.length} projection rules from ${t}`)}}class sh{projections=new Map;rules=new Map;static createFresh(){return new sh}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 i={id:t.id,pluginId:e,targetType:t.targetType,sources:t.sources.map((a)=>({kind:a.kind,types:[...a.types],...a.excludeTypes?{excludeTypes:[...a.excludeTypes]}:{}}))};this.projections.set(t.id,i),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)===i)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(Rhe)}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 i=e.filter(({projectionSource:s})=>s).map(({type:s})=>s).sort(),o=Ahe(t,i),a=Ohe(t,o)[0];if(a){let s=Mhe(a,o);throw Error(`Projection cycle is not supported: ${[...s,s[0]].join(" -> ")}`)}return khe({projections:t,edges:o,unknownSourceTypes:Ehe(t,n)})}}function Ehe(e,t){let n=[];for(let i of e){let o=[...new Set(i.sources.flatMap((a)=>[...a.types,...a.excludeTypes??[]]).filter((a)=>a!=="*"&&!t.has(a)))].sort();if(o.length>0)n.push({projectionId:i.id,types:o})}return n}function khe(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 Rhe(e){return{...e,sources:e.sources.map((t)=>({...t,types:[...t.types],...t.excludeTypes?{excludeTypes:[...t.excludeTypes]}:{}}))}}function Ahe(e,t){let n=new Map;for(let i of e)for(let o of e){let a=Phe(i,o,t);if(a.length===0)continue;n.set(`${i.id}\x00${o.id}`,new Set(a))}return Array.from(n,([i,o])=>{let[a="",s=""]=i.split("\x00");return{from:a,to:s,causes:[...o].sort()}}).sort((i,o)=>i.from.localeCompare(o.from)||i.to.localeCompare(o.to))}function Phe(e,t,n){let i=[];for(let o of t.sources){let a=new Set(o.excludeTypes??[]);if((o.types.includes("*")?[...o.types.filter((l)=>l!=="*"),...n]:o.types).includes(e.targetType)&&!a.has(e.targetType))i.push(`entity:${e.targetType}`)}return[...new Set(i)]}function Ohe(e,t){let n=e.map(({id:p})=>p).sort(),i=Q2(n,t),o=new Map,a=new Map,s=[],l=new Set,c=[],u=0,d=(p)=>{o.set(p,u),a.set(p,u),u++,s.push(p),l.add(p);for(let h of i.get(p)??[])if(!o.has(h))d(h),a.set(p,Math.min(a.get(p)??0,a.get(h)??0));else if(l.has(h))a.set(p,Math.min(a.get(p)??0,o.get(h)??0));if(a.get(p)!==o.get(p))return;let m=[],g;do{if(g=s.pop(),!g)break;l.delete(g),m.push(g)}while(g!==p);let f=i.get(p)?.includes(p)??!1;if(m.length>1||f)c.push(m.sort())};for(let p of n)if(!o.has(p))d(p);return c.sort((p,m)=>(p[0]??"").localeCompare(m[0]??""))}function Mhe(e,t){let n=new Set(e),i=Q2(e,t),o=[...e].sort()[0];if(!o)return[];if(i.get(o)?.includes(o))return[o];let a=(s,l)=>{for(let c of i.get(s)??[]){if(!n.has(c))continue;if(c===o)return l;if(l.includes(c))continue;let u=a(c,[...l,c]);if(u)return u}return};return a(o,[o])??[...e].sort()}function Q2(e,t){let n=new Map;for(let i of e)n.set(i,[]);for(let i of t){let o=n.get(i.from);if(o&&!o.includes(i.to))o.push(i.to)}for(let i of n.values())i.sort();return n}class lh{plugins=new Map;logger;events=new Y2;daemonRegistry;shell=null;initializedPluginIds=[];pluginLifecycle;dependencyResolver;capabilityRegistrar;projectionRegistry=sh.createFresh();projectionGraph;static createFresh(e,t){return new lh(e,t)}setShell(e){this.shell=e}constructor(e,t){this.logger=e.child("PluginManager"),this.events=new Y2,this.daemonRegistry=t,this.pluginLifecycle=new hC(this.plugins,this.events,this.daemonRegistry,this.projectionRegistry,e),this.dependencyResolver=new yC(this.plugins,this.events,e),this.capabilityRegistrar=new bC(e,this.projectionRegistry)}registerPlugin(e){if(!e.id)throw new ui("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 ui(e.id,`Registration failed: Plugin is already registered with version ${o}`)}let t=e.dependencies??[],n={plugin:e,status:an.REGISTERED,dependencies:t};this.plugins.set(e.id,n),this.logger.debug(`Registered plugin: ${e.id} (${e.version})`),this.events.emit(ci.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 registerInterfaceChannels(e,t){let n=this.shell;if(!n)throw Error("Cannot register interface channels: Shell not set. Call setShell() first.");for(let i of e)try{await i.registerChannelsForExecution?.(n,t)}catch(o){this.logger.error(`Channel registration failed for interface ${i.id}: ${ze(o)}`)}}async initializePlugin(e,t){if(!this.shell)throw new ui(e,"Cannot initialize plugin: Shell not set. Call setShell() first.");let n=this.shell;try{let i=await this.pluginLifecycle.initializePlugin(e,n,t);await this.capabilityRegistrar.registerCapabilities(n,e,i,{executionOnly:t?.executionOnly}),this.initializedPluginIds.push(e)}catch(i){throw await this.pluginLifecycle.failPluginInitialization(e,i),i}}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 i=e.getEntityTypeConfig(n);return{type:n,projectionSource:i.projectionSource!==!1&&i.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 vC(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===an.ERROR)await this.pluginLifecycle.failPluginInitialization(t,n.error??e)}throw e}}async startPluginDaemons(){this.logger.debug("Starting plugin daemons..."),await vC(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===an.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===an.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 X2={public:0,trusted:1,admin:2},jhe=[{id:"dashboard",roles:["dashboard"],label:"Dashboard",visibility:"public",requiresActiveSession:!1},{id:"web-chat",roles:["studio-chat","ask"],requiresRole:"chat-api",label:"Chat",visibility:"trusted",requiresActiveSession:!0},{id:"studio",roles:["studio"],label:"Studio",visibility:"public",requiresActiveSession:!0}];function Dhe(e,t){let n=X2[t.permissionLevel??"public"],i=[];for(let{id:o,roles:a,requiresRole:s,label:l,visibility:c,requiresActiveSession:u}of jhe){let d=t.self?.id===o;if(!d&&(n<X2[c]||u&&t.hasActiveSession!==!0))continue;let p=d?t.self?.href:s&&!fa(e,s)?void 0:a.map((m)=>fa(e,m)?.fullPath).find((m)=>m!==void 0);if(p!==void 0)i.push({id:o,label:l,href:p,isActive:o===t.activeId,...u?{requiresActiveSession:!0}:{}})}return i}class eG{definitions=new Map;register(e){this.definitions.set(e.type,e)}unregister(e){this.definitions.delete(e)}getDefinitions(){return Array.from(this.definitions.values())}async run(e){let t=this.definitions.get(e.type);if(!t)throw Error(`Unknown analytics report: ${e.type}. Available: ${Array.from(this.definitions.keys()).join(", ")}`);let n=t.minVisibility??"public";if(!_i.hasPermission(e.permission,n))throw Error(`The ${t.type} report answers ${n} callers only`);let i=t.params.safeParse(e.params??{});if(!i.success){let s=i.error.issues.map((l)=>`${l.path.join(".")||"params"}: ${l.message}`).join("; ");throw Error(`Invalid params for ${t.type}: ${s}`)}let o=Hr(e.permission),a=o==="public"?iu(e.entityService,{publishedOnly:!0,visibilityScope:o}):e.entityService;return t.handler(i.data,{entityService:a,visibilityScope:o})}}function zhe(e){return e}function ch(e){let t=e?.trim();if(!t)return"http://localhost:8080";let n=t.replace(/\/+$/,""),i=new URL(n);if(i.pathname!=="/"||i.search||i.hash)throw Error("OAuth issuer must be an origin without path, query, or hash");return i.origin}function Nhe(e){let t=new URL(ch(e)).hostname.toLowerCase();return t==="localhost"||t==="[::1]"||t==="::1"||t.startsWith("127.")}function tG(e,t){let i=e.headers.get("x-forwarded-proto")?.split(",")[0]?.trim(),o=e.headers.get("x-forwarded-host")??e.headers.get("host");if(o){let a=i??new URL(e.url).protocol.replace(":","");return ch(`${a}://${o}`)}return ch(t??new URL(e.url).origin)}function nG(e,t){return new Response(JSON.stringify({error:e}),{status:t,headers:{"Content-Type":"application/json; charset=utf-8","Cache-Control":"no-store"}})}function rG(e){let t=e.headers.get("origin");if(t===null)return!1;try{return t===tG(e)}catch{return!1}}function iG(e){return rG(e)?void 0:nG("Same-origin request required",403)}function Bhe(e){let t=iG(e);if(t)return t;if(!e.headers.get("content-type")?.startsWith("application/json"))return nG("JSON request required",415);return}export{Fs as Ga,ep as Ha,rn as Ia,E as Ja,Gs as Ka,W as La,Wo as Ma,ge as Na,Rn as Oa,Zn as Pa,aI as Qa,Qn as Ra,Rt as Sa,Ln as Ta,co as Ua,Na as Va,Jo as Wa,yt as Xa,en as Ya,vI as Za,cp as _a,Ho as $a,tt as ab,be as bb,Lt as cb,Mt as db,Hh as eb,mr as fb,V as gb,wp as hb,fy as ib,Si as jb,xi as kb,vE as lb,rW as mb,iW as nb,Mn as ob,Ko as pb,fn as qb,pn as rb,Or as sb,uo as tb,At as ub,ti as vb,SE as wb,oW as xb,aW as yb,sW as zb,Fc as Ab,Ni as Bb,Vr as Cb,Yd as Db,Hr as Eb,Ls as Fb,Kr as Gb,RC as Hb,Lhe as Ib,Fhe as Jb,Vd as Kb,yi as Lb,wn as Mb,vh as Nb,Hd as Ob,Aa as Pb,Bs as Qb,dr as Rb,EC as Sb,Pa as Tb,Ip as Ub,Rp as Vb,Iy as Wb,Ey as Xb,Ap as Yb,Pp as Zb,Ry as _b,Mp as $b,Ys as ac,Fi as bc,Xs as cc,jr as dc,wi as ec,Uy as fc,Zy as gc,$W as hc,UW as ic,Hy as jc,Qy as kc,Ui as lc,Jp as mc,ck as nc,ta as oc,uk as pc,iEe as qc,oEe as rc,Vp as sc,F as tc,Zi as uc,C as vc,Te as wc,_ as xc,Yn as yc,fk as zc,go as Ac,zr as Bc,fr as Cc,Vc as Dc,Oe as Ec,_n as Fc,pt as Gc,vk as Hc,Sk as Ic,ft as Jc,nl as Kc,rl as Lc,ra as Mc,Vk as Nc,um as Oc,ul as Pc,_b as Qc,Cb as Rc,Db as Sc,ym as Tc,Wb as Uc,Tm as Vc,eA as Wc,nA as Xc,Uo as Yc,xh as Zc,qH as _c,rA as $c,Cm as ad,Jb as bd,iA as cd,Oa as dd,gye as ed,fye as fd,hye as gd,yye as hd,wh as id,Th as jd,_h as kd,SG as ld,bye as md,vye as nd,Sye as od,xye as pd,wye as qd,Tye as rd,_ye as sd,Cye as td,Hb as ud,oA as vd,hl as wd,E2e as xd,N3 as yd,DO as zd,ag as Ad,ua as Bd,BA as Cd,yqe as Dd,Iv as Ed,jm as Fd,RK as Gd,AK as Hd,PK as Id,OK as Jd,VA as Kd,uu as Ld,MK as Md,jK as Nd,fl as Od,ca as Pd,zK as Qd,YA as Rd,XA as Sd,qK as Td,nP as Ud,FK as Vd,Em as Wd,la as Xd,ev as Yd,nv as Zd,rv as _d,Nm as $d,ce as ae,_t as be,Nv as ce,qv as de,Lv as ee,is as fe,Fv as ge,gu as he,fu as ie,$v as je,Uv as ke,Zv as le,a4 as me,kt as ne,Bm as oe,qm as pe,IFe as qe,EFe as re,s4 as se,TP as te,RFe as ue,f4 as ve,AFe as we,PFe as xe,OFe as ye,MFe as ze,jFe as Ae,DFe as Be,zFe as Ce,NFe as De,BFe as Ee,qFe as Fe,LFe as Ge,x4 as He,w4 as Ie,$Fe as Je,UFe as Ke,ZFe as Le,GFe as Me,WFe as Ne,JFe as Oe,VFe as Pe,HFe as Qe,Ne as Re,jn as Se,as as Te,bo as Ue,Lm as Ve,Fm as We,AP as Xe,PP as Ye,I4 as Ze,$m as _e,av as $e,HH as af,KH as bf,sv as cf,lv as df,vu as ef,t0 as ff,Su as gf,Zm as hf,ss as if,r0 as jf,Gm as kf,Xv as lf,i0 as mf,Wm as nf,eS as of,tS as pf,L4 as qf,iS as rf,Z4 as sf,Ym as tf,_A as uf,Pm as vf,PA as wf,yv as xf,Tv as yf,jA as zf,sg as Af,aS as Bf,vl as Cf,lS as Df,I5 as Ef,E5 as Ff,k5 as Gf,uS as Hf,R5 as If,A5 as Jf,P5 as Kf,O5 as Lf,M5 as Mf,j5 as Nf,z5 as Of,TM as Pf,N5 as Qf,U3 as Rf,Cl as Sf,IM as Tf,AM as Uf,OM as Vf,Tg as Wf,hr as Xf,_g as Yf,jM as Zf,ix as _f,LM as $f,Nu as ag,FM as bg,kl as cg,$M as dg,Q5 as eg,UM as fg,ZM as gg,l6 as hg,WM as ig,m6 as jg,g6 as kg,f6 as lg,h6 as mg,y6 as ng,ax as og,wo as pg,_6 as qg,sx as rg,dx as sg,I6 as tg,Jn as ug,Q4 as vg,Y4 as wg,X4 as xg,tQ as yg,uQ as zg,x0 as Ag,_0 as Bg,k0 as Cg,RS as Dg,A0 as Eg,jO as Fg,M3 as Gg,z3 as Hg,O0 as Ig,j0 as Jg,wS as Kg,$3 as Lg,US as Mg,ZS as Ng,nM as Og,Il as Pg,mg as Qg,gg as Rg,Mu as Sg,fg as Tg,uM as Ug,ju as Vg,n5 as Wg,r5 as Xg,i5 as Yg,o5 as Zg,a5 as _g,Du as $g,zu as ah,E6 as bh,nj as ch,R6 as dh,sj as eh,v5 as fh,T5 as gh,xg as hh,vM as ih,SM as jh,_5 as kh,lj as lh,C5 as mh,Gne as nh,T3e as oh,Kl as ph,KT as qh,YT as rh,XT as sh,e_ as th,t_ as uh,Le as vh,R_ as wh,qge as xh,H_ as yh,Sfe as zh,e2 as Ah,i2 as Bh,o2 as Ch,a2 as Dh,s2 as Eh,c2 as Fh,tC as Gh,nC as Hh,m2 as Ih,rC as Jh,Zf as Kh,h2 as Lh,Gf as Mh,iC as Nh,y2 as Oh,b2 as Ph,S2 as Qh,x2 as Rh,Wf as Sh,_2 as Th,C2 as Uh,Vf as Vh,Dd as Wh,zd as Xh,I2 as Yh,E2 as Zh,k2 as _h,uC as $h,Nd as ai,A2 as bi,P2 as ci,O2 as di,M2 as ei,j2 as fi,she as gi,lhe as hi,phe as ii,mhe as ji,ghe as ki,fhe as li,eh as mi,N2 as ni,th as oi,nh as pi,rh as qi,q2 as ri,As as si,ih as ti,Ld as ui,L2 as vi,mC as wi,$2 as xi,xhe as yi,gC as zi,Che as Ai,Ihe as Bi,ui as Ci,lh as Di,Dhe as Ei,eG as Fi,zhe as Gi,ch as Hi,Nhe as Ii,tG as Ji,iG as Ki,Bhe as Li};
|
|
334
334
|
|
|
335
|
-
//# debugId=
|
|
336
|
-
//# sourceMappingURL=index-
|
|
335
|
+
//# debugId=713AA1C4AB8ABDB964756E2164756E21
|
|
336
|
+
//# sourceMappingURL=index-agcfmyk2.js.map
|