@rizom/brain 0.2.0-alpha.261 → 0.2.0-alpha.262
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 +729 -729
- package/dist/chunks/{app-5n7yyhey.js → app-dfb6p4xh.js} +2 -2
- package/dist/chunks/{blog-post-adapter-9nac048d.js → blog-post-adapter-0czbdhxx.js} +2 -2
- package/dist/chunks/{index-4xtwq1dr.js → index-710dct7r.js} +3 -3
- package/dist/chunks/{index-4xtwq1dr.js.map → index-710dct7r.js.map} +1 -1
- package/dist/chunks/{index-myf58zvm.js → index-bah94jtg.js} +8 -8
- package/dist/chunks/{index-myf58zvm.js.map → index-bah94jtg.js.map} +1 -1
- package/dist/chunks/{index-p56p1x2f.js → index-q41qdf7x.js} +3 -3
- package/dist/chunks/{index-p56p1x2f.js.map → index-q41qdf7x.js.map} +4 -4
- package/dist/chunks/{index-mqdmgpcs.js → index-vn09sbyw.js} +3 -3
- package/dist/chunks/{index-mqdmgpcs.js.map → index-vn09sbyw.js.map} +1 -1
- package/dist/chunks/{index-nc9x5hwp.js → index-zj13z1g2.js} +3 -3
- package/dist/chunks/{linkedin-template-t4tf75m5.js → linkedin-template-s03h4sbp.js} +2 -2
- package/dist/chunks/{rss-datasource-eyj1p94q.js → rss-datasource-ab8e709e.js} +2 -2
- package/dist/index.js +1 -1
- package/dist/model.js +34 -34
- package/dist/model.js.map +1 -1
- package/dist/plugins.js +1 -1
- package/dist/site.js +2 -2
- package/dist/site.js.map +1 -1
- package/package.json +1 -1
- /package/dist/chunks/{app-5n7yyhey.js.map → app-dfb6p4xh.js.map} +0 -0
- /package/dist/chunks/{blog-post-adapter-9nac048d.js.map → blog-post-adapter-0czbdhxx.js.map} +0 -0
- /package/dist/chunks/{index-nc9x5hwp.js.map → index-zj13z1g2.js.map} +0 -0
- /package/dist/chunks/{linkedin-template-t4tf75m5.js.map → linkedin-template-s03h4sbp.js.map} +0 -0
- /package/dist/chunks/{rss-datasource-eyj1p94q.js.map → rss-datasource-ab8e709e.js.map} +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$e as i,$f as mZ,Af as fA,Jf as hf,Le as g,Mf as u$,Ne as w,Oe as D,Pf as zf,Qe as m,Re as Ff,Rf as P$,Se as W0,Sf as xf,Ue as Bf,Ve as kf,We as Z$,Wf as jf,Xf as bf,Ye as U$,Ze as E0,_e as $f,_f as Q$,ag as GA,bf as j,cf as k,cg as yf,df as t,eg as vA,ff as b,jf as gf,kf as pf,of as gU,rf as MA,tf as u,uf as v,vf as ef,wf as G,xf as Hf,yf as AA}from"./index-h766y45k.js";import{pg as of}from"./index-zzk961wq.js";import{Hg as fZ,Kg as lA}from"./index-1qkfzrqr.js";import{Dh as AZ}from"./index-w77s1gcj.js";import{Bi as EZ,Ci as Of,Hi as Df,Ki as NA,Uh as lf,Vh as nf,Wh as df,Zh as HZ,bi as Af,ci as G0,di as z0,ei as A0,li as F0,ri as S,si as Nf,ti as TZ,ui as Lf,vi as Uf,xi as R$}from"./index-fqrd7rca.js";import{Si as U}from"./index-58smerak.js";var uU=U.object({id:U.string(),sessionId:U.string(),interfaceType:U.string(),channelId:U.string(),personId:U.string().optional(),channelName:U.string().optional(),startedAt:U.string(),lastActiveAt:U.string(),createdAt:U.string(),updatedAt:U.string(),metadata:lA}),IU=U.object({id:U.string(),conversationId:U.string(),role:Lf,content:U.string(),timestamp:U.string(),metadata:lA});var nA=U.object({name:U.string(),role:U.string(),purpose:U.string(),values:U.array(U.string())}),dA=U.object({name:U.string(),organization:U.string().optional(),description:U.string().optional(),avatar:U.string().optional(),website:U.string().optional(),email:U.string().optional(),socialLinks:U.array(U.object({platform:U.enum(["github","instagram","linkedin","email","website"]),url:U.string(),label:U.string().optional()})).optional()});function L0(f){return w`count(${f||w.raw("*")})`.mapWith(Number)}function sA(f){return F0(iA(f))}function iA(f,A=new Set){if(f===null)return"null";if(typeof f==="string"||typeof f==="boolean")return JSON.stringify(f);if(typeof f==="number"){if(!Number.isFinite(f))throw Error("Projection inputs cannot contain non-finite numbers");if(Number.isInteger(f)&&!Number.isSafeInteger(f))throw Error("Projection inputs cannot contain unsafe integers");return JSON.stringify(f)}if(typeof f!=="object")throw Error(`Projection inputs cannot contain ${typeof f} values`);if(A.has(f))throw Error("Projection inputs cannot contain circular values");let $=new Set(A).add(f);if(Array.isArray(f))return`[${f.map((V)=>iA(V,$)).join(",")}]`;let Z=Object.getPrototypeOf(f);if(Z!==Object.prototype&&Z!==null)throw Error("Projection inputs must contain only plain JSON objects");return`{${Object.entries(f).filter(([,V])=>V!==void 0).sort(([V],[H])=>V.localeCompare(H)).map(([V,H])=>`${JSON.stringify(V)}:${iA(H,$)}`).join(",")}}`}function aA(f){if(f!==null&&typeof f==="object"){for(let A of Object.values(f))aA(A);Object.freeze(f)}return f}var pU=U.strictObject({id:U.string().trim().min(1),version:U.string().trim().min(1),sources:U.array(U.strictObject({kind:U.literal("entity"),types:U.array(U.string().trim().min(1)).min(1),excludeTypes:U.array(U.string().trim().min(1)).optional()})),targetType:U.string().trim().min(1)});function lU(f){let A=pU.parse({id:f.id,version:f.version,sources:f.sources,targetType:f.targetType});if(typeof f.selectInput!=="function")throw Error(`Projection rule "${A.id}" must select input`);if(typeof f.derive!=="function")throw Error(`Projection rule "${A.id}" must derive output`);let $=A.sources.map((Z)=>{let V=Object.freeze([...Z.types]),H=Z.excludeTypes?Object.freeze([...Z.excludeTypes]):void 0,M={kind:"entity",types:V,...H?{excludeTypes:H}:{}};return Object.freeze(M)});return Object.freeze({id:A.id,version:A.version,sources:Object.freeze($),targetType:A.targetType,inputSchema:f.inputSchema,selectInput:async(Z,V,H)=>{let M=await f.selectInput(Z,V,H),X=jf.parse(M);return aA(f.inputSchema.parse(X))},fingerprint:sA,derive:async(Z,V,H)=>{let M=f.inputSchema.parse(Z),X=U.array(bf).parse(await f.derive(M,V,H));for(let Y of X){let F=Y.operation==="upsert"?Y.entity.entityType:Y.entityType;if(F!==A.targetType)throw Error(`Projection rule "${A.id}" cannot write entity type "${F}"`)}return aA(X)}})}var C0={digest:"conversation:digest"};var J=t("conversations",{id:k("id").primaryKey(),sessionId:k("session_id").notNull(),interfaceType:k("interface_type").notNull(),channelId:k("channel_id").notNull(),personId:k("person_id"),started:k("started").notNull(),lastActive:k("last_active").notNull(),metadata:k("metadata"),created:k("created").notNull(),updated:k("updated").notNull()},(f)=>({sessionIdx:b("idx_conversations_session").on(f.sessionId),channelIdx:b("idx_conversations_channel").on(f.channelId),personIdx:b("idx_conversations_person").on(f.personId),interfaceSessionIdx:b("idx_conversations_interface_session").on(f.interfaceType,f.sessionId),interfaceChannelIdx:b("idx_conversations_interface_channel").on(f.interfaceType,f.channelId)})),h=t("messages",{id:k("id").primaryKey(),conversationId:k("conversation_id").notNull().references(()=>J.id,{onDelete:"cascade"}),role:k("role").notNull(),content:k("content").notNull(),timestamp:k("timestamp").notNull(),metadata:k("metadata")},(f)=>({conversationIdx:b("idx_messages_conversation").on(f.conversationId),timestampIdx:b("idx_messages_timestamp").on(f.timestamp)})),e=t("summary_tracking",{conversationId:k("conversation_id").primaryKey().references(()=>J.id,{onDelete:"cascade"}),lastSummarizedAt:k("last_summarized_at"),lastMessageId:k("last_message_id"),messagesSinceSummary:j("messages_since_summary").default(0),updated:k("updated").notNull()});function N0(f){return gf({url:f.url,schema:{conversations:J,messages:h,summaryTracking:e},authToken:f.authToken,authTokenEnv:"CONVERSATION_DATABASE_AUTH_TOKEN"})}var nU=U.preprocess((f)=>{if(typeof f!=="string")return f;try{return JSON.parse(f)}catch{return}},U.record(U.string(),U.unknown())).catch({});function ff(f){return nU.parse(f)}var If="conversation:messageAdded",rA="conversation:started",Pf=U.object({identity:Af,interfaceType:U.string(),role:Lf,displayName:U.string().optional(),username:U.string().optional(),isBot:U.boolean().optional()}),dU=U.preprocess(iU,Pf);function iU(f){if(!uf(f)||"identity"in f)return f;let{actorId:A,interfaceType:$,role:Z}=f;if(typeof A!=="string"||typeof $!=="string"||Z!=="user"&&Z!=="assistant")return f;let{userId:V,canonicalId:H}=f;return{identity:G0({actorId:A,interfaceType:$,role:Z,...typeof V==="string"?{userId:V}:{},...typeof H==="string"?{canonicalId:H}:{}}),interfaceType:$,role:Z,...typeof f.displayName==="string"?{displayName:f.displayName}:{},...typeof f.username==="string"?{username:f.username}:{},...typeof f.isBot==="boolean"?{isBot:f.isBot}:{}}}var Wf=U.object({messageId:U.string().optional(),channelId:U.string().optional(),channelName:U.string().optional(),threadId:U.string().optional(),metadata:U.record(U.string(),U.unknown()).optional()}),R0=U.looseObject({actor:dU.optional(),source:Wf.optional()});function K0(f){if(typeof f==="string")try{let A=JSON.parse(f);return uf(A)?A:null}catch{return null}return uf(f)?f:null}function sU(f){if(f.role!=="assistant")return!1;if(f.content.trim().length===0)return!1;let A=K0(f.metadata),$=A?.entityMemoryRefs;if(Array.isArray($)&&$.length>0)return!1;let Z=A?.cards;if(!Array.isArray(Z))return!0;return!Z.some((V)=>{if(!uf(V))return!1;if(V.kind==="tool-approval")return!0;return V.kind==="actions"&&V.id==="actions:upload-intent"})}function uf(f){return typeof f==="object"&&f!==null&&!Array.isArray(f)}var aU=U.object({id:U.string(),conversationId:U.string(),role:U.string(),content:U.string(),timestamp:U.string(),metadata:U.string().nullable()}),P0=U.object({conversationId:U.string(),messageCount:U.number(),messages:U.array(aU),windowStart:U.number(),windowEnd:U.number(),windowSize:U.number(),timestamp:U.string()});class cf{db;logger;messageBus;config;dbClient=null;dbUrl=null;pragmaInitialization=null;constructor(f,A,$,Z={}){this.db=f,this.logger=A,this.messageBus=$,this.config={digestTriggerInterval:5,digestWindowSize:10,...Z}}initialize(){return this.pragmaInitialization??=this.applyPragmas(),this.pragmaInitialization}async applyPragmas(){let f=this.dbClient,A=this.dbUrl;if(!f||A===null)return;try{await pf(f,A)}catch($){this.logger.warn("Failed to enable conversation database pragmas (non-fatal)",$)}}getDatabaseClient(){if(!this.dbClient)throw Error("ConversationService does not own a database client");return this.dbClient}close(){this.dbClient?.close()}static createFresh(f,A,$,Z){return new cf(f,A,$,Z)}static createFreshFromConfig(f,A,$,Z){let{db:V,client:H,url:M}=N0($),X=new cf(V,f,A,Z);return X.dbClient=H,X.dbUrl=M,X}async startConversation(f){let{sessionId:A,interfaceType:$,channelId:Z,personId:V,metadata:H}=f,M=new Date().toISOString();if(await this.getConversation(A))return await this.db.update(J).set({lastActive:M,updated:M}).where(D(J.id,A)),this.logger.debug("Resumed existing conversation",{conversationId:A,interfaceType:$}),A;let Y={id:A,sessionId:A,interfaceType:$,channelId:Z,personId:V??null,started:M,lastActive:M,created:M,updated:M,metadata:JSON.stringify(H)};await this.db.insert(J).values(Y);let F={conversationId:A,messagesSinceSummary:0,updated:M};return await this.db.insert(e).values(F),this.logger.debug("Started new conversation",{conversationId:A,sessionId:A,interfaceType:$}),await this.messageBus.send({type:rA,payload:{conversationId:A,sessionId:A,interfaceType:$,timestamp:M},sender:"conversation-service",broadcast:!0}),A}async addMessage(f){let{conversationId:A,role:$,content:Z,metadata:V}=f,H=new Date().toISOString(),M=g(12),X={id:M,conversationId:A,role:$,content:Z,timestamp:H,metadata:V?JSON.stringify(V):null};await this.db.insert(h).values(X),await this.db.update(J).set({lastActive:H,updated:H}).where(D(J.id,A)),await this.db.update(e).set({messagesSinceSummary:w`${e.messagesSinceSummary} + 1`,lastMessageId:M,updated:H}).where(D(e.conversationId,A)),this.logger.debug("Added message to conversation",{conversationId:A,role:$,messageId:M}),await this.messageBus.send({type:If,payload:{conversationId:A,messageId:M,role:$,content:Z,metadata:V,timestamp:H},sender:"conversation-service",broadcast:!0}),await this.checkAndBroadcastDigest(A,H)}async getMessages(f,A={}){let{limit:$=20,range:Z}=A;if(Z){let V=Z.start-1,H=Z.end-Z.start+1;return await this.db.select().from(h).where(D(h.conversationId,f)).orderBy($f(h.timestamp)).limit(H).offset(V)}else return(await this.db.select().from(h).where(D(h.conversationId,f)).orderBy(i(h.timestamp)).limit($)).reverse()}async getConversation(f){return(await this.db.select().from(J).where(D(J.id,f)).limit(1))[0]??null}async listConversations(f={}){let{limit:A=100,updatedAfter:$,interfaceType:Z,sessionId:V,channelId:H,personId:M}=f,X=[$?W0(J.updated,$):void 0,Z?D(J.interfaceType,Z):void 0,V?D(J.sessionId,V):void 0,H?D(J.channelId,H):void 0,M?D(J.personId,M):void 0].filter((F)=>F!==void 0),Y=this.db.select().from(J).orderBy(i(J.lastActive)).limit(A);if(X.length===0)return Y;return Y.where(m(...X))}async searchConversations(f,A){let $=`%${f.toLowerCase()}%`;return(await this.db.selectDistinct({conversation:J}).from(J).leftJoin(h,D(h.conversationId,J.id)).where(A?w`lower(${h.content}) LIKE ${$} AND ${J.sessionId} = ${A}`:w`lower(${h.content}) LIKE ${$}`).orderBy(i(J.lastActive))).map((V)=>V.conversation)}async countMessages(f){let[A]=await this.db.select({count:L0()}).from(h).where(D(h.conversationId,f));return Number(A?.count??0)}async updateConversationMetadata(f){let A=await this.getConversation(f.conversationId);if(!A)return!1;let $=new Date().toISOString(),Z={...ff(A.metadata),...f.metadata};return await this.db.update(J).set({metadata:JSON.stringify(Z),updated:$}).where(D(J.id,f.conversationId)),this.logger.debug("Updated conversation metadata",{conversationId:f.conversationId}),!0}async deleteConversation(f){if(!await this.getConversation(f))return!1;return await this.db.delete(J).where(D(J.id,f)),this.logger.debug("Deleted conversation",{conversationId:f}),!0}async checkAndBroadcastDigest(f,A){let $=await this.countMessages(f),Z=this.config.digestTriggerInterval??10;if($>0&&$%Z===0)await this.broadcastDigest(f,$,A)}async broadcastDigest(f,A,$){let Z=this.config.digestWindowSize??20,V=Math.max(1,A-Z+1),H=A,M=await this.getMessages(f,{range:{start:V,end:H}}),X={conversationId:f,messageCount:A,messages:M,windowStart:V,windowEnd:H,windowSize:M.length,timestamp:$};await this.messageBus.send({type:C0.digest,payload:X,sender:"conversation-service",broadcast:!0}),this.logger.debug("Broadcast conversation digest",{conversationId:f,messageCount:A,windowStart:V,windowEnd:H,windowSize:M.length})}}var oA=U.object({kind:U.string().min(1),id:U.string().min(1)}),D0=U.object({kind:U.literal("text"),filename:U.string().min(1),mediaType:U.string().min(1),content:U.string(),sizeBytes:U.number().nonnegative().optional(),source:oA.optional()}),Y1=U.custom((f)=>f instanceof Uint8Array),L1=U.object({kind:U.literal("file"),filename:U.string().min(1),mediaType:U.string().min(1),data:Y1,sizeBytes:U.number().nonnegative().optional(),source:oA.optional()}),_0=U.discriminatedUnion("kind",[D0,L1]),F1=U.object({userPermissionLevel:U.enum(["admin","trusted","public"]).optional(),isAnchor:U.boolean().optional(),interfaceType:U.string().optional(),channelId:U.string().optional(),channelName:U.string().optional(),actor:Pf.optional(),source:Wf.optional(),attachments:U.array(_0).optional()});var C1=U.object({status:U.enum(["healthy","warning","error","unknown"]),message:U.string().optional(),lastCheck:U.date().optional(),details:U.record(U.string(),U.unknown()).optional()}),B0=U.object({name:U.string(),pluginId:U.string(),status:U.string(),health:C1.optional()});var OH=U.object({id:U.string(),type:U.string(),version:U.string(),status:U.string()}),wH=U.object({name:U.string(),description:U.string()}),k0=U.enum(["admin","trusted","public"]),sf=U.object({label:U.string(),url:U.string(),pluginId:U.string(),priority:U.number().default(100),visibility:k0.default("public")}),O0=U.enum(["human","agent","admin","protocol"]),w0=U.enum(["available","coming-soon","disabled"]),af=U.object({id:U.string(),label:U.string(),description:U.string().optional(),href:U.string(),kind:O0,pluginId:U.string(),priority:U.number().default(100),visibility:k0.default("public"),status:w0.default("available")}),tA=U.object({entityType:U.string(),count:U.number()}),R1=U.object({model:U.string(),version:U.string(),uptime:U.number(),entities:U.number(),entityCounts:U.array(tA),embeddings:U.number(),ai:U.object({model:U.string(),embeddingModel:U.string()}),daemons:U.array(B0),endpoints:U.array(sf),interactions:U.array(af)});var K1=U.object({id:U.string(),version:U.string(),type:U.enum(["core","entity","service","interface"]),description:U.string().optional(),dependencies:U.array(U.string()).optional(),packageName:U.string()});var P1=U.object({status:U.enum(["healthy","warning","error","unknown"]),message:U.string().optional(),lastCheck:U.string().optional(),details:U.record(U.string(),U.unknown()).optional()}),W1=U.object({name:U.string(),pluginId:U.string(),status:U.string(),health:P1.optional()}),D1=U.object({model:U.string(),version:U.string(),uptime:U.number(),entities:U.number(),entityCounts:U.array(tA),embeddings:U.number(),ai:U.object({model:U.string(),embeddingModel:U.string()}),daemons:U.array(W1),endpoints:U.array(sf),interactions:U.array(af)});var x0=U.object({name:U.string().min(1),status:U.enum(["healthy","degraded","unhealthy"]),message:U.string().optional(),details:U.record(U.string(),U.unknown()).optional()}),J0=U.object({totals:U.object({pending:U.number().int().nonnegative(),processing:U.number().int().nonnegative(),completed:U.number().int().nonnegative(),failed:U.number().int().nonnegative()}),byType:U.array(U.object({type:U.string().min(1),status:U.enum(["pending","processing","completed","failed"]),count:U.number().int().nonnegative()})),oldestPendingAgeMs:U.number().nonnegative().nullable(),oldestProcessingAgeMs:U.number().nonnegative().nullable(),staleLeaseCount:U.number().int().nonnegative(),workerSessions:U.object({total:U.number().int().nonnegative(),active:U.number().int().nonnegative(),stale:U.number().int().nonnegative(),latestHeartbeatAgeMs:U.number().nonnegative().nullable()})}),Q0=U.object({memory:U.object({rssBytes:U.number().int().nonnegative(),heapUsedBytes:U.number().int().nonnegative(),heapTotalBytes:U.number().int().nonnegative()}),fileDescriptors:U.number().int().nonnegative().nullable(),processes:U.object({total:U.number().int().nonnegative().nullable(),zombies:U.number().int().nonnegative().nullable()}),queue:J0.nullable(),projection:U.object({initialized:U.boolean(),trackedRoots:U.number().int().nonnegative(),openCircuits:U.array(U.object({projectionId:U.string().min(1),reason:U.string().min(1),openedAt:U.number().int().nonnegative(),expiresAt:U.number().int().nonnegative()}))}),worker:U.object({total:U.number().int().nonnegative(),active:U.number().int().nonnegative(),stale:U.number().int().nonnegative(),latestHeartbeatAgeMs:U.number().nonnegative().nullable()})}),_1=U.object({status:U.enum(["ready","not_ready"]),operationalStatus:U.enum(["operational","degraded"]),checkedAt:U.iso.datetime(),checks:U.array(x0),resources:Q0});class s{callback;heartbeatInterval;constructor(f){this.callback=f}static from(f){if(!f)return;return new s(f)}createSub(f){let{scale:A}=f??{};if(A){let{start:$,end:Z}=A,V=Z-$;return new s(async(H)=>{let M=$+H.progress/(H.total??100)*V;await this.callback({...H,progress:M,total:100})})}return new s(this.callback)}async report(f){await this.callback(f)}startHeartbeat(f,A=5000){this.stopHeartbeat(),this.heartbeatInterval=setInterval(()=>{this.report({message:f,progress:0}).catch(()=>{})},A)}stopHeartbeat(){if(this.heartbeatInterval)clearInterval(this.heartbeatInterval),this.heartbeatInterval=void 0}toCallback(){return this.callback}}var B1=U.object({enabled:U.boolean().describe("Whether the plugin is enabled"),debug:U.boolean().describe("Enable debug logging for this plugin")});class rf extends Error{pluginId;issues;constructor(f,A){super(`Invalid plugin config for ${f}`);this.name="PluginConfigValidationError",this.pluginId=f,this.issues=A}}var k1=U.object({toolName:U.string(),args:U.unknown(),progressToken:U.union([U.string(),U.number()]).optional(),hasProgress:U.boolean().optional(),interfaceType:U.string(),actor:Af,displayName:U.string().optional(),conversationId:U.string().optional(),channelId:U.string().optional(),channelName:U.string().optional(),runId:U.string().optional(),toolCallId:U.string().optional(),userPermissionLevel:U.enum(["admin","trusted","public"]).optional(),isAnchor:U.boolean().optional(),signal:U.custom((f)=>f instanceof AbortSignal).optional()}),O1=U.object({resourceUri:U.string()});class Zf{id;version;description;packageName;config;context;get logger(){return this.context?.logger??of.createFresh({context:this.id})}constructor(f,A,$,Z){this.id=f,this.packageName=A.name,this.version=A.version,this.description=A.description??`${A.name} plugin`;let V=Z.safeParse($);if(!V.success)throw new rf(f,V.error.issues.map((H)=>({path:H.path.map(String).join("."),code:H.code,message:H.message})));this.config=V.data}setupMessageHandlers(f){f.messaging.subscribe(Df.toolExecute(this.id),async(A)=>{try{let $=k1.safeParse(A.payload);if(!$.success)return{success:!1,error:"Invalid tool execution request format"};let{toolName:Z,args:V,progressToken:H,hasProgress:M,interfaceType:X,actor:Y,displayName:F,conversationId:N,channelId:C,channelName:W,runId:_,toolCallId:q,userPermissionLevel:E,isAnchor:I,signal:r}=$.data,c=(await this.getTools()).find((K)=>K.name===Z);if(!c)return{success:!1,error:`Tool not found: ${Z}`};let R={interfaceType:X,actor:Y,...F&&{displayName:F},...N&&{conversationId:N},...C&&{channelId:C},...W&&{channelName:W},..._&&{runId:_},...q&&{toolCallId:q},...E&&{userPermissionLevel:E},...I!==void 0&&{isAnchor:I},...r&&{signal:r},...M&&H!==void 0&&{progressToken:H,sendProgress:async(K)=>{await f.messaging.send({type:Df.progress(this.id),payload:{progressToken:H,notification:K}})}}};return{success:!0,data:await c.handler(V,R)}}catch($){return this.logger.error("Tool execution error",$),{success:!1,error:S($)}}}),f.messaging.subscribe(Df.resourceGet(this.id),async(A)=>{try{let $=O1.safeParse(A.payload);if(!$.success)return{success:!1,error:"Invalid resource get request format"};let{resourceUri:Z}=$.data,H=(await this.getResources()).find((X)=>X.uri===Z);if(!H)return{success:!1,error:`Resource not found: ${Z}`};return{success:!0,data:await H.handler()}}catch($){return this.logger.error("Resource fetch error",$),{success:!1,error:S($)}}})}async onRegister(f){}async onRegistrationComplete(f){}async finalizeRegistration(){await this.onRegistrationComplete(this.getContext())}async onReady(f){}async ready(){await this.onReady(this.getContext())}async getCapabilities(){let f=await this.getInstructions();return{tools:await this.getTools(),resources:await this.getResources(),...f&&{instructions:f}}}async getTools(){return[]}async getResources(){return[]}async getInstructions(){return}async shutdown(){await this.onShutdown()}async onShutdown(){}getContext(){if(!this.context)throw Error(`Plugin ${this.id}: Plugin not registered yet`);return this.context}determineUserPermissionLevel(f){return"public"}createProgressBridge(f){if(!f)return;let A=this.context;if(!A)return;let $=this.id;return s.from(async(Z)=>{await A.messaging.send({type:Df.progress($),payload:{progressToken:f,notification:{progress:Z.progress,total:Z.total,message:Z.message}}})})}}var eA=U.enum(["file_operations","content_operations","data_processing","batch_processing"]),w1=U.object({pluginId:U.string().optional(),progressToken:U.union([U.string(),U.number()]).optional(),operationType:eA,operationTarget:U.string().optional(),interfaceType:U.string().optional(),conversationId:U.string().optional(),channelId:U.string().optional(),requestedByActor:Af.optional(),requestedByUserId:U.string().optional(),requestedByInterface:U.string().optional(),silent:U.boolean().optional(),provenance:Uf.optional()}),Vf=U.object({pluginId:U.string().optional(),progressToken:U.union([U.string(),U.number()]).optional(),operationType:eA,operationTarget:U.string().optional(),interfaceType:U.string().optional(),conversationId:U.string().optional(),channelId:U.string().optional(),requestedByActor:Af.optional(),requestedByUserId:U.string().optional(),requestedByInterface:U.string().optional(),silent:U.boolean().optional(),provenance:Uf.optional(),rootJobId:U.string()}),nH=U.enum(["none","skip","replace","coalesce"]);var f$=U.enum(["pending","processing","completed","failed"]),q0=U.enum(["completed","failed"]),P={PENDING:"pending",PROCESSING:"processing",COMPLETED:"completed",FAILED:"failed"},x1=U.object({id:U.string(),type:U.string(),status:f$,data:U.unknown(),result:U.unknown().optional(),lastError:U.string().optional().nullable(),attempts:U.number(),maxRetries:U.number(),priority:U.number(),createdAt:U.date(),updatedAt:U.date(),processedAt:U.date().optional().nullable(),completedAt:U.date().optional().nullable(),failedAt:U.date().optional().nullable()}),J1=U.object({jobId:U.string(),type:U.string(),status:q0,result:U.unknown().optional(),error:U.string().optional()}),A$=U.object({success:U.literal(!1),error:U.string().optional()}),tf=U.object({id:U.string(),type:U.enum(["job","batch"]),status:f$,message:U.string().optional(),progress:U.object({current:U.number(),total:U.number(),percentage:U.number()}).optional(),aggregationKey:U.string().optional(),batchDetails:U.object({totalOperations:U.number(),completedOperations:U.number(),failedOperations:U.number(),currentOperation:U.string().optional(),errors:U.array(U.string()).optional()}).optional(),jobDetails:U.object({jobType:U.string(),priority:U.number(),retryCount:U.number()}).optional(),metadata:Vf});var L=t("job_queue",{id:k("id").primaryKey().$defaultFn(()=>g()),type:k("type").notNull(),data:k("data").notNull(),result:k("result",{mode:"json"}),progress:k("progress",{mode:"json"}).$type(),source:k("source"),metadata:k("metadata",{mode:"json"}).$type().notNull(),status:k("status",{enum:["pending","processing","completed","failed"]}).notNull().default("pending"),priority:j("priority").notNull().default(0),retryCount:j("retryCount").notNull().default(0),maxRetries:j("maxRetries").notNull().default(3),lastError:k("lastError"),createdAt:j("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:j("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:j("startedAt"),completedAt:j("completedAt"),attemptId:k("attemptId"),workerSlotId:k("workerSlotId"),workerSessionId:k("workerSessionId"),leaseExpiresAt:j("leaseExpiresAt"),attemptHeartbeatAt:j("attemptHeartbeatAt"),runtimeUpdatedAt:j("runtimeUpdatedAt")},(f)=>({queueReadyIdx:b("idx_job_queue_ready").on(f.status,f.priority,f.scheduledFor),jobTypeIdx:b("idx_job_queue_type").on(f.type,f.status),runtimeUpdatesIdx:b("idx_job_queue_runtime_updates").on(f.runtimeUpdatedAt,f.id),jobSourceIdx:b("idx_job_queue_source").on(f.source)})),O=t("job_worker_sessions",{slotId:k("slotId").primaryKey(),sessionId:k("sessionId").notNull().unique(),startedAt:j("startedAt").notNull(),heartbeatAt:j("heartbeatAt").notNull()},(f)=>({heartbeatIdx:b("idx_job_worker_sessions_heartbeat").on(f.heartbeatAt)}));function T0(f){return gf({url:f.url,schema:{jobQueue:L,jobWorkerSessions:O},authToken:f.authToken,authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN"})}class $${declarations=new Map;handlers=new Map;validators=new Map;logger;mode;finalizedRegistrations;constructor(f,A){this.logger=f.child("HandlerRegistry"),this.mode=A}registerHandler(f,A,$){if(this.finalizedRegistrations)throw Error("Job handler registrations are finalized");if(this.declarations.has(f))throw Error(`Job handler is already registered for type: ${f}`);if(this.declarations.set(f,{handler:A,pluginId:$}),this.validators.set(f,A),this.mode!=="validation-only")this.handlers.set(f,A);this.logger.debug("Registered job execution declaration",{type:f,pluginId:$,mode:this.mode})}unregisterHandler(f){this.declarations.delete(f),this.handlers.delete(f),this.validators.delete(f),this.logger.debug("Unregistered job handler",{type:f})}unregisterPluginHandlers(f){let A=[...this.declarations.entries()].filter(([,$])=>$.pluginId===f).map(([$])=>$);for(let $ of A)this.declarations.delete($),this.handlers.delete($),this.validators.delete($);if(A.length>0)this.logger.debug("Unregistered plugin handlers",{pluginId:f,count:A.length,types:A})}finalizeRegistrations(){return this.finalizedRegistrations??=Object.freeze([...this.declarations.entries()].sort(([f],[A])=>f.localeCompare(A)).map(([f,A])=>Object.freeze({type:f,pluginId:A.pluginId}))),this.finalizedRegistrations}getExecutionRegistrations(){if(!this.finalizedRegistrations)throw Error("Job handler registrations are not finalized");return this.finalizedRegistrations}getRegisteredTypes(){return[...this.handlers.keys()]}getHandler(f){return this.handlers.get(f)}getValidator(f){return this.validators.get(f)}}var Q1=U.object({id:U.string(),type:U.string(),data:U.string(),status:U.enum(["pending","processing","completed","failed"]),source:U.string().nullable(),priority:U.number(),retryCount:U.number(),maxRetries:U.number(),lastError:U.string().nullable(),createdAt:U.number(),scheduledFor:U.number(),startedAt:U.number().nullable(),completedAt:U.number().nullable(),attemptId:U.string().nullable(),workerSlotId:U.string().nullable(),workerSessionId:U.string().nullable(),leaseExpiresAt:U.number().nullable(),attemptHeartbeatAt:U.number().nullable(),runtimeUpdatedAt:U.number().nullable(),metadata:Vf,progress:U.custom((f)=>typeof f==="object"&&f!==null&&("progress"in f)&&typeof f.progress==="number").nullable(),result:U.unknown().nullable().optional()}),_f=15000;class V${db;logger;constructor(f,A){this.db=f,this.logger=A.child("JobQueueRepository")}async insert(f){await this.db.insert(L).values(f)}async startWorkerSession(f,A,$=Date.now()){await this.db.insert(O).values({slotId:f,sessionId:A,startedAt:$,heartbeatAt:$}).onConflictDoUpdate({target:O.slotId,set:{sessionId:A,startedAt:$,heartbeatAt:$}})}async heartbeatWorkerSession(f,A,$=Date.now()){return(await this.db.update(O).set({heartbeatAt:$}).where(m(D(O.slotId,f),D(O.sessionId,A))).returning({slotId:O.slotId})).length===1}async endWorkerSession(f,A){return(await this.db.delete(O).where(m(D(O.slotId,f),D(O.sessionId,A))).returning({slotId:O.slotId})).length===1}async markTerminallyFailed(f,A){let $=Date.now();await this.db.update(L).set({status:P.FAILED,lastError:A,completedAt:$,runtimeUpdatedAt:this.nextRuntimeUpdatedAt($)}).where(m(D(L.id,f),D(L.status,P.PENDING)))}async setScheduledFor(f,A){await this.db.update(L).set({scheduledFor:A}).where(D(L.id,f))}async complete(f,A,$){let Z=Date.now(),H=(await this.db.update(L).set({status:P.COMPLETED,result:A,lastError:null,completedAt:Z,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(Z)}).where(this.attemptWriteGuard(f,$)).returning({id:L.id})).length===1;if(H)this.logger.debug("Job completed",{jobId:f,hasResult:A!==void 0});return H}async update(f,A,$){let V=(await this.db.update(L).set({data:JSON.stringify(A)}).where(this.attemptWriteGuard(f,$)).returning({id:L.id})).length===1;if(V)this.logger.debug("Job data updated",{jobId:f});return V}async recordAttemptProgress(f,A,$,Z=Date.now()){return(await this.db.update(L).set({attemptHeartbeatAt:Z,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(Z),progress:$}).where(this.attemptWriteGuard(f,A)).returning({id:L.id})).length===1}async renewAttemptLease(f,A,$,Z){return(await this.db.update(L).set({attemptHeartbeatAt:$,leaseExpiresAt:$+Z}).where(this.attemptWriteGuard(f,A)).returning({id:L.id})).length===1}async fail(f,A,$,Z=Date.now()){let H=(await this.db.select({retryCount:L.retryCount,maxRetries:L.maxRetries,type:L.type,scheduledFor:L.scheduledFor,startedAt:L.startedAt,runtimeUpdatedAt:L.runtimeUpdatedAt}).from(L).where(this.attemptWriteGuard(f,$)).limit(1))[0];if(!H)return!1;let M=H.retryCount<H.maxRetries,X=M?H.retryCount+1:H.retryCount,Y=Math.min(1000*2**H.retryCount,60000),F=M?Z+Y:H.scheduledFor;if((await this.db.update(L).set({status:M?P.PENDING:P.FAILED,retryCount:X,lastError:A.message,scheduledFor:F,completedAt:M?null:Z,runtimeUpdatedAt:M?H.runtimeUpdatedAt:this.nextRuntimeUpdatedAt(Z),startedAt:M?null:H.startedAt,attemptId:null,workerSlotId:null,workerSessionId:null,leaseExpiresAt:null,attemptHeartbeatAt:null}).where(m(this.attemptWriteGuard(f,$),D(L.retryCount,H.retryCount))).returning({id:L.id})).length!==1)return!1;if(M)this.logger.debug("Job scheduled for retry",{jobId:f,retryCount:X,backoffMs:Y,scheduledFor:new Date(F).toISOString()});else this.logger.error("Job failed after max retries",{jobId:f,type:H.type,retryCount:H.retryCount,error:A.message});return!0}async getStatus(f){return(await this.db.select().from(L).where(D(L.id,f)).limit(1))[0]??null}async getStatusByEntityId(f){return(await this.db.select().from(L).where(w`json_extract(${L.data}, '$.id') = ${f}`).orderBy(i(L.createdAt)).limit(1))[0]??null}async getStats(){let f=await this.db.select({status:L.status,count:w`count(*)`}).from(L).groupBy(L.status),A={pending:0,processing:0,failed:0,completed:0,total:0};for(let $ of f){let Z=Number($.count);A[$.status]=Z,A.total+=Z}return A}async getDiagnostics(f=Date.now()){let A=f-_f,[$,Z,V]=await Promise.all([this.db.select({type:L.type,status:L.status,count:w`count(*)`}).from(L).groupBy(L.type,L.status),this.db.select({oldestPendingAt:w`min(case when ${L.status} = ${P.PENDING} then ${L.createdAt} end)`,oldestProcessingAt:w`min(case when ${L.status} = ${P.PROCESSING} then ${L.startedAt} end)`,staleLeaseCount:w`coalesce(sum(case when ${L.status} = ${P.PROCESSING} and ${L.leaseExpiresAt} is not null and ${L.leaseExpiresAt} <= ${f} then 1 else 0 end), 0)`}).from(L),this.db.select({total:w`count(*)`,active:w`coalesce(sum(case when ${O.heartbeatAt} > ${A} then 1 else 0 end), 0)`,stale:w`coalesce(sum(case when ${O.heartbeatAt} <= ${A} then 1 else 0 end), 0)`,latestHeartbeatAt:w`max(${O.heartbeatAt})`}).from(O)]),H={pending:0,processing:0,completed:0,failed:0},M=$.map((N)=>{let C=Number(N.count);return H[N.status]+=C,{type:N.type,status:N.status,count:C}}),X=Z[0],Y=V[0],F=(N)=>N===null||N===void 0?null:Math.max(0,f-Number(N));return{totals:H,byType:M,oldestPendingAgeMs:F(X?.oldestPendingAt),oldestProcessingAgeMs:F(X?.oldestProcessingAt),staleLeaseCount:Number(X?.staleLeaseCount??0),workerSessions:{total:Number(Y?.total??0),active:Number(Y?.active??0),stale:Number(Y?.stale??0),latestHeartbeatAgeMs:F(Y?.latestHeartbeatAt)}}}async getRuntimeUpdates(f,A){return(await this.db.select().from(L).where(w`(${L.runtimeUpdatedAt}, ${L.id}) > (${f.updatedAt}, ${f.jobId})`).orderBy($f(L.runtimeUpdatedAt),$f(L.id)).limit(A)).map((Z)=>({job:Z,cursor:{updatedAt:Z.runtimeUpdatedAt??0,jobId:Z.id}}))}async cleanup(f){let A=Date.now()-f;return(await this.db.delete(L).where(m(Ff(D(L.status,P.COMPLETED),D(L.status,P.FAILED)),Bf(L.completedAt,A)))).rowsAffected}async getActiveJobs(f){let A=Ff(D(L.status,P.PENDING),D(L.status,P.PROCESSING)),$=f&&f.length>0?m(A,kf(L.type,f)):A;return this.db.select().from(L).where($).orderBy(i(L.createdAt))}async getFailedJobs(f){let A=D(L.status,P.FAILED),$=f&&f.length>0?m(A,kf(L.type,f)):A;return this.db.select().from(L).where($).orderBy(i(L.createdAt))}async claimNextReady(f){let{now:A,attemptId:$,workerSlotId:Z,workerSessionId:V,leaseDurationMs:H,workerSessionTimeoutMs:M,executableTypes:X}=f,Y=A-M,F=this.db.select({slotId:O.slotId}).from(O).where(m(D(O.slotId,Z),D(O.sessionId,V))),N=this.db.select({slotId:O.slotId}).from(O).where(m(D(O.slotId,L.workerSlotId),D(O.sessionId,L.workerSessionId))),C=this.db.select({slotId:O.slotId}).from(O).where(m(D(O.slotId,L.workerSlotId),D(O.sessionId,L.workerSessionId),Bf(O.heartbeatAt,Y))),W=m(D(L.status,P.PROCESSING),Ff(Z$(L.attemptId),E0(N),m(Bf(L.leaseExpiresAt,A),U$(C)))),_=w`${L.status} = ${P.PROCESSING} AND ${L.retryCount} + 1 > ${L.maxRetries}`,q=this.db.select({id:L.id}).from(L).where(m(kf(L.type,X),Ff(m(D(L.status,P.PENDING),Bf(L.scheduledFor,A)),W))).orderBy($f(L.priority),$f(L.createdAt)).limit(1),I=(await this.db.update(L).set({status:w`CASE WHEN ${_} THEN ${P.FAILED} ELSE ${P.PROCESSING} END`,retryCount:w`CASE WHEN ${L.status} = ${P.PROCESSING} THEN ${L.retryCount} + 1 ELSE ${L.retryCount} END`,lastError:w`CASE WHEN ${L.status} = ${P.PROCESSING} THEN 'Attempt lease expired' ELSE ${L.lastError} END`,startedAt:w`CASE WHEN ${_} THEN ${L.startedAt} ELSE ${A} END`,completedAt:w`CASE WHEN ${_} THEN ${A} ELSE NULL END`,attemptId:w`CASE WHEN ${_} THEN ${L.attemptId} ELSE ${$} END`,workerSlotId:w`CASE WHEN ${_} THEN ${L.workerSlotId} ELSE ${Z} END`,workerSessionId:w`CASE WHEN ${_} THEN ${L.workerSessionId} ELSE ${V} END`,leaseExpiresAt:w`CASE WHEN ${_} THEN ${L.leaseExpiresAt} ELSE ${A+H} END`,attemptHeartbeatAt:w`CASE WHEN ${_} THEN ${L.attemptHeartbeatAt} ELSE ${A} END`,runtimeUpdatedAt:w`CASE WHEN ${_} THEN ${this.nextRuntimeUpdatedAt(A)} ELSE ${L.runtimeUpdatedAt} END`}).where(m(kf(L.id,q),U$(F))).returning())[0];if(I?.status!==P.PROCESSING)return null;return this.logger.debug("Job claimed",{jobId:I.id,attemptId:I.attemptId,workerSlotId:Z,workerSessionId:V}),I}nextRuntimeUpdatedAt(f){return w`max(${f}, coalesce((select max(${L.runtimeUpdatedAt}) from ${L}), 0) + 1)`}attemptWriteGuard(f,A){return A?m(D(L.id,f),D(L.status,P.PROCESSING),D(L.attemptId,A)):m(D(L.id,f),Z$(L.attemptId),Ff(D(L.status,P.PENDING),D(L.status,P.PROCESSING)))}}var q1=U.looseObject({deduplicationKey:U.string().optional()});class H${findDuplicate(f,A,$){if(!A||A==="none")return null;let Z=this.filterByDeduplicationKey(f,$);if(Z.length===0)return null;if(A==="skip"||A==="replace")return Z.find((V)=>V.status===P.PENDING)??null;return Z[0]??null}filterByDeduplicationKey(f,A){if(!A)return f;return f.filter(($)=>{let Z=q1.safeParse($.metadata);return Z.success&&Z.data.deduplicationKey===A})}}import{AsyncLocalStorage as T1}from"async_hooks";class Cf{storage=new T1;static createFresh(){return new Cf}constructor(){}current(){return this.storage.getStore()}run(f,A,$){if(A.length===0)throw Error("Operation ID must not be empty");let Z=Uf.parse(f),V=E1(Z);return this.storage.run(Object.freeze({provenance:V,operationId:A}),$)}}function E1(f){if(Object.freeze(f.projectionLineage),f.sourceEntity)Object.freeze(f.sourceEntity);return Object.freeze(f)}class M${client;logger;handlerRegistry;repository;deduplicator;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;databaseUrl;operationContext;projectionAdmission;directWorkerSlotId=`direct:${g()}`;directWorkerSessionId=g();directLeaseDurationMs;directSessionStart=null;close(){if(this.closeRequested=!0,!this.walInitialization||this.walInitializationSettled)this.closeClient()}static createFresh(f,A,$){return new M$(f,A??of.getInstance(),$)}constructor(f,A,$){let{db:Z,client:V,url:H}=T0(f);this.client=V,this.databaseUrl=H,this.logger=A.child("JobQueueService"),this.operationContext=$?.operationContext??Cf.createFresh(),this.projectionAdmission=$?.projectionAdmission,this.handlerRegistry=new $$(this.logger,$?.handlerRegistrationMode??"combined"),this.repository=new V$(Z,this.logger),this.directLeaseDurationMs=f.claimTimeoutMs??300000,this.deduplicator=new H$}initialize(){if(this.closeRequested)return Promise.resolve();return this.walInitialization??=this.initializeWALMode(),this.walInitialization}async initializeWALMode(){try{await pf(this.client,this.databaseUrl)}catch(f){this.logger.warn("Failed to enable WAL mode (non-fatal)",f)}finally{if(this.walInitializationSettled=!0,this.closeRequested)this.closeClient()}}closeClient(){if(this.clientClosed)return;this.clientClosed=!0,this.client.close()}registerHandler(f,A,$){this.handlerRegistry.registerHandler(f,A,$)}unregisterHandler(f){this.handlerRegistry.unregisterHandler(f)}unregisterPluginHandlers(f){this.handlerRegistry.unregisterPluginHandlers(f)}getRegisteredTypes(){return this.handlerRegistry.getRegisteredTypes()}getHandler(f){return this.handlerRegistry.getHandler(f)}getValidator(f){return this.handlerRegistry.getValidator(f)}finalizeHandlerRegistrations(){return this.handlerRegistry.finalizeRegistrations()}getExecutionRegistrations(){return this.handlerRegistry.getExecutionRegistrations()}async checkForDuplicate(f,A,$){let Z=await this.getActiveJobs([f]);return this.deduplicator.findDuplicate(Z,A,$)}async enqueue(f){let{type:A,data:$,options:Z}=f,V=await this.checkForDuplicate(A,Z?.deduplication,Z?.deduplicationKey);if(V){if(Z?.deduplication==="skip")return this.logger.debug("Skipping duplicate job (already pending)",{type:A,existingJobId:V.id}),V.id;if(Z?.deduplication==="replace")this.logger.debug("Replacing duplicate job",{type:A,oldJobId:V.id}),await this.repository.markTerminallyFailed(V.id,"Replaced by newer job");if(Z?.deduplication==="coalesce")return this.logger.debug("Coalescing with existing job",{type:A,existingJobId:V.id}),await this.repository.setScheduledFor(V.id,Date.now()),V.id}let H=this.handlerRegistry.getValidator(A);if(!H)throw Error(`No handler registered for job type: ${A}`);let M=H.validateAndParse($);if(M===null)throw Error(`Invalid job data for type: ${A}`);let X=Date.now(),Y=g(),F=Z?.rootJobId??this.operationContext.current()?.provenance.rootJobId??Y,N=this.createJobProvenance(Y,F,Z);await this.projectionAdmission?.assertJobAdmission(N);let{provenance:C,...W}=Z?.metadata??{operationType:"data_processing"},_={id:Y,type:A,data:JSON.stringify(M),status:P.PENDING,priority:Z?.priority??0,maxRetries:Z?.maxRetries??3,retryCount:0,source:Z?.source??null,metadata:{...W,...Z?.deduplicationKey&&{deduplicationKey:Z.deduplicationKey},rootJobId:F,provenance:N},createdAt:X,scheduledFor:Z?.delayMs?X+Z.delayMs:X,result:null,lastError:null,startedAt:null,completedAt:null};try{return await this.repository.insert(_),this.logger.debug("Job enqueued",{id:Y,type:A,priority:_.priority,rootJobId:_.metadata.rootJobId}),Y}catch(q){throw this.logger.error("Failed to enqueue job",{type:A,error:S(q)}),q}}createJobProvenance(f,A,$){let Z=this.operationContext.current(),V=$?.metadata.provenance??Z?.provenance,H=V?.rootJobId===A?V:void 0,M=Z?.provenance.rootJobId===A?Z.operationId:void 0,X=$?.projection,Y=X?[...H?.projectionLineage??[],X.id]:[...H?.projectionLineage??[]],F=X?.id??H?.projectionId;return Uf.parse({rootJobId:A,causationId:M??H?.causationId??f,...F?{projectionId:F}:{},projectionLineage:Y,...X?.sourceEntity?{sourceEntity:X.sourceEntity}:H?.sourceEntity?{sourceEntity:H.sourceEntity}:{},derivationDepth:Y.length})}async dequeue(f){let A=this.handlerRegistry.getRegisteredTypes();if(A.length===0)return null;let $=f??await this.getDirectClaimOptions(),Z=Date.now(),V=await this.repository.claimNextReady({...$,now:Z,attemptId:g(),executableTypes:A});if(!V)return null;return this.logger.debug("Job dequeued",{id:V.id,type:V.type,priority:V.priority,retryCount:V.retryCount,attemptId:V.attemptId,workerSlotId:V.workerSlotId,workerSessionId:V.workerSessionId}),V}async startWorkerSession(f,A){await this.repository.startWorkerSession(f,A)}heartbeatWorkerSession(f,A){return this.repository.heartbeatWorkerSession(f,A)}endWorkerSession(f,A){return this.repository.endWorkerSession(f,A)}renewAttemptLease(f,A,$){return this.repository.renewAttemptLease(f,A,Date.now(),$)}recordAttemptProgress(f,A,$){return this.repository.recordAttemptProgress(f,A,$)}complete(f,A,$){return this.repository.complete(f,A,$)}update(f,A,$){return this.repository.update(f,A,$)}fail(f,A,$){return this.repository.fail(f,A,$)}async getDirectClaimOptions(){return this.directSessionStart??=this.repository.startWorkerSession(this.directWorkerSlotId,this.directWorkerSessionId),await this.directSessionStart,{workerSlotId:this.directWorkerSlotId,workerSessionId:this.directWorkerSessionId,leaseDurationMs:this.directLeaseDurationMs,workerSessionTimeoutMs:this.directLeaseDurationMs}}async getStatus(f){return this.repository.getStatus(f)}async getStatusByEntityId(f){return this.repository.getStatusByEntityId(f)}async getStats(){return this.repository.getStats()}getDiagnostics(f){return this.repository.getDiagnostics(f)}getRuntimeUpdates(f,A=1000){return this.repository.getRuntimeUpdates(f,A)}async cleanup(f){let A=await this.repository.cleanup(f);if(A>0)this.logger.info("Cleaned up old jobs",{deletedCount:A,olderThanMs:f});return A}async getActiveJobs(f){return this.repository.getActiveJobs(f)}async getFailedJobs(f){return this.repository.getFailedJobs(f)}}class m0 extends Error{constructor(f,A){super(`Job ${f} exceeded its ${A}ms execution deadline`);this.name="JobDeadlineExceededError"}}class X${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;workerSessionId=null;workerHeartbeatTimer=null;workerHeartbeatInFlight=null;static createFresh(f,A,$,Z,V){return new X$(f,A,$,Z,V)}constructor(f,A,$,Z,V){if(this.logger=$.child("JobQueueWorker"),this.jobQueueService=f,this.progressMonitor=A,this.clock=V?.clock,this.operationContext=V?.operationContext??Cf.createFresh(),this.config={concurrency:Z?.concurrency??1,pollInterval:Z?.pollInterval??1000,maxJobs:Z?.maxJobs??0,autoStart:Z?.autoStart??!1,workerSlotId:Z?.workerSlotId??process.env.BRAIN_JOB_WORKER_SLOT_ID??"default",defaultExecutionTimeoutMs:Z?.defaultExecutionTimeoutMs??300000,cancellationGraceMs:Z?.cancellationGraceMs??5000,errorCallbackTimeoutMs:Z?.errorCallbackTimeoutMs??1e4,leaseDurationMs:Z?.leaseDurationMs??30000,attemptHeartbeatIntervalMs:Z?.attemptHeartbeatIntervalMs??1e4,workerHeartbeatIntervalMs:Z?.workerHeartbeatIntervalMs??5000,workerSessionTimeoutMs:Z?.workerSessionTimeoutMs??_f,onUnhealthy:Z?.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((H)=>{this.logger.error("Failed to auto-start JobQueueWorker",{error:H})})}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 f=g();await this.jobQueueService.startWorkerSession(this.config.workerSlotId,f),this.workerSessionId=f,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=G.runSync(v.make()),this.jobFibers=G.runSync(v.extend(Hf.make(),this.workerScope)),this.pollFiber=G.runFork(this.runPollingLoop())}stop(){return this.requestTransition("stop",!0)}async stopWorker(f){if(!this.isRunning){this.logger.warn("Worker is not running");return}if(this.logger.debug("Stopping JobQueueWorker"),this.shouldStop=!0,f.awaitInFlightPoll&&this.pollFiber){let $=this.pollFiber;await G.runPromise(ef.interrupt($)),this.pollFiber=null}if(f.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 G.runPromise(Hf.awaitEmpty(this.jobFibers));await this.closeWorkerScope(),await this.stopWorkerHeartbeat();let A=this.workerSessionId;if(this.workerSessionId=null,A)await this.jobQueueService.endWorkerSession(this.config.workerSlotId,A);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 f=this.config.concurrency-this.activeJobs.size;if(f<=0)return;if(this.config.maxJobs>0){let Z=this.stats.processedJobs+this.stats.failedJobs,V=this.config.maxJobs-Z-this.activeJobs.size;if(V<=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}f=Math.min(f,V)}let A=[];for(let Z=0;Z<f;Z++){if(this.isStopRequested())break;let V=this.workerSessionId;if(!V)throw Error("Worker session is not available");let H=await this.jobQueueService.dequeue({workerSlotId:this.config.workerSlotId,workerSessionId:V,leaseDurationMs:this.config.leaseDurationMs,workerSessionTimeoutMs:this.config.workerSessionTimeoutMs});if(H)A.push(H);else break}let $=this.jobFibers;if(!$){if(A.length>0)throw Error("Worker job fiber scope is not available");return}for(let Z of A)this.activeJobs.add(Z.id),await G.runPromise(Hf.run($,Z.id,G.promise(()=>this.processJobWrapper(Z))))}catch(f){this.logger.error("Error processing available jobs",{error:f}),this.stats.lastError=S(f)}}async processJobWrapper(f){let A=f.id;try{this.logger.debug("Processing job",{jobId:A,type:f.type,priority:f.priority,retryCount:f.retryCount});let $=await this.processJob(f);if($.status==="completed")this.stats.processedJobs++,this.logger.debug("Job completed successfully",{jobId:A,type:$.type});else this.stats.failedJobs++,this.logger.warn("Job failed",{jobId:A,type:$.type,error:$.error})}catch($){this.stats.failedJobs++,this.logger.error("Error processing job",{jobId:A,type:f.type,error:$}),this.stats.lastError=S($)}finally{this.activeJobs.delete(A)}}runPollingLoop(){let A=G.suspend(()=>{if(!this.isWorkerRunning()||this.isStopRequested())return G.interrupt;return this.currentPoll=this.processAvailableJobs(),G.promise(()=>this.currentPoll??Promise.resolve()).pipe(G.andThen(G.suspend(()=>{return this.currentPoll=null,!this.isWorkerRunning()||this.isStopRequested()?G.interrupt:G.void})))}).pipe(G.schedule(fA.spaced(this.config.pollInterval)),G.asVoid);return(this.clock?G.withClock(A,this.clock):A).pipe(G.ensuring(G.sync(()=>{this.pollFiber=null})))}requestTransition(f,A){let $=this.transitionQueue.at(-1)??this.activeTransition;if($?.kind===f)return $.promise;let Z=()=>{return},V=()=>{return},H=new Promise((X,Y)=>{Z=X,V=Y}),M={kind:f,awaitInFlightPoll:A,promise:H,resolve:Z,reject:V};return this.transitionQueue.push(M),this.runNextTransition(),H}runNextTransition(){if(this.activeTransition)return;let f=this.transitionQueue.shift();if(!f)return;this.activeTransition=f,(f.kind==="start"?this.startWorker():this.stopWorker({awaitInFlightPoll:f.awaitInFlightPoll})).then(()=>this.completeTransition(f,!0),($)=>this.completeTransition(f,!1,$))}completeTransition(f,A,$){if(this.activeTransition!==f)return;if(this.activeTransition=null,A)f.resolve();else f.reject($);queueMicrotask(()=>this.runNextTransition())}async closeWorkerScope(){let f=this.workerScope;if(this.workerScope=null,this.jobFibers=null,f)await G.runPromise(v.close(f,u.void))}startWorkerHeartbeat(){this.workerHeartbeatTimer=setInterval(()=>{let f=this.workerSessionId;if(!f||this.workerHeartbeatInFlight)return;this.workerHeartbeatInFlight=this.jobQueueService.heartbeatWorkerSession(this.config.workerSlotId,f).then((A)=>{if(!A)this.markUnhealthy("Worker session was superseded")}).catch((A)=>{this.markUnhealthy(`Worker session heartbeat failed: ${S(A)}`)}).finally(()=>{this.workerHeartbeatInFlight=null})},Math.max(1,this.config.workerHeartbeatIntervalMs))}async stopWorkerHeartbeat(){if(this.workerHeartbeatTimer)clearInterval(this.workerHeartbeatTimer),this.workerHeartbeatTimer=null;await this.workerHeartbeatInFlight,this.workerHeartbeatInFlight=null}startAttemptHeartbeat(f,A){let $=f.attemptId;if(!$)return async()=>{return};let Z=null,V=!1,H=setInterval(()=>{if(V||Z)return;Z=this.jobQueueService.renewAttemptLease(f.id,$,this.config.leaseDurationMs).then((M)=>{if(M)return;let X=Error("Job attempt was superseded");A.abort(X),this.markUnhealthy(X.message)}).catch((M)=>{let X=Nf(M);A.abort(X),this.markUnhealthy(`Attempt lease heartbeat failed: ${X.message}`)}).finally(()=>{Z=null})},Math.max(1,this.config.attemptHeartbeatIntervalMs));return async()=>{if(V)return;V=!0,clearInterval(H),await Z}}markUnhealthy(f){if(!this.stats.isHealthy)return;this.stats.isHealthy=!1,this.stats.unhealthyReason=f,this.stats.lastError=f,this.shouldStop=!0,this.logger.error("Job queue worker is unhealthy",{reason:f});try{this.config.onUnhealthy(f)}catch(A){this.logger.error("Job queue worker unhealthy callback failed",{reason:f,error:S(A)})}}async executeWithDeadline(f,A,$,Z){let V=Promise.resolve().then(Z).then((W)=>({kind:"success",value:W}),(W)=>({kind:"failure",error:W})),H,M=new Promise((W)=>{H=setTimeout(()=>W({kind:"deadline"}),Math.max(1,A))}),X=await Promise.race([V,M]);if(X.kind!=="deadline"){if(H)clearTimeout(H);if(X.kind==="failure")throw X.error;return X.value}let Y=new m0(f,A);$.abort(Y);let F,N=new Promise((W)=>{F=setTimeout(()=>W({kind:"grace-expired"}),Math.max(1,this.config.cancellationGraceMs))});if((await Promise.race([V,N])).kind!=="grace-expired"){if(F)clearTimeout(F);throw Y}throw this.markUnhealthy(`${Y.message}; handler ignored cancellation grace`),await V,Y}processJob(f){let A=f.metadata.provenance??{rootJobId:f.metadata.rootJobId,causationId:f.id,projectionLineage:[],derivationDepth:0};return this.operationContext.run(A,f.id,()=>this.processJobWithinContext(f))}async processJobWithinContext(f){let A=f.attemptId;if(!A){let X=Error(`Claimed job ${f.id} has no attempt fencing token`);return this.markUnhealthy(X.message),{jobId:f.id,type:f.type,status:P.FAILED,error:X.message}}let $=this.jobQueueService.getHandler(f.type);if(!$){let X=Error(`No handler registered for job type: ${f.type}`);return await this.jobQueueService.fail(f.id,X,A),{jobId:f.id,type:f.type,status:P.FAILED,error:X.message}}let Z=new AbortController,V=this.startAttemptHeartbeat(f,Z),H=!1,M=async()=>{if(H)return;H=!0,await V()};try{this.logger.debug("Processing job",{jobId:f.id,type:f.type,attemptId:A});let X=JSON.parse(f.data),Y=$.validateAndParse(X);if(Y===null)throw Error(`Invalid job data for type: ${f.type}`);let F=this.progressMonitor.createProgressReporter(f.id,A),N=$.executionTimeoutMs??this.config.defaultExecutionTimeoutMs,C=await this.executeWithDeadline(f.type,N,Z,()=>$.process(Y,f.id,F,Z.signal));await M();let W=A$.safeParse(C);if(W.success){let q=W.data.error??"Handler returned failure",E=Error(q);if(await this.jobQueueService.fail(f.id,E,A))await this.emitTerminalFailure(f,E,$,A);return{jobId:f.id,type:f.type,status:P.FAILED,error:q}}if(!await this.jobQueueService.complete(f.id,C,A))return{jobId:f.id,type:f.type,status:P.FAILED,error:"Job attempt no longer owns the claim"};return await this.progressMonitor.handleJobStatusChange(f.id,"completed",f.metadata),{jobId:f.id,type:f.type,status:P.COMPLETED,result:C}}catch(X){let Y=Nf(X);await M();try{let N=JSON.parse(f.data),C=$.validateAndParse(N);if(C!==null&&$.onError){let W=this.progressMonitor.createProgressReporter(f.id,A),_=new AbortController;await this.executeWithDeadline(`${f.type}:onError`,this.config.errorCallbackTimeoutMs,_,()=>$.onError?.(Y,C,f.id,W,_.signal)??Promise.resolve())}}catch(N){this.logger.error("Job handler error callback failed",{jobId:f.id,error:N})}if(await this.jobQueueService.fail(f.id,Y,A))await this.emitTerminalFailure(f,Y,$,A);return{jobId:f.id,type:f.type,status:P.FAILED,error:Y.message}}}async emitTerminalFailure(f,A,$,Z){if((await this.jobQueueService.getStatus(f.id))?.status!==P.FAILED)return;if($.onTerminalError)try{let H=$.validateAndParse(JSON.parse(f.data));if(H!==null){let M=this.progressMonitor.createProgressReporter(f.id,Z),X=new AbortController;await this.executeWithDeadline(`${f.type}:onTerminalError`,this.config.errorCallbackTimeoutMs,X,()=>$.onTerminalError?.(A,H,f.id,M,X.signal)??Promise.resolve())}}catch(H){this.logger.error("Job handler terminal error callback failed",{jobId:f.id,error:H})}await this.progressMonitor.handleJobStatusChange(f.id,"failed",f.metadata)}}var m1=86400000,S0=3600000;class Y${jobQueue;logger;batches=new Map;cleanupFiber=null;cleanupSupervisor=null;inFlightCleanups=new Set;activeTransition=null;transitionQueue=[];acceptingCleanup=!0;clock;static createFresh(f,A,$){return new Y$(f,A,$)}constructor(f,A,$){this.jobQueue=f,this.logger=A,this.clock=$?.clock}start(f=S0){return this.requestTransition("start",f)}stop(){return this.requestTransition("stop",S0)}async startCleanup(f){if(this.acceptingCleanup=!0,this.cleanupFiber)return;this.cleanupFiber=G.runFork(this.runCleanupLoop(f))}runCleanupLoop(f){let A=this.cleanupTerminalBatchMetadata().pipe(G.schedule(fA.spaced(f)),G.asVoid);return this.clock?G.withClock(A,this.clock):A}scheduleTerminalBatchCleanup(){if(!this.acceptingCleanup)return;this.cleanupSupervisor??=this.createCleanupSupervisor();let f=G.runFork(this.cleanupTerminalBatchMetadata());AA.unsafeAdd(this.cleanupSupervisor.fibers,f)}async stopCleanup(){this.acceptingCleanup=!1;let f=this.cleanupFiber;if(this.cleanupFiber=null,f)await G.runPromise(ef.interrupt(f));let A=this.cleanupSupervisor;if(A)await G.runPromise(AA.awaitEmpty(A.fibers));while(this.inFlightCleanups.size>0)await Promise.allSettled(this.inFlightCleanups);if(A)await G.runPromise(v.close(A.scope,u.void)),this.cleanupSupervisor=null}requestTransition(f,A){let $=this.transitionQueue.at(-1)??this.activeTransition;if($?.kind===f)return $.promise;let Z=()=>{return},V=()=>{return},H=new Promise((X,Y)=>{Z=X,V=Y}),M={kind:f,intervalMs:A,promise:H,resolve:Z,reject:V};return this.transitionQueue.push(M),this.runNextTransition(),H}runNextTransition(){if(this.activeTransition)return;let f=this.transitionQueue.shift();if(!f)return;this.activeTransition=f,(f.kind==="start"?this.startCleanup(f.intervalMs):this.stopCleanup()).then(()=>this.completeTransition(f,!0),($)=>this.completeTransition(f,!1,$))}completeTransition(f,A,$){if(this.activeTransition!==f)return;if(this.activeTransition=null,A)f.resolve();else f.reject($);queueMicrotask(()=>this.runNextTransition())}createCleanupSupervisor(){let f=G.runSync(v.make()),A=G.runSync(v.extend(AA.make(),f));return{scope:f,fibers:A}}cleanupTerminalBatchMetadata(){return G.tryPromise({try:()=>{let f=this.cleanup(m1);return this.inFlightCleanups.add(f),f.then(()=>this.inFlightCleanups.delete(f),()=>this.inFlightCleanups.delete(f)),f},catch:(f)=>f}).pipe(G.asVoid,G.catchAll((f)=>G.sync(()=>{this.logger.warn("Failed to clean up terminal batch metadata",{error:f})})))}validateOperations(f){for(let A of f){let $=this.jobQueue.getValidator(A.type);if(!$)throw Error(`No handler registered for job type: ${A.type}`);if($.validateAndParse(A.data)===null)throw Error(`Invalid job data for type: ${A.type}`)}}async enqueueBatch(f,A,$,Z){if(f.length===0)throw Error("Cannot enqueue empty batch");this.validateOperations(f);let V=[];this.batches.set($,{jobIds:V,operations:f,source:A.source,startedAt:new Date().toISOString(),metadata:{...A.metadata,rootJobId:$}});try{for(let H of f){let M={...A,rootJobId:$,metadata:{...A.metadata,operationTarget:H.type}},X=await this.jobQueue.enqueue({type:H.type,data:H.data,options:M});V.push(X)}return this.logger.debug("Enqueued batch operations",{batchId:$,operationCount:f.length,jobIds:V,rootJobId:$}),this.scheduleTerminalBatchCleanup(),$}catch(H){throw this.batches.delete($),this.logger.error("Failed to enqueue batch operations",{error:H,operationCount:f.length,enqueuedJobs:V.length}),H}}async getBatchStatus(f){let A=this.batches.get(f);if(!A)return null;try{let $=await Promise.all(A.jobIds.map((F)=>this.jobQueue.getStatus(F))),Z=0,V=0,H=0,M=[];for(let[F,N]of $.entries()){if(!N){V++;let C=A.operations[F],W=A.jobIds[F]??"unknown";M.push(`Missing job ${W}${C?` for ${C.type}`:""}`);continue}switch(N.status){case"completed":Z++;break;case"failed":if(V++,N.lastError)M.push(N.lastError);break;case"processing":case"pending":H++;break}}H+=A.operations.length-A.jobIds.length;let X;if(H>0)X=P.PROCESSING;else if(V>0)X=P.FAILED;else X=P.COMPLETED;if(A.terminalAt===void 0&&(X===P.COMPLETED||X===P.FAILED))A.terminalAt=Date.now();let Y;for(let F=0;F<A.jobIds.length;F++){let N=$[F];if(N&&N.status!=="completed"&&N.status!=="failed"){let C=A.operations[F];if(C)Y=`Processing ${C.type}`;break}}return{batchId:f,totalOperations:A.operations.length,completedOperations:Z,failedOperations:V,errors:M,status:X,currentOperation:Y,metadata:A.metadata}}catch($){throw this.logger.error("Failed to get batch status",{batchId:f,error:$}),$}}async cleanup(f){let A=Date.now()-f,$=0;for(let[Z,V]of this.batches.entries()){if(V.terminalAt!==void 0){if(V.terminalAt<=A)this.batches.delete(Z),$++;continue}if(new Date(V.startedAt).getTime()<=A){let M=await this.getBatchStatus(Z);if(M&&(M.status===P.COMPLETED||M.status===P.FAILED))this.batches.delete(Z),$++}}return this.logger.debug("Cleaned up batch metadata",{cleaned:$}),$}registerBatch(f,A,$,Z,V){this.batches.set(f,{jobIds:A,operations:$,source:Z,startedAt:new Date().toISOString(),metadata:V}),this.logger.debug("Registered batch metadata",{batchId:f,operationCount:$.length,jobIds:A})}async getActiveBatches(){let f=[];try{for(let[A,$]of this.batches){let Z=await this.getBatchStatus(A);if(Z&&(Z.status==="pending"||Z.status==="processing"))f.push({batchId:A,status:Z,metadata:{operations:$.operations,source:$.source,startedAt:$.startedAt,metadata:$.metadata}})}return this.logger.debug("Retrieved active batches",{count:f.length}),f}catch(A){throw this.logger.error("Failed to get active batches",{error:A}),A}}}var S1=U.preprocess((f)=>{if(typeof f!=="string")return f;return JSON.parse(f)},U.record(U.string(),U.unknown()));class L${jobQueueService;messageBus;batchJobManager;logger;mode;pollTimer;pollCursor={updatedAt:0,jobId:""};polling=!1;static createFresh(f,A,$,Z,V="combined"){return new L$(f,A,$,Z,V)}constructor(f,A,$,Z,V){this.jobQueueService=f,this.messageBus=A,this.batchJobManager=$,this.logger=Z,this.mode=V}start(){if(this.mode==="durable-reader"&&!this.pollTimer){this.pollCursor={updatedAt:Date.now(),jobId:""},this.pollTimer=setInterval(()=>{this.pollDurableUpdates()},250),this.pollTimer.unref(),this.logger.debug("Job progress monitor ready (durable polling mode)");return}this.logger.debug("Job progress monitor ready (event-driven mode)")}stop(){if(this.pollTimer)clearInterval(this.pollTimer);this.pollTimer=void 0,this.logger.debug("Job progress monitor stopped")}async pollDurableUpdates(){if(this.polling)return;this.polling=!0;try{let f=await this.jobQueueService.getRuntimeUpdates(this.pollCursor,100);for(let A of f)if(this.pollCursor=A.cursor,A.job.status==="processing"&&A.job.progress)await this.publishJobProgress(A.job,A.job.progress);else if(A.job.status==="completed"||A.job.status==="failed")await this.handleJobStatusChange(A.job.id,A.job.status,A.job.metadata)}catch(f){this.logger.error("Failed to poll durable job progress",{error:f})}finally{this.polling=!1}}createProgressReporter(f,A){let $=s.from(async(Z)=>{await this.emitJobProgress(f,Z,A)});if(!$)throw Error("Failed to create ProgressReporter");return $}async emitBatchProgress(f,A,$){try{let Z={totalOperations:A.totalOperations,completedOperations:A.completedOperations,failedOperations:A.failedOperations,currentOperation:A.currentOperation??"Processing batch...",errors:A.errors},V={id:f,type:"batch",status:A.status,metadata:$,batchDetails:Z};if(A.totalOperations>0)V.progress={current:A.completedOperations,total:A.totalOperations,percentage:Math.round(A.completedOperations/A.totalOperations*100)};await this.messageBus.send({type:Of.progress,payload:V,sender:"job-progress-monitor",broadcast:!0}),this.logger.debug("Emitted batch progress update",{batchId:f,status:A.status,progress:`${A.completedOperations}/${A.totalOperations}`})}catch(Z){this.logger.error("Error emitting batch progress update",{batchId:f,error:Z})}}isBatchChild(f,A){return!!A&&A!==f}async broadcastEvent(f){await this.messageBus.send({type:Of.progress,payload:f,sender:"job-progress-monitor",broadcast:!0})}async emitJobProgress(f,A,$){try{if($&&!await this.jobQueueService.recordAttemptProgress(f,$,A)){this.logger.debug("Discarding progress from obsolete job attempt",{jobId:f,attemptId:$});return}if(this.mode==="durable-writer")return;let Z=await this.jobQueueService.getStatus(f);if(!Z){this.logger.warn("Job not found for progress update",{jobId:f});return}await this.publishJobProgress(Z,A)}catch(Z){this.logger.error("Error emitting job progress",{jobId:f,error:Z})}}async publishJobProgress(f,A){if(f.metadata.silent)return;if(this.isBatchChild(f.id,f.metadata.rootJobId))return;let $=A.total??0,Z={id:f.id,type:"job",status:"processing",metadata:f.metadata,message:A.message};if($>0)Z.progress={current:A.progress,total:$,percentage:Math.round(A.progress/$*100)};await this.broadcastEvent(Z)}async emitJobCompletion(f){if(this.mode!=="durable-writer")await this.emitJobStatusEvent(f,"completed")}async emitJobFailure(f){if(this.mode!=="durable-writer")await this.emitJobStatusEvent(f,"failed")}async emitJobStatusEvent(f,A){try{let $=await this.jobQueueService.getStatus(f);if(!$){this.logger.warn(`Cannot emit ${A} for unknown job`,{jobId:f});return}if($.metadata.silent)return;if(this.isBatchChild(f,$.metadata.rootJobId)){this.logger.debug(`Skipping individual job ${A} for batch operation`,{jobId:f,rootJobId:$.metadata.rootJobId});return}let Z={id:f,type:"job",status:A,message:this.extractStatusMessage($,A),metadata:$.metadata,jobDetails:{jobType:$.type,priority:$.priority,retryCount:$.retryCount}};await this.broadcastEvent(Z),this.logger.debug(`Emitted job ${A} event`,{jobId:f})}catch($){this.logger.error(`Error emitting job ${A} event`,{jobId:f,error:$})}}extractStatusMessage(f,A){if(A==="failed")return f.lastError??void 0;if(!f.result)return;try{let $=S1.parse(f.result),Z=$.message;if(Z)return String(Z);let V=$.routesBuilt;if(V!==void 0)return`${V} routes built`}catch{}return}getStats(){return{isRunning:!0}}async handleJobStatusChange(f,A,$){if(this.mode==="durable-writer")return;let Z=$?Vf.safeParse($):void 0,V=Z?.success?Z.data:void 0;if(V?.silent)return;try{if(await this.emitJobStatusEvent(f,A),V&&this.isBatchChild(f,V.rootJobId))try{let H=V.rootJobId,M=await this.batchJobManager.getBatchStatus(H);if(M){let X=M.metadata??V;await this.emitBatchProgress(H,M,X)}}catch(H){this.logger.warn("Failed to emit batch progress",{jobId:f,rootJobId:V.rootJobId,error:H})}}catch(H){this.logger.error("Failed to handle job status change",{jobId:f,status:A,error:H})}}}var z1=U.record(U.string(),U.unknown());class wf{logger;schema;jobTypeName;executionTimeoutMs;constructor(f,A){this.logger=f,this.schema=A.schema,this.jobTypeName=A.jobTypeName,this.executionTimeoutMs=A.executionTimeoutMs}validateAndParse(f){if(!this.schema)throw Error(`${this.jobTypeName}: No schema provided. Override validateAndParse() or provide a schema.`);let A=this.schema.safeParse(f);if(!A.success)return this.logger.warn(`Invalid ${this.jobTypeName} job data`,{data:f,validationError:A.error.issues}),null;return this.logger.debug(`${this.jobTypeName} job data validation successful`,{data:this.summarizeDataForLog(A.data)}),A.data}async onError(f,A,$,Z,V){this.logger.error(`${this.jobTypeName} job error handler triggered`,{jobId:$,errorMessage:f.message,errorStack:f.stack,data:this.summarizeDataForLog(A)})}async reportProgress(f,A){await f.report({progress:A.progress,total:A.total??100,message:A.message})}summarizeDataForLog(f){let A=z1.safeParse(f);return A.success?A.data:{}}}function F$(f,A,$){return async(Z)=>{let{type:V,data:H,toolContext:M=null,options:X,projection:Y}=Z,F=M?z0(M):void 0,{metadata:N,...C}=X??{},W={operationType:"data_processing",pluginId:A,...N,...M&&{interfaceType:M.interfaceType,conversationId:M.conversationId,channelId:M.channelId,requestedByActor:M.actor,...F?{requestedByUserId:F}:{},requestedByInterface:M.interfaceType}};if(M&&!F)delete W.requestedByUserId;let _={...C,source:A,...X?.rootJobId&&{rootJobId:X.rootJobId},...Y&&{projection:Y},metadata:W},q=$&&!V.includes(":")?`${A}:${V}`:V;return f.enqueue({type:q,data:H,options:_})}}function C$(f,A){return async($,Z)=>{let V=g(),H=$.map((X)=>({...X,type:X.type.includes(":")?X.type:`${A}:${X.type}`})),M={...Z,source:A,rootJobId:V,metadata:{...Z?.metadata,operationType:"batch_processing",pluginId:A}};return await f.enqueueBatch(H,M,V,A),V}}function N$(f,A){return($,Z)=>{let V=$.includes(":")?$:`${A}:${$}`;f.registerHandler(V,Z,A)}}var y1=U.custom((f)=>typeof f==="object"&&f!==null&&("safeParse"in f)),h1=U.object({name:U.string(),schema:y1});function y0(f){return h1.safeParse(f).success}function v1(f){if(!f)return;return{status:f.status,message:f.message,lastCheck:f.lastCheck?.toISOString(),details:f.details}}function h0(f){return{model:f.model,version:f.version,uptime:f.uptime,entities:f.entities,entityCounts:f.entityCounts,embeddings:f.embeddings,ai:f.ai,daemons:f.daemons.map((A)=>({name:A.name,pluginId:A.pluginId,status:A.status,health:v1(A.health)})),endpoints:f.endpoints,interactions:f.interactions}}function j1(f){let A=Lf.safeParse(f);return A.success?A.data:"user"}function $A(f){let A=ff(f.metadata),$=typeof A.channelName==="string"?A.channelName:void 0;return{id:f.id,sessionId:f.sessionId,interfaceType:f.interfaceType,channelId:f.channelId,...f.personId?{personId:f.personId}:{},channelName:$,startedAt:f.started,lastActiveAt:f.lastActive,createdAt:f.created,updatedAt:f.updated,metadata:A}}function v0(f){return{id:f.id,conversationId:f.conversationId,role:j1(f.role),content:f.content,timestamp:f.timestamp,metadata:ff(f.metadata)}}function j0(f){return nA.parse(f)}function b0(f){return dA.parse(f)}function g0(f){return async()=>{return h0(await f.getAppInfo())}}function u0(f,A){return{get:()=>j0(f.getIdentity()),getProfile:()=>b0(f.getProfile()),getAppInfo:A}}function I0(f,A){let $=f.getProfileKindRegistry();return{register:(Z)=>{$.register(A,Z)},getResolved:()=>$.getResolved(),getSelectedDefinition:()=>$.getSelectedDefinition()}}function G$(f){let A=f.getChannelRegistry();return{listDescriptors:()=>A.listDescriptors(),getDescriptor:($)=>A.getDescriptor($),getDeliveryProvider:($)=>A.getDeliveryProvider($)}}function c0(f,A){let $=f.getInboxRegistry();return{registerSource:(Z)=>{$.registerSource(A,Z)},listSources:()=>$.listSources(),getSource:(Z)=>$.getSource(Z)}}function p0(f,A){let $=f.getChannelRegistry();return{...G$(f),registerDescriptor:(Z)=>{$.registerDescriptor(A,Z)},registerDeliveryProvider:(Z)=>{$.registerDeliveryProvider(A,Z)}}}function l0(f,A,$,Z=!1){let V=f.getMessageBus();return{send:async(M)=>{return V.send({...M,sender:A})},subscribe:(M,X)=>{if(Z)return()=>{};if(y0(M)){let Y=M,F=X,N=async(C)=>{let W=Y.schema.safeParse(C.payload);if(!W.success)return $.warn(`Invalid payload for channel ${Y.name}`,{error:W.error.message}),{noop:!0};let{payload:_,...q}=C;return F(W.data,q)};return V.subscribe(Y.name,N)}return V.subscribe(M,X)},subscribeExecution:(M,X)=>V.subscribe(M,X)}}function n0(f,A){let $=f.getJobQueueService();return{...f.jobs,enqueue:F$($,A,!0),enqueueBatch:C$(f.jobs,A),registerHandler:N$($,A)}}function d0(f){let A=f.getPermissionService();return{assertEntityActionAllowed:($,Z,V)=>{A.assertEntityActionAllowed($,Z,V.userPermissionLevel)}}}function i0(f){return{get:async(A)=>{let Z=await f.getConversationService().getConversation(A);return Z?$A(Z):null},search:async(A)=>{return(await f.getConversationService().searchConversations(A)).map($A)},list:async(A)=>{return(await f.getConversationService().listConversations(A)).map($A)},getMessages:async(A,$)=>{return(await f.getConversationService().getMessages(A,$)).map(v0)},countMessages:async(A)=>{return f.getConversationService().countMessages(A)}}}function s0(f,A){return{registerHandler:($,Z)=>{f.registerEvalHandler(A,$,Z)}}}function a0(f){return{register:(A,$)=>{f.getInsightsRegistry().register(A,$)}}}function r0(f){return{has:(A)=>f.getPluginPackageName(A)!==void 0}}function o0(f,A){return{register:($)=>{f.registerEndpoint({...$,pluginId:A})}}}function t0(f,A){return{register:($)=>{f.registerInteraction({...$,pluginId:A})}}}function e0(f,A){return{registerWidget:async($)=>{await f.send({type:R$.registerWidget,payload:{...$,pluginId:A}})},unregisterWidget:async($)=>{await f.send({type:R$.unregisterWidget,payload:{pluginId:A,...$?{widgetId:$}:{}}})}}}function Mf(f,A,$){let Z=f.getEntityService(),V=f.getLogger().child(A),H=f.getDomain(),M=f.getLocalSiteUrl(),X=f.shouldPreferLocalUrls(),Y=f.getThemeCSS(),F=g0(f),N=f.getAttachmentRegistry(),C=f.getRuntimeUploadRegistry(),W=f.getRuntimeState(),_=$?.executionOnly===!0,q=l0(f,A,V,_);return{pluginId:A,executionOnly:_,logger:V,entityService:Z,semantic:{project:(E)=>Z.projectSemanticSpace(E)},identity:u0(f,F),profileKinds:I0(f,A),channels:G$(f),inbox:c0(f,A),appInfo:F,readiness:()=>f.getRuntimeReadiness(),judge:(E)=>f.judge(E),domain:H,siteUrl:H?`https://${H}`:void 0,localSiteUrl:M,previewUrl:H?`https://${fZ(H)}`:void 0,preferLocalUrls:X,themeCSS:Y,entityDisplay:$?.entityDisplay,spaces:f.getSpaces(),permissions:d0(f),messaging:q,dashboard:e0(q,A),jobs:n0(f,A),attachments:N,uploads:C,runtimeState:W,recurringChecks:f.getRecurringChecks(A),conversations:i0(f),dataDir:f.getDataDir(),eval:_?{registerHandler:()=>{}}:s0(f,A),insights:_?{register:()=>{}}:a0(f),plugins:r0(f),endpoints:_?{register:()=>{}}:o0(f,A),interactions:_?{register:()=>{}}:t0(f,A)}}function b1(f){return f.replace(/:/g,"-")}function g1(f){return f.split(/[:.-]/).map((A)=>A.charAt(0).toUpperCase()+A.slice(1)).join(" ")}var K$=new Map;async function ZA(f,A,$){let Z=K$.get(A);if(Z!==void 0)return Z;let V=b1(A),H;try{H=await f.getEntity({entityType:"prompt",id:V})}catch{return $}if(H?.content){let M=xf(H.content,U.record(U.string(),U.unknown())).content;return K$.set(A,M),M}try{let M=g1(A),X=P$($,{title:M,target:A});await f.createEntity({entity:{id:V,entityType:"prompt",content:X,metadata:{title:M,target:A,slug:V}}})}catch{}return K$.set(A,$),$}async function u1(f,A){let $=f.list().filter((Z)=>!!Z.basePrompt);return await Promise.all($.map((Z)=>ZA(A,Z.name,Z.basePrompt))),$.length}function UA(f){let A=f.getEntityService(),$=f.getEntityRegistry(),Z=f.getDataSourceRegistry();return{register:(V,H,M,X)=>{$.registerEntityType(V,H,M,X)},getAdapter:(V)=>{try{return $.getAdapter(V)}catch{return}},extendFrontmatterSchema:(V,H)=>{$.extendFrontmatterSchema(V,H)},getEffectiveFrontmatterSchema:(V)=>{return $.getEffectiveFrontmatterSchema(V)},registerPersistValidator:(V,H)=>{$.registerPersistValidator(V,H)},registerCreateInterceptor:(V,H)=>{$.registerCreateInterceptor(V,H)},registerUploadSaveHandler:(V)=>{$.registerUploadSaveHandler(V)},getUploadSaveHandler:(V)=>{return $.getUploadSaveHandler(V)},update:async(V)=>{return A.updateEntity({entity:V})},registerDataSource:(V)=>{Z.register(V)}}}function VA(f){return{resolve:(A,$)=>{return ZA(f,A,$)}}}function HA(f){return{query:(A,$)=>f.query(A,$),generate:async(A)=>{return f.generateContent(A)},generateObject:async(A,$,Z)=>{return f.generateObject(A,$,Z)},generateImage:async(A,$)=>{return f.generateImage(A,$)},canGenerateImages:()=>{return f.canGenerateImages()}}}function W$(f,A,$){let Z=Mf(f,A,$),V=f.getEntityService();return{...Z,entityService:V,entities:UA(f),ai:HA(f),prompts:VA(V),permissions:Z.permissions}}function D$(f,A,$){let Z=Mf(f,A,$),V=f.getEntityService(),H=f.getRenderService(),M=f.getContentService(),X=f.getPermissionService();return{...Z,permissions:{...Z.permissions,getConfiguredPrincipalSeeds:()=>X.getConfiguredPrincipalSeeds(),replaceRuntimePrincipalState:(Y)=>X.replaceRuntimePrincipalState(Y)},entityService:V,entities:UA(f),webRoutes:{getRoutes:()=>f.getPluginWebRoutes()},templates:{register:(Y,F)=>{f.registerTemplates(Y,F??A)},format:(Y,F)=>{return M.formatContent(Y,F,{pluginId:A})},parse:(Y,F)=>{return M.parseContent(Y,F,A)},resolve:async(Y,F)=>{return await M.resolveContent(Y,F,A)},getCapabilities:(Y)=>{let F=Y.includes(":")?Y:`${A}:${Y}`,N=f.getTemplate(F);if(!N)return null;let C=AZ.getCapabilities(N);return{canGenerate:C.canGenerate,canFetch:C.canFetch,canRender:C.canRender,isStaticOnly:C.isStaticOnly}}},views:{get:(Y)=>{return H.get(Y)??void 0},list:()=>{return H.list()},hasRenderer:(Y,F="web")=>{return H.hasRenderer(Y,F)},getRenderer:(Y,F="web")=>{return H.getRenderer(Y,F)},validate:(Y,F)=>{return H.validate(Y,F)}},prompts:VA(V),ai:HA(f),registerInstructions:(Y)=>{f.registerInstructions(A,Y)}}}class $Z extends Zf{type="service";getApiRoutes(){return[]}getWebRoutes(){return[]}async register(f,A){let $=D$(f,this.id,A);return this.context=$,this.setupMessageHandlers($),await this.onRegister($),this.getCapabilities()}get entityService(){return this.getContext().entityService}registerEntityType(f,A,$,Z){this.getContext().entities.register(f,A,$,Z)}async enqueueJob(f){return this.getContext().jobs.enqueue(f)}async enqueueBatch(f,A){return this.getContext().jobs.enqueueBatch(f,A)}async registerEntityTypes(f){}async registerJobHandlers(f){}async onRegister(f){await this.registerEntityTypes(f),await this.registerJobHandlers(f)}}var I1=U.object({});class _$ extends Zf{type="entity";entityActionPolicy;constructor(f,A,$,Z,V){super(f,A,$,Z);if(V!==void 0)this.entityActionPolicy=V}async register(f,A){let $=W$(f,this.id,A);this.context=$,this.setupMessageHandlers($);let Z=this.getProjectionRules($),V=this.getEntityTypeConfig(),H=Z.some((W)=>W.targetType===this.entityType),M=V?.projectionSource!==!1&&V?.projectionSourceRole!=="excluded"&&(V?.projectionSource===!0||V?.projectionSourceRole!==void 0),X=H&&!M?{...V,projectionSource:!1,projectionSourceRole:"excluded"}:V;if($.entities.register(this.entityType,this.schema,this.adapter,X),this.interceptCreate!==_$.prototype.interceptCreate)$.entities.registerCreateInterceptor(this.entityType,(W,_)=>this.interceptCreate(W,_,$));let Y=this.createGenerationHandler($);if(Y)$.jobs.registerHandler(`${this.entityType}:generation`,Y);let F=this.getTemplates();if(F&&Object.keys(F).length>0)f.registerTemplates(F,this.id);let N=this.getDataSources();for(let W of N)$.entities.registerDataSource(W);await this.onRegister(this.context);let C=await this.getInstructions();return{tools:[],resources:[],...C&&{instructions:C},...Z.length>0&&{projectionRules:Z}}}async interceptCreate(f,A,$){return{kind:"continue",input:f}}createGenerationHandler(f){return null}getTemplates(){return null}getDataSources(){return[]}getEntityTypeConfig(){return}getProjectionRules(f){return[]}}async function c1({context:f,targetType:A,desired:$,getId:Z,toEntityInput:V,equals:H,deleteStale:M=!1,outputVisibility:X="public",concurrency:Y=1,logger:F}){let N=new Map;for(let z of $)N.set(Z(z),z);let C=(await f.entityService.listEntities({entityType:A,options:{filter:{visibilityScope:X}}})).filter((z)=>z.visibility===X),W=new Map(C.map((z)=>[z.id,z])),_=0,q=0,E=0,I=0,r=Math.max(1,Y);if(M){let z=C.filter((c)=>!N.has(c.id));await ZZ(z,r,async(c)=>{await f.entityService.deleteEntity({entityType:A,id:c.id}),E++})}return await ZZ(Array.from(N),r,async([z,c])=>{let R=W.get(z),B={...V(c,z),visibility:X};try{if(!R){await f.entityService.createEntity({entity:B}),_++;return}if(H?.(R,c)??!1){I++;return}await f.entityService.updateEntity({entity:{...R,...B,id:z,entityType:A,visibility:X}}),q++}catch(K){F?.error("Failed to reconcile entity",{targetType:A,id:z,error:S(K)})}}),{created:_,updated:q,deleted:E,skipped:I}}async function ZZ(f,A,$){let Z=await G.runPromiseExit(G.forEach(f,(V)=>G.tryPromise({try:()=>$(V),catch:(H)=>H}),{concurrency:A,discard:!0}));if(u.isFailure(Z))throw MA.squash(Z.cause)}async function p1({entityService:f,entity:A,options:$}){let Z=await f.getEntity({entityType:A.entityType,id:A.id});if(Z)return{entityId:Z.id,created:!1,existingEntity:Z};let V=await f.createEntity({entity:A,...$?{options:$}:{}});return{entityId:V.entityId,created:!0,mutation:V}}async function l1({entityService:f,entity:A,expectedContentHash:$}){let Z=await f.getEntity({entityType:A.entityType,id:A.id});if(Z){let H={...Z,content:A.content,metadata:A.metadata,updated:A.updated??new Date().toISOString()},M=await f.updateEntity({entity:H,...$!==void 0?{options:{expectedContentHash:$}}:{}});return{entityId:M.entityId,updated:!0,mutation:M,previousEntity:Z}}if($!==void 0)return{entityId:A.id,updated:!1,mutation:{entityId:A.id,jobId:"",skipped:!0,skipReason:"content-conflict"}};let V=await f.createEntity({entity:A});return{entityId:V.entityId,updated:!1,mutation:V}}async function n1({entityService:f,entityType:A,id:$,error:Z,content:V}){let H=await f.getEntity({entityType:A,id:$});if(!H)return{found:!1};let M={...H,content:V??H.content,metadata:{...H.metadata,status:"failed",processingError:Z},updated:new Date().toISOString()},X=await f.updateEntity({entity:M});return{found:!0,entityId:X.entityId,mutation:X,previousEntity:H}}function UZ(f){return HZ(f)}function VZ(f){if(!f)return;return{...f.userPermissionLevel&&{userPermissionLevel:f.userPermissionLevel},...f.isAnchor!==void 0&&{isAnchor:f.isAnchor},...f.interfaceType&&{interfaceType:f.interfaceType},...f.channelId&&{channelId:f.channelId},...f.channelName&&{channelName:f.channelName},...f.actor&&{actor:f.actor},...f.source&&{source:f.source},...f.attachments&&{attachments:f.attachments}}}function MZ(f){return{chat:async(A,$,Z,V)=>{let H=VZ(Z),M=V?await f.chat(A,$,H,V):await f.chat(A,$,H);return UZ(M)},confirmPendingAction:async(A,$,Z,V,H)=>{let M=VZ(V);if(!M)throw Error("Confirmation requires caller context.");let X=H?await f.confirmPendingAction(A,$,Z,M,H):await f.confirmPendingAction(A,$,Z,M);return UZ(X)},invalidate:()=>{f.invalidateAgent()}}}var XA=new WeakMap;function d1(f,A){if(XA.has(f))throw Error("HTTP route snapshot provider is already bound");XA.set(f,A)}function XZ(f,A){let $=XA.get(f);if(!$)throw Error("HTTP route snapshot provider is not bound");d1(A,$)}function YZ(f){let A=XA.get(f);if(!A)throw Error("HTTP route snapshot provider is not bound");return A()}function YA(f,A,$){let Z=Mf(f,A,$),V=f.getMCPService(),H=f.getPermissionService(),M=MZ(f.getAgentService());return{...Z,mcpTransport:V,agent:M,permissions:{...Z.permissions,getUserLevel:(X,Y,F)=>{return H.determineUserLevel(X,Y,F)},isAnchor:(X,Y)=>H.isAnchor(X,Y)},daemons:{register:(X,Y)=>{let F=`${A}:${X}`;f.registerDaemon(F,Y,A),Z.logger.debug(`Registered daemon: ${F}`)}},conversations:{...Z.conversations,start:async(X)=>{return f.getConversationService().startConversation(X)},addMessage:async(X)=>{await f.getConversationService().addMessage(X)},updateMetadata:async(X)=>{return f.getConversationService().updateConversationMetadata(X)},delete:async(X)=>{return f.getConversationService().deleteConversation(X)}},tools:{listForPermissionLevel:(X)=>{return f.listToolsForPermissionLevel(X)}},apiRoutes:{getRoutes:()=>{return f.getPluginApiRoutes()},getMessageBus:()=>{return f.getMessageBus()}},webRoutes:{getRoutes:()=>{return f.getPluginWebRoutes()}},httpRoutes:{getRoutes:()=>YZ(f)},plugins:{has:(X)=>f.hasPlugin(X)}}}function B$(f,A,$){return{...YA(f,A,$),channels:p0(f,A)}}var i1=3600000;class LA extends Zf{type="interface";daemon;jobTrackingEntries=new Map;jobTrackingTtlMs=i1;createContext(f,A){return YA(f,this.id,A)}async register(f,A){let $=this.createContext(f,A);if(this.context=$,this.initializeDaemon(),this.daemon)await this.registerDaemon($);return this.setupMessageHandlers($),await this.onRegister($),this.getCapabilities()}async onRegister(f){}async registerDaemon(f){if(!this.daemon)return;f.daemons.register(this.id,this.daemon),f.logger.debug(`Registered daemon for interface: ${this.id}`)}createDaemon(){return}requiresDaemonStartup(){return!1}getWebRoutes(){return[]}initializeDaemon(){let f=this.createDaemon();if(f)this.daemon=f}async handleProgressEvent(f,A){}cleanupExpiredEntries(){let f=Date.now(),A=[];for(let[$,Z]of this.jobTrackingEntries)if(f-Z.createdAt>this.jobTrackingTtlMs)A.push($);for(let $ of A)this.jobTrackingEntries.delete($)}ownsJob(f,A){return this.jobTrackingEntries.has(f)||A!==void 0&&this.jobTrackingEntries.has(A)}getJobTracking(f,A){let $=this.jobTrackingEntries.get(f);if($)return $.info;if(A){let Z=this.jobTrackingEntries.get(A);if(Z)return Z.info}return}setJobTracking(f,A){this.cleanupExpiredEntries(),this.jobTrackingEntries.set(f,{info:A,createdAt:Date.now()})}removeJobTracking(f){this.jobTrackingEntries.delete(f)}async createJobWithTracking(f,A){let Z=await this.getContext().jobs.enqueue(f);return this.setJobTracking(Z,A),Z}async createBatchWithTracking(f,A,$){let V=await this.getContext().jobs.enqueueBatch(f,$);return this.setJobTracking(V,A),V}}var CZ=/^[a-z][a-z0-9-]*$/,s1=U.strictObject({source:U.string().min(1).max(500),flags:U.string().regex(/^[imu]*$/).optional()}),a1=U.strictObject({type:U.string().trim().regex(CZ),displayName:U.string().trim().min(1).max(100),subjectLabel:U.string().trim().min(1).max(100),subjectPattern:s1.optional(),manualDelivery:U.boolean().optional()});class NZ{descriptorRegistrations=new Map;providerRegistrations=new Map;activeDescriptors=new Map;activeProviders=new Map;finalized=!1;registerDescriptor(f,A){this.assertRegistrationOpen();let $=LZ(f),Z=a1.parse(A);if(Z.subjectPattern)new RegExp(Z.subjectPattern.source,Z.subjectPattern.flags);let V=Object.freeze({type:Z.type,displayName:Z.displayName,subjectLabel:Z.subjectLabel,...Z.subjectPattern?{subjectPattern:Object.freeze({...Z.subjectPattern})}:{},...Z.manualDelivery!==void 0?{manualDelivery:Z.manualDelivery}:{}}),H=this.descriptorRegistrations.get(Z.type)??[];H.push({pluginId:$,descriptor:V}),this.descriptorRegistrations.set(Z.type,H)}registerDeliveryProvider(f,A){this.assertRegistrationOpen();let $=LZ(f),Z=k$(A.channelType);if(typeof A.isAvailable!=="function"||typeof A.send!=="function")throw Error("Channel delivery provider operations are required");let V=Object.freeze({channelType:Z,isAvailable:A.isAvailable.bind(A),send:A.send.bind(A)}),H=this.providerRegistrations.get(Z)??[];H.push({pluginId:$,provider:V}),this.providerRegistrations.set(Z,H)}unregisterPlugin(f){let A=f.trim();for(let[$,Z]of this.descriptorRegistrations){let V=Z.filter((H)=>H.pluginId!==A);if(V.length===0)this.descriptorRegistrations.delete($);else this.descriptorRegistrations.set($,V)}for(let[$,Z]of this.providerRegistrations){let V=Z.filter((H)=>H.pluginId!==A);if(V.length===0)this.providerRegistrations.delete($);else this.providerRegistrations.set($,V)}if(this.finalized)this.rebuildActiveState(!1)}finalize(){if(this.finalized)return;this.rebuildActiveState(!0),this.finalized=!0}listDescriptors(){return this.assertFinalized(),[...this.activeDescriptors.values()].sort((f,A)=>f.type.localeCompare(A.type))}getDescriptor(f){return this.assertFinalized(),this.activeDescriptors.get(k$(f))}getDeliveryProvider(f){return this.assertFinalized(),this.activeProviders.get(k$(f))}isFinalized(){return this.finalized}rebuildActiveState(f){let A=new Map,$=new Map;for(let[Z,V]of this.descriptorRegistrations){if(V.length>1){if(!f)continue;throw FZ("Channel",Z,V)}let H=V[0]?.descriptor;if(H)A.set(Z,H)}for(let[Z,V]of this.providerRegistrations){if(V.length>1){if(!f)continue;throw FZ("Delivery provider for channel",Z,V)}if(!A.has(Z)){if(f)throw Error(`Delivery provider for channel "${Z}" has no descriptor`);continue}let H=this.descriptorRegistrations.get(Z)?.[0]?.pluginId,M=V[0]?.pluginId;if(H!==M){if(f)throw Error(`Delivery provider for channel "${Z}" must be registered by descriptor owner "${H??"unknown"}", not "${M??"unknown"}"`);continue}let X=V[0]?.provider;if(X)$.set(Z,X)}this.activeDescriptors=A,this.activeProviders=$}assertRegistrationOpen(){if(this.finalized)throw Error("Channel registration is closed")}assertFinalized(){if(!this.finalized)throw Error("Channel registry is not finalized")}}function LZ(f){let A=f.trim();if(!A)throw Error("Channel registration plugin id is required");return A}function k$(f){let A=f.trim();if(!CZ.test(A))throw Error(`Invalid channel type: ${f}`);return A}function FZ(f,A,$){let Z=$.map((V)=>V.pluginId).sort().join(", ");return Error(`${f} "${A}" is registered by multiple plugins: ${Z}`)}var FA=/^[a-z][a-z0-9-]*$/,GZ=U.strictObject({id:U.string().trim().regex(FA),label:U.string().trim().min(1).max(100),confirm:U.boolean().optional()}),RZ=U.strictObject({entityType:U.string().trim().min(1).max(100),entityId:U.string().trim().min(1).max(300)}),KZ=U.strictObject({id:U.string().trim().min(1).max(300),title:U.string().trim().min(1).max(160),summary:U.string().trim().min(1).max(1000).optional(),receivedAt:U.iso.datetime(),urgency:U.enum(["high","normal"]),entityRef:RZ.optional(),actions:U.array(GZ).max(10)}).superRefine((f,A)=>{let $=new Set;for(let Z of f.actions){if($.has(Z.id))A.addIssue({code:"custom",path:["actions"],message:`Duplicate inbox action id: ${Z.id}`});$.add(Z.id)}}),PZ=U.array(KZ).max(1000),WZ=U.strictObject({permissionLevel:U.enum(["admin","trusted","public"])}),DZ=U.strictObject({sourceId:U.string().trim().regex(FA),displayName:U.string().trim().min(1).max(100)});class _Z{registrations=new Map;activeSources=new Map;finalized=!1;registerSource(f,A){this.assertRegistrationOpen();let $=t1(f),Z=DZ.parse({sourceId:A.sourceId,displayName:A.displayName});if(typeof A.list!=="function"||typeof A.act!=="function")throw Error("Inbox source operations are required");let V=r1(Z,A),H=this.registrations.get(Z.sourceId)??[];H.push({pluginId:$,source:V}),this.registrations.set(Z.sourceId,H)}unregisterPlugin(f){let A=f.trim();for(let[$,Z]of this.registrations){let V=Z.filter((H)=>H.pluginId!==A);if(V.length===0)this.registrations.delete($);else this.registrations.set($,V)}if(this.finalized)this.rebuildActiveState(!1)}finalize(){if(this.finalized)return;this.rebuildActiveState(!0),this.finalized=!0}listSources(){return this.assertFinalized(),[...this.activeSources.values()].sort((f,A)=>f.sourceId.localeCompare(A.sourceId))}getSource(f){return this.assertFinalized(),this.activeSources.get(e1(f))}isFinalized(){return this.finalized}rebuildActiveState(f){let A=new Map;for(let[$,Z]of this.registrations){if(Z.length>1){if(!f)continue;let H=Z.map((M)=>M.pluginId).sort().join(", ");throw Error(`Inbox source "${$}" is registered by multiple plugins: ${H}`)}let V=Z[0]?.source;if(V)A.set($,V)}this.activeSources=A}assertRegistrationOpen(){if(this.finalized)throw Error("Inbox registration is closed")}assertFinalized(){if(!this.finalized)throw Error("Inbox registry is not finalized")}}function r1(f,A){return Object.freeze({...f,list:async()=>{return PZ.parse(await A.list()).map(o1)},act:async($,Z,V)=>{let H=U.string().trim().min(1).max(300).parse($),M=U.string().trim().regex(FA).parse(Z);await A.act(H,M,WZ.parse(V))}})}function o1(f){let A=f.actions.map(($)=>Object.freeze({...$}));return Object.freeze(A),Object.freeze({...f,...f.entityRef?{entityRef:Object.freeze({...f.entityRef})}:{},actions:A})}function t1(f){let A=f.trim();if(!A)throw Error("Inbox registration plugin id is required");return A}function e1(f){return U.string().trim().regex(FA).parse(f)}var f8={pluginsRegistered:"system:plugins:registered",initialSyncCompleted:"sync:initial:completed",shellReady:"system:shell:ready"};function A8(f){return{register:(A,$,Z)=>{return f.register(A,$,Z)},resolve:(A)=>{return f.resolve(A)},hasProvider:(A,$)=>{return f.has(A,$)},getProviderMetadata:(A,$)=>{return f.getMetadata(A,$)}}}class O${providers=new Map;static createFresh(){return new O$}constructor(){}register(f,A,$){return this.getOrCreateSourceProviders(f).set(A,$),()=>{this.unregister(f,A)}}async resolve(f){let A=this.get(f.sourceEntityType,f.attachmentType);if(!A)return;return A.resolve(f)}get(f,A){return this.providers.get(f)?.get(A)}has(f,A){return this.get(f,A)!==void 0}getMetadata(f,A){return this.get(f,A)?.metadata}unregister(f,A){let $=this.providers.get(f);if(!$)return;if($.delete(A),$.size===0)this.providers.delete(f)}getRegisteredAttachmentTypes(f){return Array.from(this.providers.get(f)?.keys()??[])}clear(){this.providers.clear()}getOrCreateSourceProviders(f){let A=this.providers.get(f);if(A)return A;let $=new Map;return this.providers.set(f,$),$}}import{mkdir as $8,readdir as Z8,readFile as BZ,rm as kZ,stat as U8,writeFile as OZ}from"fs/promises";import{basename as V8,dirname as H8,join as n}from"path";var CA=/^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,wZ=86400000,xZ=200;class Xf extends Error{code;constructor(f,A){super(A);this.code=f,this.name="RuntimeUploadStoreError"}}var M8=U.object({id:U.string().regex(CA),ref:U.object({kind:U.string().min(1),id:U.string().regex(CA)}),filename:U.string().min(1),mediaType:U.string().min(1),sizeBytes:U.number().nonnegative(),createdAt:U.string().datetime(),metadata:U.record(U.string(),U.unknown()).optional()});function X8(f){return{scoped:(A)=>f.scoped(A)}}function JZ(f){return V8(f)==="brain-data"?n(H8(f),"data"):f}class w${dataDir;constructor(f){this.dataDir=JZ(f.dataDir)}static createFresh(f){return new w$(f)}scoped(f){return new x$({...f,dataDir:this.dataDir})}}class x${options;retentionMs;maxCount;createUploadId;getNow;constructor(f){this.options=f,this.retentionMs=f.retentionMs??wZ,this.maxCount=f.maxCount??xZ,this.createUploadId=f.createId??(()=>`upload-${crypto.randomUUID()}`),this.getNow=f.now??(()=>new Date)}async save(f){let A=this.createUploadId();this.assertValidUploadId(A);let $={id:A,ref:{kind:this.options.refKind,id:A},filename:f.filename,mediaType:f.mediaType,sizeBytes:f.content.byteLength,createdAt:this.getNow().toISOString(),...f.metadata!==void 0&&{metadata:f.metadata}},Z=this.getUploadDir(A);return await $8(Z,{recursive:!0}),await OZ(n(Z,"content"),f.content),await OZ(n(Z,"metadata.json"),`${JSON.stringify($,null,2)}
|
|
2
|
+
import{$e as i,$f as mZ,Af as fA,Jf as hf,Le as g,Mf as u$,Ne as w,Oe as D,Pf as zf,Qe as m,Re as Ff,Rf as P$,Se as W0,Sf as xf,Ue as Bf,Ve as kf,We as Z$,Wf as jf,Xf as bf,Ye as U$,Ze as E0,_e as $f,_f as Q$,ag as GA,bf as j,cf as k,cg as yf,df as t,eg as vA,ff as b,jf as gf,kf as pf,of as gU,rf as MA,tf as u,uf as v,vf as ef,wf as G,xf as Hf,yf as AA}from"./index-h766y45k.js";import{pg as of}from"./index-zzk961wq.js";import{Hg as fZ,Kg as lA}from"./index-1qkfzrqr.js";import{Dh as AZ}from"./index-w77s1gcj.js";import{Bi as EZ,Ci as Of,Hi as Df,Ki as NA,Uh as lf,Vh as nf,Wh as df,Zh as HZ,bi as Af,ci as G0,di as z0,ei as A0,li as F0,ri as S,si as Nf,ti as TZ,ui as Lf,vi as Uf,xi as R$}from"./index-fqrd7rca.js";import{Si as U}from"./index-58smerak.js";var uU=U.object({id:U.string(),sessionId:U.string(),interfaceType:U.string(),channelId:U.string(),personId:U.string().optional(),channelName:U.string().optional(),startedAt:U.string(),lastActiveAt:U.string(),createdAt:U.string(),updatedAt:U.string(),metadata:lA}),IU=U.object({id:U.string(),conversationId:U.string(),role:Lf,content:U.string(),timestamp:U.string(),metadata:lA});var nA=U.object({name:U.string(),role:U.string(),purpose:U.string(),values:U.array(U.string())}),dA=U.object({name:U.string(),organization:U.string().optional(),description:U.string().optional(),avatar:U.string().optional(),website:U.string().optional(),email:U.string().optional(),socialLinks:U.array(U.object({platform:U.enum(["github","instagram","linkedin","email","website"]),url:U.string(),label:U.string().optional()})).optional()});function L0(f){return w`count(${f||w.raw("*")})`.mapWith(Number)}function sA(f){return F0(iA(f))}function iA(f,A=new Set){if(f===null)return"null";if(typeof f==="string"||typeof f==="boolean")return JSON.stringify(f);if(typeof f==="number"){if(!Number.isFinite(f))throw Error("Projection inputs cannot contain non-finite numbers");if(Number.isInteger(f)&&!Number.isSafeInteger(f))throw Error("Projection inputs cannot contain unsafe integers");return JSON.stringify(f)}if(typeof f!=="object")throw Error(`Projection inputs cannot contain ${typeof f} values`);if(A.has(f))throw Error("Projection inputs cannot contain circular values");let $=new Set(A).add(f);if(Array.isArray(f))return`[${f.map((V)=>iA(V,$)).join(",")}]`;let Z=Object.getPrototypeOf(f);if(Z!==Object.prototype&&Z!==null)throw Error("Projection inputs must contain only plain JSON objects");return`{${Object.entries(f).filter(([,V])=>V!==void 0).sort(([V],[H])=>V.localeCompare(H)).map(([V,H])=>`${JSON.stringify(V)}:${iA(H,$)}`).join(",")}}`}function aA(f){if(f!==null&&typeof f==="object"){for(let A of Object.values(f))aA(A);Object.freeze(f)}return f}var pU=U.strictObject({id:U.string().trim().min(1),version:U.string().trim().min(1),sources:U.array(U.strictObject({kind:U.literal("entity"),types:U.array(U.string().trim().min(1)).min(1),excludeTypes:U.array(U.string().trim().min(1)).optional()})),targetType:U.string().trim().min(1)});function lU(f){let A=pU.parse({id:f.id,version:f.version,sources:f.sources,targetType:f.targetType});if(typeof f.selectInput!=="function")throw Error(`Projection rule "${A.id}" must select input`);if(typeof f.derive!=="function")throw Error(`Projection rule "${A.id}" must derive output`);let $=A.sources.map((Z)=>{let V=Object.freeze([...Z.types]),H=Z.excludeTypes?Object.freeze([...Z.excludeTypes]):void 0,M={kind:"entity",types:V,...H?{excludeTypes:H}:{}};return Object.freeze(M)});return Object.freeze({id:A.id,version:A.version,sources:Object.freeze($),targetType:A.targetType,inputSchema:f.inputSchema,selectInput:async(Z,V,H)=>{let M=await f.selectInput(Z,V,H),X=jf.parse(M);return aA(f.inputSchema.parse(X))},fingerprint:sA,derive:async(Z,V,H)=>{let M=f.inputSchema.parse(Z),X=U.array(bf).parse(await f.derive(M,V,H));for(let Y of X){let F=Y.operation==="upsert"?Y.entity.entityType:Y.entityType;if(F!==A.targetType)throw Error(`Projection rule "${A.id}" cannot write entity type "${F}"`)}return aA(X)}})}var C0={digest:"conversation:digest"};var J=t("conversations",{id:k("id").primaryKey(),sessionId:k("session_id").notNull(),interfaceType:k("interface_type").notNull(),channelId:k("channel_id").notNull(),personId:k("person_id"),started:k("started").notNull(),lastActive:k("last_active").notNull(),metadata:k("metadata"),created:k("created").notNull(),updated:k("updated").notNull()},(f)=>({sessionIdx:b("idx_conversations_session").on(f.sessionId),channelIdx:b("idx_conversations_channel").on(f.channelId),personIdx:b("idx_conversations_person").on(f.personId),interfaceSessionIdx:b("idx_conversations_interface_session").on(f.interfaceType,f.sessionId),interfaceChannelIdx:b("idx_conversations_interface_channel").on(f.interfaceType,f.channelId)})),h=t("messages",{id:k("id").primaryKey(),conversationId:k("conversation_id").notNull().references(()=>J.id,{onDelete:"cascade"}),role:k("role").notNull(),content:k("content").notNull(),timestamp:k("timestamp").notNull(),metadata:k("metadata")},(f)=>({conversationIdx:b("idx_messages_conversation").on(f.conversationId),timestampIdx:b("idx_messages_timestamp").on(f.timestamp)})),e=t("summary_tracking",{conversationId:k("conversation_id").primaryKey().references(()=>J.id,{onDelete:"cascade"}),lastSummarizedAt:k("last_summarized_at"),lastMessageId:k("last_message_id"),messagesSinceSummary:j("messages_since_summary").default(0),updated:k("updated").notNull()});function N0(f){return gf({url:f.url,schema:{conversations:J,messages:h,summaryTracking:e},authToken:f.authToken,authTokenEnv:"CONVERSATION_DATABASE_AUTH_TOKEN"})}var nU=U.preprocess((f)=>{if(typeof f!=="string")return f;try{return JSON.parse(f)}catch{return}},U.record(U.string(),U.unknown())).catch({});function ff(f){return nU.parse(f)}var If="conversation:messageAdded",rA="conversation:started",Pf=U.object({identity:Af,interfaceType:U.string(),role:Lf,displayName:U.string().optional(),username:U.string().optional(),isBot:U.boolean().optional()}),dU=U.preprocess(iU,Pf);function iU(f){if(!uf(f)||"identity"in f)return f;let{actorId:A,interfaceType:$,role:Z}=f;if(typeof A!=="string"||typeof $!=="string"||Z!=="user"&&Z!=="assistant")return f;let{userId:V,canonicalId:H}=f;return{identity:G0({actorId:A,interfaceType:$,role:Z,...typeof V==="string"?{userId:V}:{},...typeof H==="string"?{canonicalId:H}:{}}),interfaceType:$,role:Z,...typeof f.displayName==="string"?{displayName:f.displayName}:{},...typeof f.username==="string"?{username:f.username}:{},...typeof f.isBot==="boolean"?{isBot:f.isBot}:{}}}var Wf=U.object({messageId:U.string().optional(),channelId:U.string().optional(),channelName:U.string().optional(),threadId:U.string().optional(),metadata:U.record(U.string(),U.unknown()).optional()}),R0=U.looseObject({actor:dU.optional(),source:Wf.optional()});function K0(f){if(typeof f==="string")try{let A=JSON.parse(f);return uf(A)?A:null}catch{return null}return uf(f)?f:null}function sU(f){if(f.role!=="assistant")return!1;if(f.content.trim().length===0)return!1;let A=K0(f.metadata),$=A?.entityMemoryRefs;if(Array.isArray($)&&$.length>0)return!1;let Z=A?.cards;if(!Array.isArray(Z))return!0;return!Z.some((V)=>{if(!uf(V))return!1;if(V.kind==="tool-approval")return!0;return V.kind==="actions"&&V.id==="actions:upload-intent"})}function uf(f){return typeof f==="object"&&f!==null&&!Array.isArray(f)}var aU=U.object({id:U.string(),conversationId:U.string(),role:U.string(),content:U.string(),timestamp:U.string(),metadata:U.string().nullable()}),P0=U.object({conversationId:U.string(),messageCount:U.number(),messages:U.array(aU),windowStart:U.number(),windowEnd:U.number(),windowSize:U.number(),timestamp:U.string()});class cf{db;logger;messageBus;config;dbClient=null;dbUrl=null;pragmaInitialization=null;constructor(f,A,$,Z={}){this.db=f,this.logger=A,this.messageBus=$,this.config={digestTriggerInterval:5,digestWindowSize:10,...Z}}initialize(){return this.pragmaInitialization??=this.applyPragmas(),this.pragmaInitialization}async applyPragmas(){let f=this.dbClient,A=this.dbUrl;if(!f||A===null)return;try{await pf(f,A)}catch($){this.logger.warn("Failed to enable conversation database pragmas (non-fatal)",$)}}getDatabaseClient(){if(!this.dbClient)throw Error("ConversationService does not own a database client");return this.dbClient}close(){this.dbClient?.close()}static createFresh(f,A,$,Z){return new cf(f,A,$,Z)}static createFreshFromConfig(f,A,$,Z){let{db:V,client:H,url:M}=N0($),X=new cf(V,f,A,Z);return X.dbClient=H,X.dbUrl=M,X}async startConversation(f){let{sessionId:A,interfaceType:$,channelId:Z,personId:V,metadata:H}=f,M=new Date().toISOString();if(await this.getConversation(A))return await this.db.update(J).set({lastActive:M,updated:M}).where(D(J.id,A)),this.logger.debug("Resumed existing conversation",{conversationId:A,interfaceType:$}),A;let Y={id:A,sessionId:A,interfaceType:$,channelId:Z,personId:V??null,started:M,lastActive:M,created:M,updated:M,metadata:JSON.stringify(H)};await this.db.insert(J).values(Y);let F={conversationId:A,messagesSinceSummary:0,updated:M};return await this.db.insert(e).values(F),this.logger.debug("Started new conversation",{conversationId:A,sessionId:A,interfaceType:$}),await this.messageBus.send({type:rA,payload:{conversationId:A,sessionId:A,interfaceType:$,timestamp:M},sender:"conversation-service",broadcast:!0}),A}async addMessage(f){let{conversationId:A,role:$,content:Z,metadata:V}=f,H=new Date().toISOString(),M=g(12),X={id:M,conversationId:A,role:$,content:Z,timestamp:H,metadata:V?JSON.stringify(V):null};await this.db.insert(h).values(X),await this.db.update(J).set({lastActive:H,updated:H}).where(D(J.id,A)),await this.db.update(e).set({messagesSinceSummary:w`${e.messagesSinceSummary} + 1`,lastMessageId:M,updated:H}).where(D(e.conversationId,A)),this.logger.debug("Added message to conversation",{conversationId:A,role:$,messageId:M}),await this.messageBus.send({type:If,payload:{conversationId:A,messageId:M,role:$,content:Z,metadata:V,timestamp:H},sender:"conversation-service",broadcast:!0}),await this.checkAndBroadcastDigest(A,H)}async getMessages(f,A={}){let{limit:$=20,range:Z}=A;if(Z){let V=Z.start-1,H=Z.end-Z.start+1;return await this.db.select().from(h).where(D(h.conversationId,f)).orderBy($f(h.timestamp)).limit(H).offset(V)}else return(await this.db.select().from(h).where(D(h.conversationId,f)).orderBy(i(h.timestamp)).limit($)).reverse()}async getConversation(f){return(await this.db.select().from(J).where(D(J.id,f)).limit(1))[0]??null}async listConversations(f={}){let{limit:A=100,updatedAfter:$,interfaceType:Z,sessionId:V,channelId:H,personId:M}=f,X=[$?W0(J.updated,$):void 0,Z?D(J.interfaceType,Z):void 0,V?D(J.sessionId,V):void 0,H?D(J.channelId,H):void 0,M?D(J.personId,M):void 0].filter((F)=>F!==void 0),Y=this.db.select().from(J).orderBy(i(J.lastActive)).limit(A);if(X.length===0)return Y;return Y.where(m(...X))}async searchConversations(f,A){let $=`%${f.toLowerCase()}%`;return(await this.db.selectDistinct({conversation:J}).from(J).leftJoin(h,D(h.conversationId,J.id)).where(A?w`lower(${h.content}) LIKE ${$} AND ${J.sessionId} = ${A}`:w`lower(${h.content}) LIKE ${$}`).orderBy(i(J.lastActive))).map((V)=>V.conversation)}async countMessages(f){let[A]=await this.db.select({count:L0()}).from(h).where(D(h.conversationId,f));return Number(A?.count??0)}async updateConversationMetadata(f){let A=await this.getConversation(f.conversationId);if(!A)return!1;let $=new Date().toISOString(),Z={...ff(A.metadata),...f.metadata};return await this.db.update(J).set({metadata:JSON.stringify(Z),updated:$}).where(D(J.id,f.conversationId)),this.logger.debug("Updated conversation metadata",{conversationId:f.conversationId}),!0}async deleteConversation(f){if(!await this.getConversation(f))return!1;return await this.db.delete(J).where(D(J.id,f)),this.logger.debug("Deleted conversation",{conversationId:f}),!0}async checkAndBroadcastDigest(f,A){let $=await this.countMessages(f),Z=this.config.digestTriggerInterval??10;if($>0&&$%Z===0)await this.broadcastDigest(f,$,A)}async broadcastDigest(f,A,$){let Z=this.config.digestWindowSize??20,V=Math.max(1,A-Z+1),H=A,M=await this.getMessages(f,{range:{start:V,end:H}}),X={conversationId:f,messageCount:A,messages:M,windowStart:V,windowEnd:H,windowSize:M.length,timestamp:$};await this.messageBus.send({type:C0.digest,payload:X,sender:"conversation-service",broadcast:!0}),this.logger.debug("Broadcast conversation digest",{conversationId:f,messageCount:A,windowStart:V,windowEnd:H,windowSize:M.length})}}var oA=U.object({kind:U.string().min(1),id:U.string().min(1)}),D0=U.object({kind:U.literal("text"),filename:U.string().min(1),mediaType:U.string().min(1),content:U.string(),sizeBytes:U.number().nonnegative().optional(),source:oA.optional()}),Y1=U.custom((f)=>f instanceof Uint8Array),L1=U.object({kind:U.literal("file"),filename:U.string().min(1),mediaType:U.string().min(1),data:Y1,sizeBytes:U.number().nonnegative().optional(),source:oA.optional()}),_0=U.discriminatedUnion("kind",[D0,L1]),F1=U.object({userPermissionLevel:U.enum(["admin","trusted","public"]).optional(),isAnchor:U.boolean().optional(),interfaceType:U.string().optional(),channelId:U.string().optional(),channelName:U.string().optional(),actor:Pf.optional(),source:Wf.optional(),attachments:U.array(_0).optional()});var C1=U.object({status:U.enum(["healthy","warning","error","unknown"]),message:U.string().optional(),lastCheck:U.date().optional(),details:U.record(U.string(),U.unknown()).optional()}),B0=U.object({name:U.string(),pluginId:U.string(),status:U.string(),health:C1.optional()});var OH=U.object({id:U.string(),type:U.string(),version:U.string(),status:U.string()}),wH=U.object({name:U.string(),description:U.string()}),k0=U.enum(["admin","trusted","public"]),sf=U.object({label:U.string(),url:U.string(),pluginId:U.string(),priority:U.number().default(100),visibility:k0.default("public")}),O0=U.enum(["human","agent","admin","protocol"]),w0=U.enum(["available","coming-soon","disabled"]),af=U.object({id:U.string(),label:U.string(),description:U.string().optional(),href:U.string(),kind:O0,pluginId:U.string(),priority:U.number().default(100),visibility:k0.default("public"),status:w0.default("available")}),tA=U.object({entityType:U.string(),count:U.number()}),R1=U.object({model:U.string(),version:U.string(),uptime:U.number(),entities:U.number(),entityCounts:U.array(tA),embeddings:U.number(),ai:U.object({model:U.string(),embeddingModel:U.string()}),daemons:U.array(B0),endpoints:U.array(sf),interactions:U.array(af)});var K1=U.object({id:U.string(),version:U.string(),type:U.enum(["core","entity","service","interface"]),description:U.string().optional(),dependencies:U.array(U.string()).optional(),packageName:U.string()});var P1=U.object({status:U.enum(["healthy","warning","error","unknown"]),message:U.string().optional(),lastCheck:U.string().optional(),details:U.record(U.string(),U.unknown()).optional()}),W1=U.object({name:U.string(),pluginId:U.string(),status:U.string(),health:P1.optional()}),D1=U.object({model:U.string(),version:U.string(),uptime:U.number(),entities:U.number(),entityCounts:U.array(tA),embeddings:U.number(),ai:U.object({model:U.string(),embeddingModel:U.string()}),daemons:U.array(W1),endpoints:U.array(sf),interactions:U.array(af)});var x0=U.object({name:U.string().min(1),status:U.enum(["healthy","degraded","unhealthy"]),message:U.string().optional(),details:U.record(U.string(),U.unknown()).optional()}),J0=U.object({totals:U.object({pending:U.number().int().nonnegative(),processing:U.number().int().nonnegative(),completed:U.number().int().nonnegative(),failed:U.number().int().nonnegative()}),byType:U.array(U.object({type:U.string().min(1),status:U.enum(["pending","processing","completed","failed"]),count:U.number().int().nonnegative()})),oldestPendingAgeMs:U.number().nonnegative().nullable(),oldestProcessingAgeMs:U.number().nonnegative().nullable(),staleLeaseCount:U.number().int().nonnegative(),workerSessions:U.object({total:U.number().int().nonnegative(),active:U.number().int().nonnegative(),stale:U.number().int().nonnegative(),latestHeartbeatAgeMs:U.number().nonnegative().nullable()})}),Q0=U.object({memory:U.object({rssBytes:U.number().int().nonnegative(),heapUsedBytes:U.number().int().nonnegative(),heapTotalBytes:U.number().int().nonnegative()}),fileDescriptors:U.number().int().nonnegative().nullable(),processes:U.object({total:U.number().int().nonnegative().nullable(),zombies:U.number().int().nonnegative().nullable()}),queue:J0.nullable(),projection:U.object({initialized:U.boolean(),trackedRoots:U.number().int().nonnegative(),openCircuits:U.array(U.object({projectionId:U.string().min(1),reason:U.string().min(1),openedAt:U.number().int().nonnegative(),expiresAt:U.number().int().nonnegative()}))}),worker:U.object({total:U.number().int().nonnegative(),active:U.number().int().nonnegative(),stale:U.number().int().nonnegative(),latestHeartbeatAgeMs:U.number().nonnegative().nullable()})}),_1=U.object({status:U.enum(["ready","not_ready"]),operationalStatus:U.enum(["operational","degraded"]),checkedAt:U.iso.datetime(),checks:U.array(x0),resources:Q0});class s{callback;heartbeatInterval;constructor(f){this.callback=f}static from(f){if(!f)return;return new s(f)}createSub(f){let{scale:A}=f??{};if(A){let{start:$,end:Z}=A,V=Z-$;return new s(async(H)=>{let M=$+H.progress/(H.total??100)*V;await this.callback({...H,progress:M,total:100})})}return new s(this.callback)}async report(f){await this.callback(f)}startHeartbeat(f,A=5000){this.stopHeartbeat(),this.heartbeatInterval=setInterval(()=>{this.report({message:f,progress:0}).catch(()=>{})},A)}stopHeartbeat(){if(this.heartbeatInterval)clearInterval(this.heartbeatInterval),this.heartbeatInterval=void 0}toCallback(){return this.callback}}var B1=U.object({enabled:U.boolean().describe("Whether the plugin is enabled"),debug:U.boolean().describe("Enable debug logging for this plugin")});class rf extends Error{pluginId;issues;constructor(f,A){super(`Invalid plugin config for ${f}`);this.name="PluginConfigValidationError",this.pluginId=f,this.issues=A}}var k1=U.object({toolName:U.string(),args:U.unknown(),progressToken:U.union([U.string(),U.number()]).optional(),hasProgress:U.boolean().optional(),interfaceType:U.string(),actor:Af,displayName:U.string().optional(),conversationId:U.string().optional(),channelId:U.string().optional(),channelName:U.string().optional(),runId:U.string().optional(),toolCallId:U.string().optional(),userPermissionLevel:U.enum(["admin","trusted","public"]).optional(),isAnchor:U.boolean().optional(),signal:U.custom((f)=>f instanceof AbortSignal).optional()}),O1=U.object({resourceUri:U.string()});class Zf{id;version;description;packageName;config;context;get logger(){return this.context?.logger??of.createFresh({context:this.id})}constructor(f,A,$,Z){this.id=f,this.packageName=A.name,this.version=A.version,this.description=A.description??`${A.name} plugin`;let V=Z.safeParse($);if(!V.success)throw new rf(f,V.error.issues.map((H)=>({path:H.path.map(String).join("."),code:H.code,message:H.message})));this.config=V.data}setupMessageHandlers(f){f.messaging.subscribe(Df.toolExecute(this.id),async(A)=>{try{let $=k1.safeParse(A.payload);if(!$.success)return{success:!1,error:"Invalid tool execution request format"};let{toolName:Z,args:V,progressToken:H,hasProgress:M,interfaceType:X,actor:Y,displayName:F,conversationId:N,channelId:C,channelName:W,runId:_,toolCallId:q,userPermissionLevel:E,isAnchor:I,signal:r}=$.data,c=(await this.getTools()).find((K)=>K.name===Z);if(!c)return{success:!1,error:`Tool not found: ${Z}`};let R={interfaceType:X,actor:Y,...F&&{displayName:F},...N&&{conversationId:N},...C&&{channelId:C},...W&&{channelName:W},..._&&{runId:_},...q&&{toolCallId:q},...E&&{userPermissionLevel:E},...I!==void 0&&{isAnchor:I},...r&&{signal:r},...M&&H!==void 0&&{progressToken:H,sendProgress:async(K)=>{await f.messaging.send({type:Df.progress(this.id),payload:{progressToken:H,notification:K}})}}};return{success:!0,data:await c.handler(V,R)}}catch($){return this.logger.error("Tool execution error",$),{success:!1,error:S($)}}}),f.messaging.subscribe(Df.resourceGet(this.id),async(A)=>{try{let $=O1.safeParse(A.payload);if(!$.success)return{success:!1,error:"Invalid resource get request format"};let{resourceUri:Z}=$.data,H=(await this.getResources()).find((X)=>X.uri===Z);if(!H)return{success:!1,error:`Resource not found: ${Z}`};return{success:!0,data:await H.handler()}}catch($){return this.logger.error("Resource fetch error",$),{success:!1,error:S($)}}})}async onRegister(f){}async onRegistrationComplete(f){}async finalizeRegistration(){await this.onRegistrationComplete(this.getContext())}async onReady(f){}async ready(){await this.onReady(this.getContext())}async getCapabilities(){let f=await this.getInstructions();return{tools:await this.getTools(),resources:await this.getResources(),...f&&{instructions:f}}}async getTools(){return[]}async getResources(){return[]}async getInstructions(){return}async shutdown(){await this.onShutdown()}async onShutdown(){}getContext(){if(!this.context)throw Error(`Plugin ${this.id}: Plugin not registered yet`);return this.context}determineUserPermissionLevel(f){return"public"}createProgressBridge(f){if(!f)return;let A=this.context;if(!A)return;let $=this.id;return s.from(async(Z)=>{await A.messaging.send({type:Df.progress($),payload:{progressToken:f,notification:{progress:Z.progress,total:Z.total,message:Z.message}}})})}}var eA=U.enum(["file_operations","content_operations","data_processing","batch_processing"]),w1=U.object({pluginId:U.string().optional(),progressToken:U.union([U.string(),U.number()]).optional(),operationType:eA,operationTarget:U.string().optional(),interfaceType:U.string().optional(),conversationId:U.string().optional(),channelId:U.string().optional(),requestedByActor:Af.optional(),requestedByUserId:U.string().optional(),requestedByInterface:U.string().optional(),silent:U.boolean().optional(),provenance:Uf.optional()}),Vf=U.object({pluginId:U.string().optional(),progressToken:U.union([U.string(),U.number()]).optional(),operationType:eA,operationTarget:U.string().optional(),interfaceType:U.string().optional(),conversationId:U.string().optional(),channelId:U.string().optional(),requestedByActor:Af.optional(),requestedByUserId:U.string().optional(),requestedByInterface:U.string().optional(),silent:U.boolean().optional(),provenance:Uf.optional(),rootJobId:U.string()}),nH=U.enum(["none","skip","replace","coalesce"]);var f$=U.enum(["pending","processing","completed","failed"]),q0=U.enum(["completed","failed"]),P={PENDING:"pending",PROCESSING:"processing",COMPLETED:"completed",FAILED:"failed"},x1=U.object({id:U.string(),type:U.string(),status:f$,data:U.unknown(),result:U.unknown().optional(),lastError:U.string().optional().nullable(),attempts:U.number(),maxRetries:U.number(),priority:U.number(),createdAt:U.date(),updatedAt:U.date(),processedAt:U.date().optional().nullable(),completedAt:U.date().optional().nullable(),failedAt:U.date().optional().nullable()}),J1=U.object({jobId:U.string(),type:U.string(),status:q0,result:U.unknown().optional(),error:U.string().optional()}),A$=U.object({success:U.literal(!1),error:U.string().optional()}),tf=U.object({id:U.string(),type:U.enum(["job","batch"]),status:f$,message:U.string().optional(),progress:U.object({current:U.number(),total:U.number(),percentage:U.number()}).optional(),aggregationKey:U.string().optional(),batchDetails:U.object({totalOperations:U.number(),completedOperations:U.number(),failedOperations:U.number(),currentOperation:U.string().optional(),errors:U.array(U.string()).optional()}).optional(),jobDetails:U.object({jobType:U.string(),priority:U.number(),retryCount:U.number()}).optional(),metadata:Vf});var L=t("job_queue",{id:k("id").primaryKey().$defaultFn(()=>g()),type:k("type").notNull(),data:k("data").notNull(),result:k("result",{mode:"json"}),progress:k("progress",{mode:"json"}).$type(),source:k("source"),metadata:k("metadata",{mode:"json"}).$type().notNull(),status:k("status",{enum:["pending","processing","completed","failed"]}).notNull().default("pending"),priority:j("priority").notNull().default(0),retryCount:j("retryCount").notNull().default(0),maxRetries:j("maxRetries").notNull().default(3),lastError:k("lastError"),createdAt:j("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:j("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:j("startedAt"),completedAt:j("completedAt"),attemptId:k("attemptId"),workerSlotId:k("workerSlotId"),workerSessionId:k("workerSessionId"),leaseExpiresAt:j("leaseExpiresAt"),attemptHeartbeatAt:j("attemptHeartbeatAt"),runtimeUpdatedAt:j("runtimeUpdatedAt")},(f)=>({queueReadyIdx:b("idx_job_queue_ready").on(f.status,f.priority,f.scheduledFor),jobTypeIdx:b("idx_job_queue_type").on(f.type,f.status),runtimeUpdatesIdx:b("idx_job_queue_runtime_updates").on(f.runtimeUpdatedAt,f.id),jobSourceIdx:b("idx_job_queue_source").on(f.source)})),O=t("job_worker_sessions",{slotId:k("slotId").primaryKey(),sessionId:k("sessionId").notNull().unique(),startedAt:j("startedAt").notNull(),heartbeatAt:j("heartbeatAt").notNull()},(f)=>({heartbeatIdx:b("idx_job_worker_sessions_heartbeat").on(f.heartbeatAt)}));function T0(f){return gf({url:f.url,schema:{jobQueue:L,jobWorkerSessions:O},authToken:f.authToken,authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN"})}class $${declarations=new Map;handlers=new Map;validators=new Map;logger;mode;finalizedRegistrations;constructor(f,A){this.logger=f.child("HandlerRegistry"),this.mode=A}registerHandler(f,A,$){if(this.finalizedRegistrations)throw Error("Job handler registrations are finalized");if(this.declarations.has(f))throw Error(`Job handler is already registered for type: ${f}`);if(this.declarations.set(f,{handler:A,pluginId:$}),this.validators.set(f,A),this.mode!=="validation-only")this.handlers.set(f,A);this.logger.debug("Registered job execution declaration",{type:f,pluginId:$,mode:this.mode})}unregisterHandler(f){this.declarations.delete(f),this.handlers.delete(f),this.validators.delete(f),this.logger.debug("Unregistered job handler",{type:f})}unregisterPluginHandlers(f){let A=[...this.declarations.entries()].filter(([,$])=>$.pluginId===f).map(([$])=>$);for(let $ of A)this.declarations.delete($),this.handlers.delete($),this.validators.delete($);if(A.length>0)this.logger.debug("Unregistered plugin handlers",{pluginId:f,count:A.length,types:A})}finalizeRegistrations(){return this.finalizedRegistrations??=Object.freeze([...this.declarations.entries()].sort(([f],[A])=>f.localeCompare(A)).map(([f,A])=>Object.freeze({type:f,pluginId:A.pluginId}))),this.finalizedRegistrations}getExecutionRegistrations(){if(!this.finalizedRegistrations)throw Error("Job handler registrations are not finalized");return this.finalizedRegistrations}getRegisteredTypes(){return[...this.handlers.keys()]}getHandler(f){return this.handlers.get(f)}getValidator(f){return this.validators.get(f)}}var Q1=U.object({id:U.string(),type:U.string(),data:U.string(),status:U.enum(["pending","processing","completed","failed"]),source:U.string().nullable(),priority:U.number(),retryCount:U.number(),maxRetries:U.number(),lastError:U.string().nullable(),createdAt:U.number(),scheduledFor:U.number(),startedAt:U.number().nullable(),completedAt:U.number().nullable(),attemptId:U.string().nullable(),workerSlotId:U.string().nullable(),workerSessionId:U.string().nullable(),leaseExpiresAt:U.number().nullable(),attemptHeartbeatAt:U.number().nullable(),runtimeUpdatedAt:U.number().nullable(),metadata:Vf,progress:U.custom((f)=>typeof f==="object"&&f!==null&&("progress"in f)&&typeof f.progress==="number").nullable(),result:U.unknown().nullable().optional()}),_f=15000;class V${db;logger;constructor(f,A){this.db=f,this.logger=A.child("JobQueueRepository")}async insert(f){await this.db.insert(L).values(f)}async startWorkerSession(f,A,$=Date.now()){await this.db.insert(O).values({slotId:f,sessionId:A,startedAt:$,heartbeatAt:$}).onConflictDoUpdate({target:O.slotId,set:{sessionId:A,startedAt:$,heartbeatAt:$}})}async heartbeatWorkerSession(f,A,$=Date.now()){return(await this.db.update(O).set({heartbeatAt:$}).where(m(D(O.slotId,f),D(O.sessionId,A))).returning({slotId:O.slotId})).length===1}async endWorkerSession(f,A){return(await this.db.delete(O).where(m(D(O.slotId,f),D(O.sessionId,A))).returning({slotId:O.slotId})).length===1}async markTerminallyFailed(f,A){let $=Date.now();await this.db.update(L).set({status:P.FAILED,lastError:A,completedAt:$,runtimeUpdatedAt:this.nextRuntimeUpdatedAt($)}).where(m(D(L.id,f),D(L.status,P.PENDING)))}async setScheduledFor(f,A){await this.db.update(L).set({scheduledFor:A}).where(D(L.id,f))}async complete(f,A,$){let Z=Date.now(),H=(await this.db.update(L).set({status:P.COMPLETED,result:A,lastError:null,completedAt:Z,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(Z)}).where(this.attemptWriteGuard(f,$)).returning({id:L.id})).length===1;if(H)this.logger.debug("Job completed",{jobId:f,hasResult:A!==void 0});return H}async update(f,A,$){let V=(await this.db.update(L).set({data:JSON.stringify(A)}).where(this.attemptWriteGuard(f,$)).returning({id:L.id})).length===1;if(V)this.logger.debug("Job data updated",{jobId:f});return V}async recordAttemptProgress(f,A,$,Z=Date.now()){return(await this.db.update(L).set({attemptHeartbeatAt:Z,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(Z),progress:$}).where(this.attemptWriteGuard(f,A)).returning({id:L.id})).length===1}async renewAttemptLease(f,A,$,Z){return(await this.db.update(L).set({attemptHeartbeatAt:$,leaseExpiresAt:$+Z}).where(this.attemptWriteGuard(f,A)).returning({id:L.id})).length===1}async fail(f,A,$,Z=Date.now()){let H=(await this.db.select({retryCount:L.retryCount,maxRetries:L.maxRetries,type:L.type,scheduledFor:L.scheduledFor,startedAt:L.startedAt,runtimeUpdatedAt:L.runtimeUpdatedAt}).from(L).where(this.attemptWriteGuard(f,$)).limit(1))[0];if(!H)return!1;let M=H.retryCount<H.maxRetries,X=M?H.retryCount+1:H.retryCount,Y=Math.min(1000*2**H.retryCount,60000),F=M?Z+Y:H.scheduledFor;if((await this.db.update(L).set({status:M?P.PENDING:P.FAILED,retryCount:X,lastError:A.message,scheduledFor:F,completedAt:M?null:Z,runtimeUpdatedAt:M?H.runtimeUpdatedAt:this.nextRuntimeUpdatedAt(Z),startedAt:M?null:H.startedAt,attemptId:null,workerSlotId:null,workerSessionId:null,leaseExpiresAt:null,attemptHeartbeatAt:null}).where(m(this.attemptWriteGuard(f,$),D(L.retryCount,H.retryCount))).returning({id:L.id})).length!==1)return!1;if(M)this.logger.debug("Job scheduled for retry",{jobId:f,retryCount:X,backoffMs:Y,scheduledFor:new Date(F).toISOString()});else this.logger.error("Job failed after max retries",{jobId:f,type:H.type,retryCount:H.retryCount,error:A.message});return!0}async getStatus(f){return(await this.db.select().from(L).where(D(L.id,f)).limit(1))[0]??null}async getStatusByEntityId(f){return(await this.db.select().from(L).where(w`json_extract(${L.data}, '$.id') = ${f}`).orderBy(i(L.createdAt)).limit(1))[0]??null}async getStats(){let f=await this.db.select({status:L.status,count:w`count(*)`}).from(L).groupBy(L.status),A={pending:0,processing:0,failed:0,completed:0,total:0};for(let $ of f){let Z=Number($.count);A[$.status]=Z,A.total+=Z}return A}async getDiagnostics(f=Date.now()){let A=f-_f,[$,Z,V]=await Promise.all([this.db.select({type:L.type,status:L.status,count:w`count(*)`}).from(L).groupBy(L.type,L.status),this.db.select({oldestPendingAt:w`min(case when ${L.status} = ${P.PENDING} then ${L.createdAt} end)`,oldestProcessingAt:w`min(case when ${L.status} = ${P.PROCESSING} then ${L.startedAt} end)`,staleLeaseCount:w`coalesce(sum(case when ${L.status} = ${P.PROCESSING} and ${L.leaseExpiresAt} is not null and ${L.leaseExpiresAt} <= ${f} then 1 else 0 end), 0)`}).from(L),this.db.select({total:w`count(*)`,active:w`coalesce(sum(case when ${O.heartbeatAt} > ${A} then 1 else 0 end), 0)`,stale:w`coalesce(sum(case when ${O.heartbeatAt} <= ${A} then 1 else 0 end), 0)`,latestHeartbeatAt:w`max(${O.heartbeatAt})`}).from(O)]),H={pending:0,processing:0,completed:0,failed:0},M=$.map((N)=>{let C=Number(N.count);return H[N.status]+=C,{type:N.type,status:N.status,count:C}}),X=Z[0],Y=V[0],F=(N)=>N===null||N===void 0?null:Math.max(0,f-Number(N));return{totals:H,byType:M,oldestPendingAgeMs:F(X?.oldestPendingAt),oldestProcessingAgeMs:F(X?.oldestProcessingAt),staleLeaseCount:Number(X?.staleLeaseCount??0),workerSessions:{total:Number(Y?.total??0),active:Number(Y?.active??0),stale:Number(Y?.stale??0),latestHeartbeatAgeMs:F(Y?.latestHeartbeatAt)}}}async getRuntimeUpdates(f,A){return(await this.db.select().from(L).where(w`(${L.runtimeUpdatedAt}, ${L.id}) > (${f.updatedAt}, ${f.jobId})`).orderBy($f(L.runtimeUpdatedAt),$f(L.id)).limit(A)).map((Z)=>({job:Z,cursor:{updatedAt:Z.runtimeUpdatedAt??0,jobId:Z.id}}))}async cleanup(f){let A=Date.now()-f;return(await this.db.delete(L).where(m(Ff(D(L.status,P.COMPLETED),D(L.status,P.FAILED)),Bf(L.completedAt,A)))).rowsAffected}async getActiveJobs(f){let A=Ff(D(L.status,P.PENDING),D(L.status,P.PROCESSING)),$=f&&f.length>0?m(A,kf(L.type,f)):A;return this.db.select().from(L).where($).orderBy(i(L.createdAt))}async getFailedJobs(f){let A=D(L.status,P.FAILED),$=f&&f.length>0?m(A,kf(L.type,f)):A;return this.db.select().from(L).where($).orderBy(i(L.createdAt))}async claimNextReady(f){let{now:A,attemptId:$,workerSlotId:Z,workerSessionId:V,leaseDurationMs:H,workerSessionTimeoutMs:M,executableTypes:X}=f,Y=A-M,F=this.db.select({slotId:O.slotId}).from(O).where(m(D(O.slotId,Z),D(O.sessionId,V))),N=this.db.select({slotId:O.slotId}).from(O).where(m(D(O.slotId,L.workerSlotId),D(O.sessionId,L.workerSessionId))),C=this.db.select({slotId:O.slotId}).from(O).where(m(D(O.slotId,L.workerSlotId),D(O.sessionId,L.workerSessionId),Bf(O.heartbeatAt,Y))),W=m(D(L.status,P.PROCESSING),Ff(Z$(L.attemptId),E0(N),m(Bf(L.leaseExpiresAt,A),U$(C)))),_=w`${L.status} = ${P.PROCESSING} AND ${L.retryCount} + 1 > ${L.maxRetries}`,q=this.db.select({id:L.id}).from(L).where(m(kf(L.type,X),Ff(m(D(L.status,P.PENDING),Bf(L.scheduledFor,A)),W))).orderBy($f(L.priority),$f(L.createdAt)).limit(1),I=(await this.db.update(L).set({status:w`CASE WHEN ${_} THEN ${P.FAILED} ELSE ${P.PROCESSING} END`,retryCount:w`CASE WHEN ${L.status} = ${P.PROCESSING} THEN ${L.retryCount} + 1 ELSE ${L.retryCount} END`,lastError:w`CASE WHEN ${L.status} = ${P.PROCESSING} THEN 'Attempt lease expired' ELSE ${L.lastError} END`,startedAt:w`CASE WHEN ${_} THEN ${L.startedAt} ELSE ${A} END`,completedAt:w`CASE WHEN ${_} THEN ${A} ELSE NULL END`,attemptId:w`CASE WHEN ${_} THEN ${L.attemptId} ELSE ${$} END`,workerSlotId:w`CASE WHEN ${_} THEN ${L.workerSlotId} ELSE ${Z} END`,workerSessionId:w`CASE WHEN ${_} THEN ${L.workerSessionId} ELSE ${V} END`,leaseExpiresAt:w`CASE WHEN ${_} THEN ${L.leaseExpiresAt} ELSE ${A+H} END`,attemptHeartbeatAt:w`CASE WHEN ${_} THEN ${L.attemptHeartbeatAt} ELSE ${A} END`,runtimeUpdatedAt:w`CASE WHEN ${_} THEN ${this.nextRuntimeUpdatedAt(A)} ELSE ${L.runtimeUpdatedAt} END`}).where(m(kf(L.id,q),U$(F))).returning())[0];if(I?.status!==P.PROCESSING)return null;return this.logger.debug("Job claimed",{jobId:I.id,attemptId:I.attemptId,workerSlotId:Z,workerSessionId:V}),I}nextRuntimeUpdatedAt(f){return w`max(${f}, coalesce((select max(${L.runtimeUpdatedAt}) from ${L}), 0) + 1)`}attemptWriteGuard(f,A){return A?m(D(L.id,f),D(L.status,P.PROCESSING),D(L.attemptId,A)):m(D(L.id,f),Z$(L.attemptId),Ff(D(L.status,P.PENDING),D(L.status,P.PROCESSING)))}}var q1=U.looseObject({deduplicationKey:U.string().optional()});class H${findDuplicate(f,A,$){if(!A||A==="none")return null;let Z=this.filterByDeduplicationKey(f,$);if(Z.length===0)return null;if(A==="skip"||A==="replace")return Z.find((V)=>V.status===P.PENDING)??null;return Z[0]??null}filterByDeduplicationKey(f,A){if(!A)return f;return f.filter(($)=>{let Z=q1.safeParse($.metadata);return Z.success&&Z.data.deduplicationKey===A})}}import{AsyncLocalStorage as T1}from"async_hooks";class Cf{storage=new T1;static createFresh(){return new Cf}constructor(){}current(){return this.storage.getStore()}run(f,A,$){if(A.length===0)throw Error("Operation ID must not be empty");let Z=Uf.parse(f),V=E1(Z);return this.storage.run(Object.freeze({provenance:V,operationId:A}),$)}}function E1(f){if(Object.freeze(f.projectionLineage),f.sourceEntity)Object.freeze(f.sourceEntity);return Object.freeze(f)}class M${client;logger;handlerRegistry;repository;deduplicator;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;databaseUrl;operationContext;projectionAdmission;directWorkerSlotId=`direct:${g()}`;directWorkerSessionId=g();directLeaseDurationMs;directSessionStart=null;close(){if(this.closeRequested=!0,!this.walInitialization||this.walInitializationSettled)this.closeClient()}static createFresh(f,A,$){return new M$(f,A??of.getInstance(),$)}constructor(f,A,$){let{db:Z,client:V,url:H}=T0(f);this.client=V,this.databaseUrl=H,this.logger=A.child("JobQueueService"),this.operationContext=$?.operationContext??Cf.createFresh(),this.projectionAdmission=$?.projectionAdmission,this.handlerRegistry=new $$(this.logger,$?.handlerRegistrationMode??"combined"),this.repository=new V$(Z,this.logger),this.directLeaseDurationMs=f.claimTimeoutMs??300000,this.deduplicator=new H$}initialize(){if(this.closeRequested)return Promise.resolve();return this.walInitialization??=this.initializeWALMode(),this.walInitialization}async initializeWALMode(){try{await pf(this.client,this.databaseUrl)}catch(f){this.logger.warn("Failed to enable WAL mode (non-fatal)",f)}finally{if(this.walInitializationSettled=!0,this.closeRequested)this.closeClient()}}closeClient(){if(this.clientClosed)return;this.clientClosed=!0,this.client.close()}registerHandler(f,A,$){this.handlerRegistry.registerHandler(f,A,$)}unregisterHandler(f){this.handlerRegistry.unregisterHandler(f)}unregisterPluginHandlers(f){this.handlerRegistry.unregisterPluginHandlers(f)}getRegisteredTypes(){return this.handlerRegistry.getRegisteredTypes()}getHandler(f){return this.handlerRegistry.getHandler(f)}getValidator(f){return this.handlerRegistry.getValidator(f)}finalizeHandlerRegistrations(){return this.handlerRegistry.finalizeRegistrations()}getExecutionRegistrations(){return this.handlerRegistry.getExecutionRegistrations()}async checkForDuplicate(f,A,$){let Z=await this.getActiveJobs([f]);return this.deduplicator.findDuplicate(Z,A,$)}async enqueue(f){let{type:A,data:$,options:Z}=f,V=await this.checkForDuplicate(A,Z?.deduplication,Z?.deduplicationKey);if(V){if(Z?.deduplication==="skip")return this.logger.debug("Skipping duplicate job (already pending)",{type:A,existingJobId:V.id}),V.id;if(Z?.deduplication==="replace")this.logger.debug("Replacing duplicate job",{type:A,oldJobId:V.id}),await this.repository.markTerminallyFailed(V.id,"Replaced by newer job");if(Z?.deduplication==="coalesce")return this.logger.debug("Coalescing with existing job",{type:A,existingJobId:V.id}),await this.repository.setScheduledFor(V.id,Date.now()),V.id}let H=this.handlerRegistry.getValidator(A);if(!H)throw Error(`No job type declared: ${A}`);let M=H.validateAndParse($);if(M===null)throw Error(`Invalid job data for type: ${A}`);let X=Date.now(),Y=g(),F=Z?.rootJobId??this.operationContext.current()?.provenance.rootJobId??Y,N=this.createJobProvenance(Y,F,Z);await this.projectionAdmission?.assertJobAdmission(N);let{provenance:C,...W}=Z?.metadata??{operationType:"data_processing"},_={id:Y,type:A,data:JSON.stringify(M),status:P.PENDING,priority:Z?.priority??0,maxRetries:Z?.maxRetries??3,retryCount:0,source:Z?.source??null,metadata:{...W,...Z?.deduplicationKey&&{deduplicationKey:Z.deduplicationKey},rootJobId:F,provenance:N},createdAt:X,scheduledFor:Z?.delayMs?X+Z.delayMs:X,result:null,lastError:null,startedAt:null,completedAt:null};try{return await this.repository.insert(_),this.logger.debug("Job enqueued",{id:Y,type:A,priority:_.priority,rootJobId:_.metadata.rootJobId}),Y}catch(q){throw this.logger.error("Failed to enqueue job",{type:A,error:S(q)}),q}}createJobProvenance(f,A,$){let Z=this.operationContext.current(),V=$?.metadata.provenance??Z?.provenance,H=V?.rootJobId===A?V:void 0,M=Z?.provenance.rootJobId===A?Z.operationId:void 0,X=$?.projection,Y=X?[...H?.projectionLineage??[],X.id]:[...H?.projectionLineage??[]],F=X?.id??H?.projectionId;return Uf.parse({rootJobId:A,causationId:M??H?.causationId??f,...F?{projectionId:F}:{},projectionLineage:Y,...X?.sourceEntity?{sourceEntity:X.sourceEntity}:H?.sourceEntity?{sourceEntity:H.sourceEntity}:{},derivationDepth:Y.length})}async dequeue(f){let A=this.handlerRegistry.getRegisteredTypes();if(A.length===0)return null;let $=f??await this.getDirectClaimOptions(),Z=Date.now(),V=await this.repository.claimNextReady({...$,now:Z,attemptId:g(),executableTypes:A});if(!V)return null;return this.logger.debug("Job dequeued",{id:V.id,type:V.type,priority:V.priority,retryCount:V.retryCount,attemptId:V.attemptId,workerSlotId:V.workerSlotId,workerSessionId:V.workerSessionId}),V}async startWorkerSession(f,A){await this.repository.startWorkerSession(f,A)}heartbeatWorkerSession(f,A){return this.repository.heartbeatWorkerSession(f,A)}endWorkerSession(f,A){return this.repository.endWorkerSession(f,A)}renewAttemptLease(f,A,$){return this.repository.renewAttemptLease(f,A,Date.now(),$)}recordAttemptProgress(f,A,$){return this.repository.recordAttemptProgress(f,A,$)}complete(f,A,$){return this.repository.complete(f,A,$)}update(f,A,$){return this.repository.update(f,A,$)}fail(f,A,$){return this.repository.fail(f,A,$)}async getDirectClaimOptions(){return this.directSessionStart??=this.repository.startWorkerSession(this.directWorkerSlotId,this.directWorkerSessionId),await this.directSessionStart,{workerSlotId:this.directWorkerSlotId,workerSessionId:this.directWorkerSessionId,leaseDurationMs:this.directLeaseDurationMs,workerSessionTimeoutMs:this.directLeaseDurationMs}}async getStatus(f){return this.repository.getStatus(f)}async getStatusByEntityId(f){return this.repository.getStatusByEntityId(f)}async getStats(){return this.repository.getStats()}getDiagnostics(f){return this.repository.getDiagnostics(f)}getRuntimeUpdates(f,A=1000){return this.repository.getRuntimeUpdates(f,A)}async cleanup(f){let A=await this.repository.cleanup(f);if(A>0)this.logger.info("Cleaned up old jobs",{deletedCount:A,olderThanMs:f});return A}async getActiveJobs(f){return this.repository.getActiveJobs(f)}async getFailedJobs(f){return this.repository.getFailedJobs(f)}}class m0 extends Error{constructor(f,A){super(`Job ${f} exceeded its ${A}ms execution deadline`);this.name="JobDeadlineExceededError"}}class X${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;workerSessionId=null;workerHeartbeatTimer=null;workerHeartbeatInFlight=null;static createFresh(f,A,$,Z,V){return new X$(f,A,$,Z,V)}constructor(f,A,$,Z,V){if(this.logger=$.child("JobQueueWorker"),this.jobQueueService=f,this.progressMonitor=A,this.clock=V?.clock,this.operationContext=V?.operationContext??Cf.createFresh(),this.config={concurrency:Z?.concurrency??1,pollInterval:Z?.pollInterval??1000,maxJobs:Z?.maxJobs??0,autoStart:Z?.autoStart??!1,workerSlotId:Z?.workerSlotId??process.env.BRAIN_JOB_WORKER_SLOT_ID??"default",defaultExecutionTimeoutMs:Z?.defaultExecutionTimeoutMs??300000,cancellationGraceMs:Z?.cancellationGraceMs??5000,errorCallbackTimeoutMs:Z?.errorCallbackTimeoutMs??1e4,leaseDurationMs:Z?.leaseDurationMs??30000,attemptHeartbeatIntervalMs:Z?.attemptHeartbeatIntervalMs??1e4,workerHeartbeatIntervalMs:Z?.workerHeartbeatIntervalMs??5000,workerSessionTimeoutMs:Z?.workerSessionTimeoutMs??_f,onUnhealthy:Z?.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((H)=>{this.logger.error("Failed to auto-start JobQueueWorker",{error:H})})}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 f=g();await this.jobQueueService.startWorkerSession(this.config.workerSlotId,f),this.workerSessionId=f,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=G.runSync(v.make()),this.jobFibers=G.runSync(v.extend(Hf.make(),this.workerScope)),this.pollFiber=G.runFork(this.runPollingLoop())}stop(){return this.requestTransition("stop",!0)}async stopWorker(f){if(!this.isRunning){this.logger.warn("Worker is not running");return}if(this.logger.debug("Stopping JobQueueWorker"),this.shouldStop=!0,f.awaitInFlightPoll&&this.pollFiber){let $=this.pollFiber;await G.runPromise(ef.interrupt($)),this.pollFiber=null}if(f.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 G.runPromise(Hf.awaitEmpty(this.jobFibers));await this.closeWorkerScope(),await this.stopWorkerHeartbeat();let A=this.workerSessionId;if(this.workerSessionId=null,A)await this.jobQueueService.endWorkerSession(this.config.workerSlotId,A);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 f=this.config.concurrency-this.activeJobs.size;if(f<=0)return;if(this.config.maxJobs>0){let Z=this.stats.processedJobs+this.stats.failedJobs,V=this.config.maxJobs-Z-this.activeJobs.size;if(V<=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}f=Math.min(f,V)}let A=[];for(let Z=0;Z<f;Z++){if(this.isStopRequested())break;let V=this.workerSessionId;if(!V)throw Error("Worker session is not available");let H=await this.jobQueueService.dequeue({workerSlotId:this.config.workerSlotId,workerSessionId:V,leaseDurationMs:this.config.leaseDurationMs,workerSessionTimeoutMs:this.config.workerSessionTimeoutMs});if(H)A.push(H);else break}let $=this.jobFibers;if(!$){if(A.length>0)throw Error("Worker job fiber scope is not available");return}for(let Z of A)this.activeJobs.add(Z.id),await G.runPromise(Hf.run($,Z.id,G.promise(()=>this.processJobWrapper(Z))))}catch(f){this.logger.error("Error processing available jobs",{error:f}),this.stats.lastError=S(f)}}async processJobWrapper(f){let A=f.id;try{this.logger.debug("Processing job",{jobId:A,type:f.type,priority:f.priority,retryCount:f.retryCount});let $=await this.processJob(f);if($.status==="completed")this.stats.processedJobs++,this.logger.debug("Job completed successfully",{jobId:A,type:$.type});else this.stats.failedJobs++,this.logger.warn("Job failed",{jobId:A,type:$.type,error:$.error})}catch($){this.stats.failedJobs++,this.logger.error("Error processing job",{jobId:A,type:f.type,error:$}),this.stats.lastError=S($)}finally{this.activeJobs.delete(A)}}runPollingLoop(){let A=G.suspend(()=>{if(!this.isWorkerRunning()||this.isStopRequested())return G.interrupt;return this.currentPoll=this.processAvailableJobs(),G.promise(()=>this.currentPoll??Promise.resolve()).pipe(G.andThen(G.suspend(()=>{return this.currentPoll=null,!this.isWorkerRunning()||this.isStopRequested()?G.interrupt:G.void})))}).pipe(G.schedule(fA.spaced(this.config.pollInterval)),G.asVoid);return(this.clock?G.withClock(A,this.clock):A).pipe(G.ensuring(G.sync(()=>{this.pollFiber=null})))}requestTransition(f,A){let $=this.transitionQueue.at(-1)??this.activeTransition;if($?.kind===f)return $.promise;let Z=()=>{return},V=()=>{return},H=new Promise((X,Y)=>{Z=X,V=Y}),M={kind:f,awaitInFlightPoll:A,promise:H,resolve:Z,reject:V};return this.transitionQueue.push(M),this.runNextTransition(),H}runNextTransition(){if(this.activeTransition)return;let f=this.transitionQueue.shift();if(!f)return;this.activeTransition=f,(f.kind==="start"?this.startWorker():this.stopWorker({awaitInFlightPoll:f.awaitInFlightPoll})).then(()=>this.completeTransition(f,!0),($)=>this.completeTransition(f,!1,$))}completeTransition(f,A,$){if(this.activeTransition!==f)return;if(this.activeTransition=null,A)f.resolve();else f.reject($);queueMicrotask(()=>this.runNextTransition())}async closeWorkerScope(){let f=this.workerScope;if(this.workerScope=null,this.jobFibers=null,f)await G.runPromise(v.close(f,u.void))}startWorkerHeartbeat(){this.workerHeartbeatTimer=setInterval(()=>{let f=this.workerSessionId;if(!f||this.workerHeartbeatInFlight)return;this.workerHeartbeatInFlight=this.jobQueueService.heartbeatWorkerSession(this.config.workerSlotId,f).then((A)=>{if(!A)this.markUnhealthy("Worker session was superseded")}).catch((A)=>{this.markUnhealthy(`Worker session heartbeat failed: ${S(A)}`)}).finally(()=>{this.workerHeartbeatInFlight=null})},Math.max(1,this.config.workerHeartbeatIntervalMs))}async stopWorkerHeartbeat(){if(this.workerHeartbeatTimer)clearInterval(this.workerHeartbeatTimer),this.workerHeartbeatTimer=null;await this.workerHeartbeatInFlight,this.workerHeartbeatInFlight=null}startAttemptHeartbeat(f,A){let $=f.attemptId;if(!$)return async()=>{return};let Z=null,V=!1,H=setInterval(()=>{if(V||Z)return;Z=this.jobQueueService.renewAttemptLease(f.id,$,this.config.leaseDurationMs).then((M)=>{if(M)return;let X=Error("Job attempt was superseded");A.abort(X),this.markUnhealthy(X.message)}).catch((M)=>{let X=Nf(M);A.abort(X),this.markUnhealthy(`Attempt lease heartbeat failed: ${X.message}`)}).finally(()=>{Z=null})},Math.max(1,this.config.attemptHeartbeatIntervalMs));return async()=>{if(V)return;V=!0,clearInterval(H),await Z}}markUnhealthy(f){if(!this.stats.isHealthy)return;this.stats.isHealthy=!1,this.stats.unhealthyReason=f,this.stats.lastError=f,this.shouldStop=!0,this.logger.error("Job queue worker is unhealthy",{reason:f});try{this.config.onUnhealthy(f)}catch(A){this.logger.error("Job queue worker unhealthy callback failed",{reason:f,error:S(A)})}}async executeWithDeadline(f,A,$,Z){let V=Promise.resolve().then(Z).then((W)=>({kind:"success",value:W}),(W)=>({kind:"failure",error:W})),H,M=new Promise((W)=>{H=setTimeout(()=>W({kind:"deadline"}),Math.max(1,A))}),X=await Promise.race([V,M]);if(X.kind!=="deadline"){if(H)clearTimeout(H);if(X.kind==="failure")throw X.error;return X.value}let Y=new m0(f,A);$.abort(Y);let F,N=new Promise((W)=>{F=setTimeout(()=>W({kind:"grace-expired"}),Math.max(1,this.config.cancellationGraceMs))});if((await Promise.race([V,N])).kind!=="grace-expired"){if(F)clearTimeout(F);throw Y}throw this.markUnhealthy(`${Y.message}; handler ignored cancellation grace`),await V,Y}processJob(f){let A=f.metadata.provenance??{rootJobId:f.metadata.rootJobId,causationId:f.id,projectionLineage:[],derivationDepth:0};return this.operationContext.run(A,f.id,()=>this.processJobWithinContext(f))}async processJobWithinContext(f){let A=f.attemptId;if(!A){let X=Error(`Claimed job ${f.id} has no attempt fencing token`);return this.markUnhealthy(X.message),{jobId:f.id,type:f.type,status:P.FAILED,error:X.message}}let $=this.jobQueueService.getHandler(f.type);if(!$){let X=Error(`No handler registered for job type: ${f.type}`);return await this.jobQueueService.fail(f.id,X,A),{jobId:f.id,type:f.type,status:P.FAILED,error:X.message}}let Z=new AbortController,V=this.startAttemptHeartbeat(f,Z),H=!1,M=async()=>{if(H)return;H=!0,await V()};try{this.logger.debug("Processing job",{jobId:f.id,type:f.type,attemptId:A});let X=JSON.parse(f.data),Y=$.validateAndParse(X);if(Y===null)throw Error(`Invalid job data for type: ${f.type}`);let F=this.progressMonitor.createProgressReporter(f.id,A),N=$.executionTimeoutMs??this.config.defaultExecutionTimeoutMs,C=await this.executeWithDeadline(f.type,N,Z,()=>$.process(Y,f.id,F,Z.signal));await M();let W=A$.safeParse(C);if(W.success){let q=W.data.error??"Handler returned failure",E=Error(q);if(await this.jobQueueService.fail(f.id,E,A))await this.emitTerminalFailure(f,E,$,A);return{jobId:f.id,type:f.type,status:P.FAILED,error:q}}if(!await this.jobQueueService.complete(f.id,C,A))return{jobId:f.id,type:f.type,status:P.FAILED,error:"Job attempt no longer owns the claim"};return await this.progressMonitor.handleJobStatusChange(f.id,"completed",f.metadata),{jobId:f.id,type:f.type,status:P.COMPLETED,result:C}}catch(X){let Y=Nf(X);await M();try{let N=JSON.parse(f.data),C=$.validateAndParse(N);if(C!==null&&$.onError){let W=this.progressMonitor.createProgressReporter(f.id,A),_=new AbortController;await this.executeWithDeadline(`${f.type}:onError`,this.config.errorCallbackTimeoutMs,_,()=>$.onError?.(Y,C,f.id,W,_.signal)??Promise.resolve())}}catch(N){this.logger.error("Job handler error callback failed",{jobId:f.id,error:N})}if(await this.jobQueueService.fail(f.id,Y,A))await this.emitTerminalFailure(f,Y,$,A);return{jobId:f.id,type:f.type,status:P.FAILED,error:Y.message}}}async emitTerminalFailure(f,A,$,Z){if((await this.jobQueueService.getStatus(f.id))?.status!==P.FAILED)return;if($.onTerminalError)try{let H=$.validateAndParse(JSON.parse(f.data));if(H!==null){let M=this.progressMonitor.createProgressReporter(f.id,Z),X=new AbortController;await this.executeWithDeadline(`${f.type}:onTerminalError`,this.config.errorCallbackTimeoutMs,X,()=>$.onTerminalError?.(A,H,f.id,M,X.signal)??Promise.resolve())}}catch(H){this.logger.error("Job handler terminal error callback failed",{jobId:f.id,error:H})}await this.progressMonitor.handleJobStatusChange(f.id,"failed",f.metadata)}}var m1=86400000,S0=3600000;class Y${jobQueue;logger;batches=new Map;cleanupFiber=null;cleanupSupervisor=null;inFlightCleanups=new Set;activeTransition=null;transitionQueue=[];acceptingCleanup=!0;clock;static createFresh(f,A,$){return new Y$(f,A,$)}constructor(f,A,$){this.jobQueue=f,this.logger=A,this.clock=$?.clock}start(f=S0){return this.requestTransition("start",f)}stop(){return this.requestTransition("stop",S0)}async startCleanup(f){if(this.acceptingCleanup=!0,this.cleanupFiber)return;this.cleanupFiber=G.runFork(this.runCleanupLoop(f))}runCleanupLoop(f){let A=this.cleanupTerminalBatchMetadata().pipe(G.schedule(fA.spaced(f)),G.asVoid);return this.clock?G.withClock(A,this.clock):A}scheduleTerminalBatchCleanup(){if(!this.acceptingCleanup)return;this.cleanupSupervisor??=this.createCleanupSupervisor();let f=G.runFork(this.cleanupTerminalBatchMetadata());AA.unsafeAdd(this.cleanupSupervisor.fibers,f)}async stopCleanup(){this.acceptingCleanup=!1;let f=this.cleanupFiber;if(this.cleanupFiber=null,f)await G.runPromise(ef.interrupt(f));let A=this.cleanupSupervisor;if(A)await G.runPromise(AA.awaitEmpty(A.fibers));while(this.inFlightCleanups.size>0)await Promise.allSettled(this.inFlightCleanups);if(A)await G.runPromise(v.close(A.scope,u.void)),this.cleanupSupervisor=null}requestTransition(f,A){let $=this.transitionQueue.at(-1)??this.activeTransition;if($?.kind===f)return $.promise;let Z=()=>{return},V=()=>{return},H=new Promise((X,Y)=>{Z=X,V=Y}),M={kind:f,intervalMs:A,promise:H,resolve:Z,reject:V};return this.transitionQueue.push(M),this.runNextTransition(),H}runNextTransition(){if(this.activeTransition)return;let f=this.transitionQueue.shift();if(!f)return;this.activeTransition=f,(f.kind==="start"?this.startCleanup(f.intervalMs):this.stopCleanup()).then(()=>this.completeTransition(f,!0),($)=>this.completeTransition(f,!1,$))}completeTransition(f,A,$){if(this.activeTransition!==f)return;if(this.activeTransition=null,A)f.resolve();else f.reject($);queueMicrotask(()=>this.runNextTransition())}createCleanupSupervisor(){let f=G.runSync(v.make()),A=G.runSync(v.extend(AA.make(),f));return{scope:f,fibers:A}}cleanupTerminalBatchMetadata(){return G.tryPromise({try:()=>{let f=this.cleanup(m1);return this.inFlightCleanups.add(f),f.then(()=>this.inFlightCleanups.delete(f),()=>this.inFlightCleanups.delete(f)),f},catch:(f)=>f}).pipe(G.asVoid,G.catchAll((f)=>G.sync(()=>{this.logger.warn("Failed to clean up terminal batch metadata",{error:f})})))}validateOperations(f){for(let A of f){let $=this.jobQueue.getValidator(A.type);if(!$)throw Error(`No job type declared: ${A.type}`);if($.validateAndParse(A.data)===null)throw Error(`Invalid job data for type: ${A.type}`)}}async enqueueBatch(f,A,$,Z){if(f.length===0)throw Error("Cannot enqueue empty batch");this.validateOperations(f);let V=[];this.batches.set($,{jobIds:V,operations:f,source:A.source,startedAt:new Date().toISOString(),metadata:{...A.metadata,rootJobId:$}});try{for(let H of f){let M={...A,rootJobId:$,metadata:{...A.metadata,operationTarget:H.type}},X=await this.jobQueue.enqueue({type:H.type,data:H.data,options:M});V.push(X)}return this.logger.debug("Enqueued batch operations",{batchId:$,operationCount:f.length,jobIds:V,rootJobId:$}),this.scheduleTerminalBatchCleanup(),$}catch(H){throw this.batches.delete($),this.logger.error("Failed to enqueue batch operations",{error:H,operationCount:f.length,enqueuedJobs:V.length}),H}}async getBatchStatus(f){let A=this.batches.get(f);if(!A)return null;try{let $=await Promise.all(A.jobIds.map((F)=>this.jobQueue.getStatus(F))),Z=0,V=0,H=0,M=[];for(let[F,N]of $.entries()){if(!N){V++;let C=A.operations[F],W=A.jobIds[F]??"unknown";M.push(`Missing job ${W}${C?` for ${C.type}`:""}`);continue}switch(N.status){case"completed":Z++;break;case"failed":if(V++,N.lastError)M.push(N.lastError);break;case"processing":case"pending":H++;break}}H+=A.operations.length-A.jobIds.length;let X;if(H>0)X=P.PROCESSING;else if(V>0)X=P.FAILED;else X=P.COMPLETED;if(A.terminalAt===void 0&&(X===P.COMPLETED||X===P.FAILED))A.terminalAt=Date.now();let Y;for(let F=0;F<A.jobIds.length;F++){let N=$[F];if(N&&N.status!=="completed"&&N.status!=="failed"){let C=A.operations[F];if(C)Y=`Processing ${C.type}`;break}}return{batchId:f,totalOperations:A.operations.length,completedOperations:Z,failedOperations:V,errors:M,status:X,currentOperation:Y,metadata:A.metadata}}catch($){throw this.logger.error("Failed to get batch status",{batchId:f,error:$}),$}}async cleanup(f){let A=Date.now()-f,$=0;for(let[Z,V]of this.batches.entries()){if(V.terminalAt!==void 0){if(V.terminalAt<=A)this.batches.delete(Z),$++;continue}if(new Date(V.startedAt).getTime()<=A){let M=await this.getBatchStatus(Z);if(M&&(M.status===P.COMPLETED||M.status===P.FAILED))this.batches.delete(Z),$++}}return this.logger.debug("Cleaned up batch metadata",{cleaned:$}),$}registerBatch(f,A,$,Z,V){this.batches.set(f,{jobIds:A,operations:$,source:Z,startedAt:new Date().toISOString(),metadata:V}),this.logger.debug("Registered batch metadata",{batchId:f,operationCount:$.length,jobIds:A})}async getActiveBatches(){let f=[];try{for(let[A,$]of this.batches){let Z=await this.getBatchStatus(A);if(Z&&(Z.status==="pending"||Z.status==="processing"))f.push({batchId:A,status:Z,metadata:{operations:$.operations,source:$.source,startedAt:$.startedAt,metadata:$.metadata}})}return this.logger.debug("Retrieved active batches",{count:f.length}),f}catch(A){throw this.logger.error("Failed to get active batches",{error:A}),A}}}var S1=U.preprocess((f)=>{if(typeof f!=="string")return f;return JSON.parse(f)},U.record(U.string(),U.unknown()));class L${jobQueueService;messageBus;batchJobManager;logger;mode;pollTimer;pollCursor={updatedAt:0,jobId:""};polling=!1;static createFresh(f,A,$,Z,V="combined"){return new L$(f,A,$,Z,V)}constructor(f,A,$,Z,V){this.jobQueueService=f,this.messageBus=A,this.batchJobManager=$,this.logger=Z,this.mode=V}start(){if(this.mode==="durable-reader"&&!this.pollTimer){this.pollCursor={updatedAt:Date.now(),jobId:""},this.pollTimer=setInterval(()=>{this.pollDurableUpdates()},250),this.pollTimer.unref(),this.logger.debug("Job progress monitor ready (durable polling mode)");return}this.logger.debug("Job progress monitor ready (event-driven mode)")}stop(){if(this.pollTimer)clearInterval(this.pollTimer);this.pollTimer=void 0,this.logger.debug("Job progress monitor stopped")}async pollDurableUpdates(){if(this.polling)return;this.polling=!0;try{let f=await this.jobQueueService.getRuntimeUpdates(this.pollCursor,100);for(let A of f)if(this.pollCursor=A.cursor,A.job.status==="processing"&&A.job.progress)await this.publishJobProgress(A.job,A.job.progress);else if(A.job.status==="completed"||A.job.status==="failed")await this.handleJobStatusChange(A.job.id,A.job.status,A.job.metadata)}catch(f){this.logger.error("Failed to poll durable job progress",{error:f})}finally{this.polling=!1}}createProgressReporter(f,A){let $=s.from(async(Z)=>{await this.emitJobProgress(f,Z,A)});if(!$)throw Error("Failed to create ProgressReporter");return $}async emitBatchProgress(f,A,$){try{let Z={totalOperations:A.totalOperations,completedOperations:A.completedOperations,failedOperations:A.failedOperations,currentOperation:A.currentOperation??"Processing batch...",errors:A.errors},V={id:f,type:"batch",status:A.status,metadata:$,batchDetails:Z};if(A.totalOperations>0)V.progress={current:A.completedOperations,total:A.totalOperations,percentage:Math.round(A.completedOperations/A.totalOperations*100)};await this.messageBus.send({type:Of.progress,payload:V,sender:"job-progress-monitor",broadcast:!0}),this.logger.debug("Emitted batch progress update",{batchId:f,status:A.status,progress:`${A.completedOperations}/${A.totalOperations}`})}catch(Z){this.logger.error("Error emitting batch progress update",{batchId:f,error:Z})}}isBatchChild(f,A){return!!A&&A!==f}async broadcastEvent(f){await this.messageBus.send({type:Of.progress,payload:f,sender:"job-progress-monitor",broadcast:!0})}async emitJobProgress(f,A,$){try{if($&&!await this.jobQueueService.recordAttemptProgress(f,$,A)){this.logger.debug("Discarding progress from obsolete job attempt",{jobId:f,attemptId:$});return}if(this.mode==="durable-writer")return;let Z=await this.jobQueueService.getStatus(f);if(!Z){this.logger.warn("Job not found for progress update",{jobId:f});return}await this.publishJobProgress(Z,A)}catch(Z){this.logger.error("Error emitting job progress",{jobId:f,error:Z})}}async publishJobProgress(f,A){if(f.metadata.silent)return;if(this.isBatchChild(f.id,f.metadata.rootJobId))return;let $=A.total??0,Z={id:f.id,type:"job",status:"processing",metadata:f.metadata,message:A.message};if($>0)Z.progress={current:A.progress,total:$,percentage:Math.round(A.progress/$*100)};await this.broadcastEvent(Z)}async emitJobCompletion(f){if(this.mode!=="durable-writer")await this.emitJobStatusEvent(f,"completed")}async emitJobFailure(f){if(this.mode!=="durable-writer")await this.emitJobStatusEvent(f,"failed")}async emitJobStatusEvent(f,A){try{let $=await this.jobQueueService.getStatus(f);if(!$){this.logger.warn(`Cannot emit ${A} for unknown job`,{jobId:f});return}if($.metadata.silent)return;if(this.isBatchChild(f,$.metadata.rootJobId)){this.logger.debug(`Skipping individual job ${A} for batch operation`,{jobId:f,rootJobId:$.metadata.rootJobId});return}let Z={id:f,type:"job",status:A,message:this.extractStatusMessage($,A),metadata:$.metadata,jobDetails:{jobType:$.type,priority:$.priority,retryCount:$.retryCount}};await this.broadcastEvent(Z),this.logger.debug(`Emitted job ${A} event`,{jobId:f})}catch($){this.logger.error(`Error emitting job ${A} event`,{jobId:f,error:$})}}extractStatusMessage(f,A){if(A==="failed")return f.lastError??void 0;if(!f.result)return;try{let $=S1.parse(f.result),Z=$.message;if(Z)return String(Z);let V=$.routesBuilt;if(V!==void 0)return`${V} routes built`}catch{}return}getStats(){return{isRunning:!0}}async handleJobStatusChange(f,A,$){if(this.mode==="durable-writer")return;let Z=$?Vf.safeParse($):void 0,V=Z?.success?Z.data:void 0;if(V?.silent)return;try{if(await this.emitJobStatusEvent(f,A),V&&this.isBatchChild(f,V.rootJobId))try{let H=V.rootJobId,M=await this.batchJobManager.getBatchStatus(H);if(M){let X=M.metadata??V;await this.emitBatchProgress(H,M,X)}}catch(H){this.logger.warn("Failed to emit batch progress",{jobId:f,rootJobId:V.rootJobId,error:H})}}catch(H){this.logger.error("Failed to handle job status change",{jobId:f,status:A,error:H})}}}var z1=U.record(U.string(),U.unknown());class wf{logger;schema;jobTypeName;executionTimeoutMs;constructor(f,A){this.logger=f,this.schema=A.schema,this.jobTypeName=A.jobTypeName,this.executionTimeoutMs=A.executionTimeoutMs}validateAndParse(f){if(!this.schema)throw Error(`${this.jobTypeName}: No schema provided. Override validateAndParse() or provide a schema.`);let A=this.schema.safeParse(f);if(!A.success)return this.logger.warn(`Invalid ${this.jobTypeName} job data`,{data:f,validationError:A.error.issues}),null;return this.logger.debug(`${this.jobTypeName} job data validation successful`,{data:this.summarizeDataForLog(A.data)}),A.data}async onError(f,A,$,Z,V){this.logger.error(`${this.jobTypeName} job error handler triggered`,{jobId:$,errorMessage:f.message,errorStack:f.stack,data:this.summarizeDataForLog(A)})}async reportProgress(f,A){await f.report({progress:A.progress,total:A.total??100,message:A.message})}summarizeDataForLog(f){let A=z1.safeParse(f);return A.success?A.data:{}}}function F$(f,A,$){return async(Z)=>{let{type:V,data:H,toolContext:M=null,options:X,projection:Y}=Z,F=M?z0(M):void 0,{metadata:N,...C}=X??{},W={operationType:"data_processing",pluginId:A,...N,...M&&{interfaceType:M.interfaceType,conversationId:M.conversationId,channelId:M.channelId,requestedByActor:M.actor,...F?{requestedByUserId:F}:{},requestedByInterface:M.interfaceType}};if(M&&!F)delete W.requestedByUserId;let _={...C,source:A,...X?.rootJobId&&{rootJobId:X.rootJobId},...Y&&{projection:Y},metadata:W},q=$&&!V.includes(":")?`${A}:${V}`:V;return f.enqueue({type:q,data:H,options:_})}}function C$(f,A){return async($,Z)=>{let V=g(),H=$.map((X)=>({...X,type:X.type.includes(":")?X.type:`${A}:${X.type}`})),M={...Z,source:A,rootJobId:V,metadata:{...Z?.metadata,operationType:"batch_processing",pluginId:A}};return await f.enqueueBatch(H,M,V,A),V}}function N$(f,A){return($,Z)=>{let V=$.includes(":")?$:`${A}:${$}`;f.registerHandler(V,Z,A)}}var y1=U.custom((f)=>typeof f==="object"&&f!==null&&("safeParse"in f)),h1=U.object({name:U.string(),schema:y1});function y0(f){return h1.safeParse(f).success}function v1(f){if(!f)return;return{status:f.status,message:f.message,lastCheck:f.lastCheck?.toISOString(),details:f.details}}function h0(f){return{model:f.model,version:f.version,uptime:f.uptime,entities:f.entities,entityCounts:f.entityCounts,embeddings:f.embeddings,ai:f.ai,daemons:f.daemons.map((A)=>({name:A.name,pluginId:A.pluginId,status:A.status,health:v1(A.health)})),endpoints:f.endpoints,interactions:f.interactions}}function j1(f){let A=Lf.safeParse(f);return A.success?A.data:"user"}function $A(f){let A=ff(f.metadata),$=typeof A.channelName==="string"?A.channelName:void 0;return{id:f.id,sessionId:f.sessionId,interfaceType:f.interfaceType,channelId:f.channelId,...f.personId?{personId:f.personId}:{},channelName:$,startedAt:f.started,lastActiveAt:f.lastActive,createdAt:f.created,updatedAt:f.updated,metadata:A}}function v0(f){return{id:f.id,conversationId:f.conversationId,role:j1(f.role),content:f.content,timestamp:f.timestamp,metadata:ff(f.metadata)}}function j0(f){return nA.parse(f)}function b0(f){return dA.parse(f)}function g0(f){return async()=>{return h0(await f.getAppInfo())}}function u0(f,A){return{get:()=>j0(f.getIdentity()),getProfile:()=>b0(f.getProfile()),getAppInfo:A}}function I0(f,A){let $=f.getProfileKindRegistry();return{register:(Z)=>{$.register(A,Z)},getResolved:()=>$.getResolved(),getSelectedDefinition:()=>$.getSelectedDefinition()}}function G$(f){let A=f.getChannelRegistry();return{listDescriptors:()=>A.listDescriptors(),getDescriptor:($)=>A.getDescriptor($),getDeliveryProvider:($)=>A.getDeliveryProvider($)}}function c0(f,A){let $=f.getInboxRegistry();return{registerSource:(Z)=>{$.registerSource(A,Z)},listSources:()=>$.listSources(),getSource:(Z)=>$.getSource(Z)}}function p0(f,A){let $=f.getChannelRegistry();return{...G$(f),registerDescriptor:(Z)=>{$.registerDescriptor(A,Z)},registerDeliveryProvider:(Z)=>{$.registerDeliveryProvider(A,Z)}}}function l0(f,A,$,Z=!1){let V=f.getMessageBus();return{send:async(M)=>{return V.send({...M,sender:A})},subscribe:(M,X)=>{if(Z)return()=>{};if(y0(M)){let Y=M,F=X,N=async(C)=>{let W=Y.schema.safeParse(C.payload);if(!W.success)return $.warn(`Invalid payload for channel ${Y.name}`,{error:W.error.message}),{noop:!0};let{payload:_,...q}=C;return F(W.data,q)};return V.subscribe(Y.name,N)}return V.subscribe(M,X)},subscribeExecution:(M,X)=>V.subscribe(M,X)}}function n0(f,A){let $=f.getJobQueueService();return{...f.jobs,enqueue:F$($,A,!0),enqueueBatch:C$(f.jobs,A),registerHandler:N$($,A)}}function d0(f){let A=f.getPermissionService();return{assertEntityActionAllowed:($,Z,V)=>{A.assertEntityActionAllowed($,Z,V.userPermissionLevel)}}}function i0(f){return{get:async(A)=>{let Z=await f.getConversationService().getConversation(A);return Z?$A(Z):null},search:async(A)=>{return(await f.getConversationService().searchConversations(A)).map($A)},list:async(A)=>{return(await f.getConversationService().listConversations(A)).map($A)},getMessages:async(A,$)=>{return(await f.getConversationService().getMessages(A,$)).map(v0)},countMessages:async(A)=>{return f.getConversationService().countMessages(A)}}}function s0(f,A){return{registerHandler:($,Z)=>{f.registerEvalHandler(A,$,Z)}}}function a0(f){return{register:(A,$)=>{f.getInsightsRegistry().register(A,$)}}}function r0(f){return{has:(A)=>f.getPluginPackageName(A)!==void 0}}function o0(f,A){return{register:($)=>{f.registerEndpoint({...$,pluginId:A})}}}function t0(f,A){return{register:($)=>{f.registerInteraction({...$,pluginId:A})}}}function e0(f,A){return{registerWidget:async($)=>{await f.send({type:R$.registerWidget,payload:{...$,pluginId:A}})},unregisterWidget:async($)=>{await f.send({type:R$.unregisterWidget,payload:{pluginId:A,...$?{widgetId:$}:{}}})}}}function Mf(f,A,$){let Z=f.getEntityService(),V=f.getLogger().child(A),H=f.getDomain(),M=f.getLocalSiteUrl(),X=f.shouldPreferLocalUrls(),Y=f.getThemeCSS(),F=g0(f),N=f.getAttachmentRegistry(),C=f.getRuntimeUploadRegistry(),W=f.getRuntimeState(),_=$?.executionOnly===!0,q=l0(f,A,V,_);return{pluginId:A,executionOnly:_,logger:V,entityService:Z,semantic:{project:(E)=>Z.projectSemanticSpace(E)},identity:u0(f,F),profileKinds:I0(f,A),channels:G$(f),inbox:c0(f,A),appInfo:F,readiness:()=>f.getRuntimeReadiness(),judge:(E)=>f.judge(E),domain:H,siteUrl:H?`https://${H}`:void 0,localSiteUrl:M,previewUrl:H?`https://${fZ(H)}`:void 0,preferLocalUrls:X,themeCSS:Y,entityDisplay:$?.entityDisplay,spaces:f.getSpaces(),permissions:d0(f),messaging:q,dashboard:e0(q,A),jobs:n0(f,A),attachments:N,uploads:C,runtimeState:W,recurringChecks:f.getRecurringChecks(A),conversations:i0(f),dataDir:f.getDataDir(),eval:_?{registerHandler:()=>{}}:s0(f,A),insights:_?{register:()=>{}}:a0(f),plugins:r0(f),endpoints:_?{register:()=>{}}:o0(f,A),interactions:_?{register:()=>{}}:t0(f,A)}}function b1(f){return f.replace(/:/g,"-")}function g1(f){return f.split(/[:.-]/).map((A)=>A.charAt(0).toUpperCase()+A.slice(1)).join(" ")}var K$=new Map;async function ZA(f,A,$){let Z=K$.get(A);if(Z!==void 0)return Z;let V=b1(A),H;try{H=await f.getEntity({entityType:"prompt",id:V})}catch{return $}if(H?.content){let M=xf(H.content,U.record(U.string(),U.unknown())).content;return K$.set(A,M),M}try{let M=g1(A),X=P$($,{title:M,target:A});await f.createEntity({entity:{id:V,entityType:"prompt",content:X,metadata:{title:M,target:A,slug:V}}})}catch{}return K$.set(A,$),$}async function u1(f,A){let $=f.list().filter((Z)=>!!Z.basePrompt);return await Promise.all($.map((Z)=>ZA(A,Z.name,Z.basePrompt))),$.length}function UA(f){let A=f.getEntityService(),$=f.getEntityRegistry(),Z=f.getDataSourceRegistry();return{register:(V,H,M,X)=>{$.registerEntityType(V,H,M,X)},getAdapter:(V)=>{try{return $.getAdapter(V)}catch{return}},extendFrontmatterSchema:(V,H)=>{$.extendFrontmatterSchema(V,H)},getEffectiveFrontmatterSchema:(V)=>{return $.getEffectiveFrontmatterSchema(V)},registerPersistValidator:(V,H)=>{$.registerPersistValidator(V,H)},registerCreateInterceptor:(V,H)=>{$.registerCreateInterceptor(V,H)},registerUploadSaveHandler:(V)=>{$.registerUploadSaveHandler(V)},getUploadSaveHandler:(V)=>{return $.getUploadSaveHandler(V)},update:async(V)=>{return A.updateEntity({entity:V})},registerDataSource:(V)=>{Z.register(V)}}}function VA(f){return{resolve:(A,$)=>{return ZA(f,A,$)}}}function HA(f){return{query:(A,$)=>f.query(A,$),generate:async(A)=>{return f.generateContent(A)},generateObject:async(A,$,Z)=>{return f.generateObject(A,$,Z)},generateImage:async(A,$)=>{return f.generateImage(A,$)},canGenerateImages:()=>{return f.canGenerateImages()}}}function W$(f,A,$){let Z=Mf(f,A,$),V=f.getEntityService();return{...Z,entityService:V,entities:UA(f),ai:HA(f),prompts:VA(V),permissions:Z.permissions}}function D$(f,A,$){let Z=Mf(f,A,$),V=f.getEntityService(),H=f.getRenderService(),M=f.getContentService(),X=f.getPermissionService();return{...Z,permissions:{...Z.permissions,getConfiguredPrincipalSeeds:()=>X.getConfiguredPrincipalSeeds(),replaceRuntimePrincipalState:(Y)=>X.replaceRuntimePrincipalState(Y)},entityService:V,entities:UA(f),webRoutes:{getRoutes:()=>f.getPluginWebRoutes()},templates:{register:(Y,F)=>{f.registerTemplates(Y,F??A)},format:(Y,F)=>{return M.formatContent(Y,F,{pluginId:A})},parse:(Y,F)=>{return M.parseContent(Y,F,A)},resolve:async(Y,F)=>{return await M.resolveContent(Y,F,A)},getCapabilities:(Y)=>{let F=Y.includes(":")?Y:`${A}:${Y}`,N=f.getTemplate(F);if(!N)return null;let C=AZ.getCapabilities(N);return{canGenerate:C.canGenerate,canFetch:C.canFetch,canRender:C.canRender,isStaticOnly:C.isStaticOnly}}},views:{get:(Y)=>{return H.get(Y)??void 0},list:()=>{return H.list()},hasRenderer:(Y,F="web")=>{return H.hasRenderer(Y,F)},getRenderer:(Y,F="web")=>{return H.getRenderer(Y,F)},validate:(Y,F)=>{return H.validate(Y,F)}},prompts:VA(V),ai:HA(f),registerInstructions:(Y)=>{f.registerInstructions(A,Y)}}}class $Z extends Zf{type="service";getApiRoutes(){return[]}getWebRoutes(){return[]}async register(f,A){let $=D$(f,this.id,A);return this.context=$,this.setupMessageHandlers($),await this.onRegister($),this.getCapabilities()}get entityService(){return this.getContext().entityService}registerEntityType(f,A,$,Z){this.getContext().entities.register(f,A,$,Z)}async enqueueJob(f){return this.getContext().jobs.enqueue(f)}async enqueueBatch(f,A){return this.getContext().jobs.enqueueBatch(f,A)}async registerEntityTypes(f){}async registerJobHandlers(f){}async onRegister(f){await this.registerEntityTypes(f),await this.registerJobHandlers(f)}}var I1=U.object({});class _$ extends Zf{type="entity";entityActionPolicy;constructor(f,A,$,Z,V){super(f,A,$,Z);if(V!==void 0)this.entityActionPolicy=V}async register(f,A){let $=W$(f,this.id,A);this.context=$,this.setupMessageHandlers($);let Z=this.getProjectionRules($),V=this.getEntityTypeConfig(),H=Z.some((W)=>W.targetType===this.entityType),M=V?.projectionSource!==!1&&V?.projectionSourceRole!=="excluded"&&(V?.projectionSource===!0||V?.projectionSourceRole!==void 0),X=H&&!M?{...V,projectionSource:!1,projectionSourceRole:"excluded"}:V;if($.entities.register(this.entityType,this.schema,this.adapter,X),this.interceptCreate!==_$.prototype.interceptCreate)$.entities.registerCreateInterceptor(this.entityType,(W,_)=>this.interceptCreate(W,_,$));let Y=this.createGenerationHandler($);if(Y)$.jobs.registerHandler(`${this.entityType}:generation`,Y);let F=this.getTemplates();if(F&&Object.keys(F).length>0)f.registerTemplates(F,this.id);let N=this.getDataSources();for(let W of N)$.entities.registerDataSource(W);await this.onRegister(this.context);let C=await this.getInstructions();return{tools:[],resources:[],...C&&{instructions:C},...Z.length>0&&{projectionRules:Z}}}async interceptCreate(f,A,$){return{kind:"continue",input:f}}createGenerationHandler(f){return null}getTemplates(){return null}getDataSources(){return[]}getEntityTypeConfig(){return}getProjectionRules(f){return[]}}async function c1({context:f,targetType:A,desired:$,getId:Z,toEntityInput:V,equals:H,deleteStale:M=!1,outputVisibility:X="public",concurrency:Y=1,logger:F}){let N=new Map;for(let z of $)N.set(Z(z),z);let C=(await f.entityService.listEntities({entityType:A,options:{filter:{visibilityScope:X}}})).filter((z)=>z.visibility===X),W=new Map(C.map((z)=>[z.id,z])),_=0,q=0,E=0,I=0,r=Math.max(1,Y);if(M){let z=C.filter((c)=>!N.has(c.id));await ZZ(z,r,async(c)=>{await f.entityService.deleteEntity({entityType:A,id:c.id}),E++})}return await ZZ(Array.from(N),r,async([z,c])=>{let R=W.get(z),B={...V(c,z),visibility:X};try{if(!R){await f.entityService.createEntity({entity:B}),_++;return}if(H?.(R,c)??!1){I++;return}await f.entityService.updateEntity({entity:{...R,...B,id:z,entityType:A,visibility:X}}),q++}catch(K){F?.error("Failed to reconcile entity",{targetType:A,id:z,error:S(K)})}}),{created:_,updated:q,deleted:E,skipped:I}}async function ZZ(f,A,$){let Z=await G.runPromiseExit(G.forEach(f,(V)=>G.tryPromise({try:()=>$(V),catch:(H)=>H}),{concurrency:A,discard:!0}));if(u.isFailure(Z))throw MA.squash(Z.cause)}async function p1({entityService:f,entity:A,options:$}){let Z=await f.getEntity({entityType:A.entityType,id:A.id});if(Z)return{entityId:Z.id,created:!1,existingEntity:Z};let V=await f.createEntity({entity:A,...$?{options:$}:{}});return{entityId:V.entityId,created:!0,mutation:V}}async function l1({entityService:f,entity:A,expectedContentHash:$}){let Z=await f.getEntity({entityType:A.entityType,id:A.id});if(Z){let H={...Z,content:A.content,metadata:A.metadata,updated:A.updated??new Date().toISOString()},M=await f.updateEntity({entity:H,...$!==void 0?{options:{expectedContentHash:$}}:{}});return{entityId:M.entityId,updated:!0,mutation:M,previousEntity:Z}}if($!==void 0)return{entityId:A.id,updated:!1,mutation:{entityId:A.id,jobId:"",skipped:!0,skipReason:"content-conflict"}};let V=await f.createEntity({entity:A});return{entityId:V.entityId,updated:!1,mutation:V}}async function n1({entityService:f,entityType:A,id:$,error:Z,content:V}){let H=await f.getEntity({entityType:A,id:$});if(!H)return{found:!1};let M={...H,content:V??H.content,metadata:{...H.metadata,status:"failed",processingError:Z},updated:new Date().toISOString()},X=await f.updateEntity({entity:M});return{found:!0,entityId:X.entityId,mutation:X,previousEntity:H}}function UZ(f){return HZ(f)}function VZ(f){if(!f)return;return{...f.userPermissionLevel&&{userPermissionLevel:f.userPermissionLevel},...f.isAnchor!==void 0&&{isAnchor:f.isAnchor},...f.interfaceType&&{interfaceType:f.interfaceType},...f.channelId&&{channelId:f.channelId},...f.channelName&&{channelName:f.channelName},...f.actor&&{actor:f.actor},...f.source&&{source:f.source},...f.attachments&&{attachments:f.attachments}}}function MZ(f){return{chat:async(A,$,Z,V)=>{let H=VZ(Z),M=V?await f.chat(A,$,H,V):await f.chat(A,$,H);return UZ(M)},confirmPendingAction:async(A,$,Z,V,H)=>{let M=VZ(V);if(!M)throw Error("Confirmation requires caller context.");let X=H?await f.confirmPendingAction(A,$,Z,M,H):await f.confirmPendingAction(A,$,Z,M);return UZ(X)},invalidate:()=>{f.invalidateAgent()}}}var XA=new WeakMap;function d1(f,A){if(XA.has(f))throw Error("HTTP route snapshot provider is already bound");XA.set(f,A)}function XZ(f,A){let $=XA.get(f);if(!$)throw Error("HTTP route snapshot provider is not bound");d1(A,$)}function YZ(f){let A=XA.get(f);if(!A)throw Error("HTTP route snapshot provider is not bound");return A()}function YA(f,A,$){let Z=Mf(f,A,$),V=f.getMCPService(),H=f.getPermissionService(),M=MZ(f.getAgentService());return{...Z,mcpTransport:V,agent:M,permissions:{...Z.permissions,getUserLevel:(X,Y,F)=>{return H.determineUserLevel(X,Y,F)},isAnchor:(X,Y)=>H.isAnchor(X,Y)},daemons:{register:(X,Y)=>{let F=`${A}:${X}`;f.registerDaemon(F,Y,A),Z.logger.debug(`Registered daemon: ${F}`)}},conversations:{...Z.conversations,start:async(X)=>{return f.getConversationService().startConversation(X)},addMessage:async(X)=>{await f.getConversationService().addMessage(X)},updateMetadata:async(X)=>{return f.getConversationService().updateConversationMetadata(X)},delete:async(X)=>{return f.getConversationService().deleteConversation(X)}},tools:{listForPermissionLevel:(X)=>{return f.listToolsForPermissionLevel(X)}},apiRoutes:{getRoutes:()=>{return f.getPluginApiRoutes()},getMessageBus:()=>{return f.getMessageBus()}},webRoutes:{getRoutes:()=>{return f.getPluginWebRoutes()}},httpRoutes:{getRoutes:()=>YZ(f)},plugins:{has:(X)=>f.hasPlugin(X)}}}function B$(f,A,$){return{...YA(f,A,$),channels:p0(f,A)}}var i1=3600000;class LA extends Zf{type="interface";daemon;jobTrackingEntries=new Map;jobTrackingTtlMs=i1;createContext(f,A){return YA(f,this.id,A)}async register(f,A){let $=this.createContext(f,A);if(this.context=$,this.initializeDaemon(),this.daemon)await this.registerDaemon($);return this.setupMessageHandlers($),await this.onRegister($),this.getCapabilities()}async onRegister(f){}async registerDaemon(f){if(!this.daemon)return;f.daemons.register(this.id,this.daemon),f.logger.debug(`Registered daemon for interface: ${this.id}`)}createDaemon(){return}requiresDaemonStartup(){return!1}getWebRoutes(){return[]}initializeDaemon(){let f=this.createDaemon();if(f)this.daemon=f}async handleProgressEvent(f,A){}cleanupExpiredEntries(){let f=Date.now(),A=[];for(let[$,Z]of this.jobTrackingEntries)if(f-Z.createdAt>this.jobTrackingTtlMs)A.push($);for(let $ of A)this.jobTrackingEntries.delete($)}ownsJob(f,A){return this.jobTrackingEntries.has(f)||A!==void 0&&this.jobTrackingEntries.has(A)}getJobTracking(f,A){let $=this.jobTrackingEntries.get(f);if($)return $.info;if(A){let Z=this.jobTrackingEntries.get(A);if(Z)return Z.info}return}setJobTracking(f,A){this.cleanupExpiredEntries(),this.jobTrackingEntries.set(f,{info:A,createdAt:Date.now()})}removeJobTracking(f){this.jobTrackingEntries.delete(f)}async createJobWithTracking(f,A){let Z=await this.getContext().jobs.enqueue(f);return this.setJobTracking(Z,A),Z}async createBatchWithTracking(f,A,$){let V=await this.getContext().jobs.enqueueBatch(f,$);return this.setJobTracking(V,A),V}}var CZ=/^[a-z][a-z0-9-]*$/,s1=U.strictObject({source:U.string().min(1).max(500),flags:U.string().regex(/^[imu]*$/).optional()}),a1=U.strictObject({type:U.string().trim().regex(CZ),displayName:U.string().trim().min(1).max(100),subjectLabel:U.string().trim().min(1).max(100),subjectPattern:s1.optional(),manualDelivery:U.boolean().optional()});class NZ{descriptorRegistrations=new Map;providerRegistrations=new Map;activeDescriptors=new Map;activeProviders=new Map;finalized=!1;registerDescriptor(f,A){this.assertRegistrationOpen();let $=LZ(f),Z=a1.parse(A);if(Z.subjectPattern)new RegExp(Z.subjectPattern.source,Z.subjectPattern.flags);let V=Object.freeze({type:Z.type,displayName:Z.displayName,subjectLabel:Z.subjectLabel,...Z.subjectPattern?{subjectPattern:Object.freeze({...Z.subjectPattern})}:{},...Z.manualDelivery!==void 0?{manualDelivery:Z.manualDelivery}:{}}),H=this.descriptorRegistrations.get(Z.type)??[];H.push({pluginId:$,descriptor:V}),this.descriptorRegistrations.set(Z.type,H)}registerDeliveryProvider(f,A){this.assertRegistrationOpen();let $=LZ(f),Z=k$(A.channelType);if(typeof A.isAvailable!=="function"||typeof A.send!=="function")throw Error("Channel delivery provider operations are required");let V=Object.freeze({channelType:Z,isAvailable:A.isAvailable.bind(A),send:A.send.bind(A)}),H=this.providerRegistrations.get(Z)??[];H.push({pluginId:$,provider:V}),this.providerRegistrations.set(Z,H)}unregisterPlugin(f){let A=f.trim();for(let[$,Z]of this.descriptorRegistrations){let V=Z.filter((H)=>H.pluginId!==A);if(V.length===0)this.descriptorRegistrations.delete($);else this.descriptorRegistrations.set($,V)}for(let[$,Z]of this.providerRegistrations){let V=Z.filter((H)=>H.pluginId!==A);if(V.length===0)this.providerRegistrations.delete($);else this.providerRegistrations.set($,V)}if(this.finalized)this.rebuildActiveState(!1)}finalize(){if(this.finalized)return;this.rebuildActiveState(!0),this.finalized=!0}listDescriptors(){return this.assertFinalized(),[...this.activeDescriptors.values()].sort((f,A)=>f.type.localeCompare(A.type))}getDescriptor(f){return this.assertFinalized(),this.activeDescriptors.get(k$(f))}getDeliveryProvider(f){return this.assertFinalized(),this.activeProviders.get(k$(f))}isFinalized(){return this.finalized}rebuildActiveState(f){let A=new Map,$=new Map;for(let[Z,V]of this.descriptorRegistrations){if(V.length>1){if(!f)continue;throw FZ("Channel",Z,V)}let H=V[0]?.descriptor;if(H)A.set(Z,H)}for(let[Z,V]of this.providerRegistrations){if(V.length>1){if(!f)continue;throw FZ("Delivery provider for channel",Z,V)}if(!A.has(Z)){if(f)throw Error(`Delivery provider for channel "${Z}" has no descriptor`);continue}let H=this.descriptorRegistrations.get(Z)?.[0]?.pluginId,M=V[0]?.pluginId;if(H!==M){if(f)throw Error(`Delivery provider for channel "${Z}" must be registered by descriptor owner "${H??"unknown"}", not "${M??"unknown"}"`);continue}let X=V[0]?.provider;if(X)$.set(Z,X)}this.activeDescriptors=A,this.activeProviders=$}assertRegistrationOpen(){if(this.finalized)throw Error("Channel registration is closed")}assertFinalized(){if(!this.finalized)throw Error("Channel registry is not finalized")}}function LZ(f){let A=f.trim();if(!A)throw Error("Channel registration plugin id is required");return A}function k$(f){let A=f.trim();if(!CZ.test(A))throw Error(`Invalid channel type: ${f}`);return A}function FZ(f,A,$){let Z=$.map((V)=>V.pluginId).sort().join(", ");return Error(`${f} "${A}" is registered by multiple plugins: ${Z}`)}var FA=/^[a-z][a-z0-9-]*$/,GZ=U.strictObject({id:U.string().trim().regex(FA),label:U.string().trim().min(1).max(100),confirm:U.boolean().optional()}),RZ=U.strictObject({entityType:U.string().trim().min(1).max(100),entityId:U.string().trim().min(1).max(300)}),KZ=U.strictObject({id:U.string().trim().min(1).max(300),title:U.string().trim().min(1).max(160),summary:U.string().trim().min(1).max(1000).optional(),receivedAt:U.iso.datetime(),urgency:U.enum(["high","normal"]),entityRef:RZ.optional(),actions:U.array(GZ).max(10)}).superRefine((f,A)=>{let $=new Set;for(let Z of f.actions){if($.has(Z.id))A.addIssue({code:"custom",path:["actions"],message:`Duplicate inbox action id: ${Z.id}`});$.add(Z.id)}}),PZ=U.array(KZ).max(1000),WZ=U.strictObject({permissionLevel:U.enum(["admin","trusted","public"])}),DZ=U.strictObject({sourceId:U.string().trim().regex(FA),displayName:U.string().trim().min(1).max(100)});class _Z{registrations=new Map;activeSources=new Map;finalized=!1;registerSource(f,A){this.assertRegistrationOpen();let $=t1(f),Z=DZ.parse({sourceId:A.sourceId,displayName:A.displayName});if(typeof A.list!=="function"||typeof A.act!=="function")throw Error("Inbox source operations are required");let V=r1(Z,A),H=this.registrations.get(Z.sourceId)??[];H.push({pluginId:$,source:V}),this.registrations.set(Z.sourceId,H)}unregisterPlugin(f){let A=f.trim();for(let[$,Z]of this.registrations){let V=Z.filter((H)=>H.pluginId!==A);if(V.length===0)this.registrations.delete($);else this.registrations.set($,V)}if(this.finalized)this.rebuildActiveState(!1)}finalize(){if(this.finalized)return;this.rebuildActiveState(!0),this.finalized=!0}listSources(){return this.assertFinalized(),[...this.activeSources.values()].sort((f,A)=>f.sourceId.localeCompare(A.sourceId))}getSource(f){return this.assertFinalized(),this.activeSources.get(e1(f))}isFinalized(){return this.finalized}rebuildActiveState(f){let A=new Map;for(let[$,Z]of this.registrations){if(Z.length>1){if(!f)continue;let H=Z.map((M)=>M.pluginId).sort().join(", ");throw Error(`Inbox source "${$}" is registered by multiple plugins: ${H}`)}let V=Z[0]?.source;if(V)A.set($,V)}this.activeSources=A}assertRegistrationOpen(){if(this.finalized)throw Error("Inbox registration is closed")}assertFinalized(){if(!this.finalized)throw Error("Inbox registry is not finalized")}}function r1(f,A){return Object.freeze({...f,list:async()=>{return PZ.parse(await A.list()).map(o1)},act:async($,Z,V)=>{let H=U.string().trim().min(1).max(300).parse($),M=U.string().trim().regex(FA).parse(Z);await A.act(H,M,WZ.parse(V))}})}function o1(f){let A=f.actions.map(($)=>Object.freeze({...$}));return Object.freeze(A),Object.freeze({...f,...f.entityRef?{entityRef:Object.freeze({...f.entityRef})}:{},actions:A})}function t1(f){let A=f.trim();if(!A)throw Error("Inbox registration plugin id is required");return A}function e1(f){return U.string().trim().regex(FA).parse(f)}var f8={pluginsRegistered:"system:plugins:registered",initialSyncCompleted:"sync:initial:completed",shellReady:"system:shell:ready"};function A8(f){return{register:(A,$,Z)=>{return f.register(A,$,Z)},resolve:(A)=>{return f.resolve(A)},hasProvider:(A,$)=>{return f.has(A,$)},getProviderMetadata:(A,$)=>{return f.getMetadata(A,$)}}}class O${providers=new Map;static createFresh(){return new O$}constructor(){}register(f,A,$){return this.getOrCreateSourceProviders(f).set(A,$),()=>{this.unregister(f,A)}}async resolve(f){let A=this.get(f.sourceEntityType,f.attachmentType);if(!A)return;return A.resolve(f)}get(f,A){return this.providers.get(f)?.get(A)}has(f,A){return this.get(f,A)!==void 0}getMetadata(f,A){return this.get(f,A)?.metadata}unregister(f,A){let $=this.providers.get(f);if(!$)return;if($.delete(A),$.size===0)this.providers.delete(f)}getRegisteredAttachmentTypes(f){return Array.from(this.providers.get(f)?.keys()??[])}clear(){this.providers.clear()}getOrCreateSourceProviders(f){let A=this.providers.get(f);if(A)return A;let $=new Map;return this.providers.set(f,$),$}}import{mkdir as $8,readdir as Z8,readFile as BZ,rm as kZ,stat as U8,writeFile as OZ}from"fs/promises";import{basename as V8,dirname as H8,join as n}from"path";var CA=/^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,wZ=86400000,xZ=200;class Xf extends Error{code;constructor(f,A){super(A);this.code=f,this.name="RuntimeUploadStoreError"}}var M8=U.object({id:U.string().regex(CA),ref:U.object({kind:U.string().min(1),id:U.string().regex(CA)}),filename:U.string().min(1),mediaType:U.string().min(1),sizeBytes:U.number().nonnegative(),createdAt:U.string().datetime(),metadata:U.record(U.string(),U.unknown()).optional()});function X8(f){return{scoped:(A)=>f.scoped(A)}}function JZ(f){return V8(f)==="brain-data"?n(H8(f),"data"):f}class w${dataDir;constructor(f){this.dataDir=JZ(f.dataDir)}static createFresh(f){return new w$(f)}scoped(f){return new x$({...f,dataDir:this.dataDir})}}class x${options;retentionMs;maxCount;createUploadId;getNow;constructor(f){this.options=f,this.retentionMs=f.retentionMs??wZ,this.maxCount=f.maxCount??xZ,this.createUploadId=f.createId??(()=>`upload-${crypto.randomUUID()}`),this.getNow=f.now??(()=>new Date)}async save(f){let A=this.createUploadId();this.assertValidUploadId(A);let $={id:A,ref:{kind:this.options.refKind,id:A},filename:f.filename,mediaType:f.mediaType,sizeBytes:f.content.byteLength,createdAt:this.getNow().toISOString(),...f.metadata!==void 0&&{metadata:f.metadata}},Z=this.getUploadDir(A);return await $8(Z,{recursive:!0}),await OZ(n(Z,"content"),f.content),await OZ(n(Z,"metadata.json"),`${JSON.stringify($,null,2)}
|
|
3
3
|
`,"utf8"),await this.prune(),$}async remove(f){this.assertValidUploadId(f),await kZ(this.getUploadDir(f),{recursive:!0,force:!0})}async read(f){let A=await this.readRecord(f);try{let $=await BZ(n(this.getUploadDir(f),"content"));return{record:A,content:$}}catch{throw new Xf("not_found","Upload not found")}}async readRecord(f){this.assertValidUploadId(f);try{let A=await BZ(n(this.getUploadDir(f),"metadata.json"),"utf8"),$=M8.safeParse(JSON.parse(A));if(!$.success||$.data.id!==f||$.data.ref.id!==f||$.data.ref.kind!==this.options.refKind)throw new Xf("invalid_metadata","Invalid upload metadata");return $.data}catch(A){if(A instanceof Xf)throw A;throw new Xf("not_found","Upload not found")}}toResponseBody(f){return{...f,url:this.getUploadUrl(f.id),downloadUrl:this.getUploadUrl(f.id,!0)}}async prune(){let f=this.getUploadsRoot();try{let A=await Z8(f),Z=(await Promise.all(A.map(async(M)=>{try{let X=await U8(n(f,M));return X.isDirectory()?{entry:M,mtimeMs:X.mtimeMs}:null}catch{return null}}))).filter((M)=>M!==null).sort((M,X)=>X.mtimeMs-M.mtimeMs),V=this.getNow().getTime()-this.retentionMs,H=Z.filter((M,X)=>X>=this.maxCount||M.mtimeMs<V);await Promise.all(H.map((M)=>kZ(n(f,M.entry),{recursive:!0,force:!0})))}catch{}}getUploadDir(f){return this.assertValidUploadId(f),n(this.getUploadsRoot(),f)}getUploadsRoot(){return n(this.options.dataDir,this.options.namespace,"uploads")}getUploadUrl(f,A=!1){this.assertValidUploadId(f);let $=encodeURIComponent(f);return`${this.options.routePath}?id=${$}${A?"&download=1":""}`}assertValidUploadId(f){if(!CA.test(f))throw new Xf("invalid_ref","Invalid upload ref")}}function J$(f){if(typeof f!=="object"||f===null||!("entityId"in f))return;let A=f.entityId;return typeof A==="string"&&A.trim().length>0?A.trim():void 0}function QZ(f){if(typeof f!=="object"||f===null||!("coverImage"in f))return;let A=f.coverImage;if(A===void 0||A===!1)return;if(A===!0)return{generate:!0};if(typeof A!=="object"||A===null)return;let $=A;if($.generate===!1)return;let Z=$.prompt?.trim();return{generate:!0,...Z&&{prompt:Z}}}function RA(f){return Object.fromEntries(Object.entries(f).filter(([,A])=>A!==void 0))}function qZ(f){let A={...f};return delete A.status,delete A.error,RA(A)}class SZ extends wf{context;entityType;constructor(f,A,$){super(f,{schema:$.schema,jobTypeName:$.jobTypeName});this.context=A,this.entityType=$.entityType}async afterCreate(f,A,$,Z){}async onGenerationFailure(f,A){}validateAndParse(f){let A=super.validateAndParse(f);if(!A)return null;let $=QZ(f);if(typeof A!=="object")return A;let Z=J$(f);if(!$&&!Z)return A;return Object.assign(A,{...$&&{coverImage:$},...Z&&{entityId:Z}}),A}async process(f,A,$){try{await this.reportProgress($,{progress:NA.START,message:`Starting ${this.jobTypeName}`});let Z=await this.generate(f,$),V=J$(f),H=V?this.applyPreallocatedEntityId(V,Z):Z;await this.reportProgress($,{progress:NA.SAVE,message:`Saving ${this.entityType} to database`});let M=V?await this.updatePreallocatedStub(V,H):await this.context.entityService.createEntity({entity:{id:H.id,entityType:this.entityType,content:H.content,metadata:H.metadata},options:H.createOptions});return await this.afterCreate(f,M.entityId,$,H),await this.enqueueGenericCoverImageIfRequested(f,M.entityId,$,H),await this.reportProgress($,{progress:NA.COMPLETE,message:`${H.title??this.entityType} created successfully`}),{success:!0,entityId:M.entityId,...H.resultExtras}}catch(Z){if(Z instanceof q$)return await this.markPreallocatedStubFailed(f,Z.message),await this.onGenerationFailure(f,Z.message),{success:!1,error:Z.message};let V=S(Z);return this.logger.error(`${this.jobTypeName} job failed`,{error:Z,jobId:A,data:this.summarizeDataForLog(f)}),await this.markPreallocatedStubFailed(f,V),await this.onGenerationFailure(f,V),TZ.failure(Z)}}applyPreallocatedEntityId(f,A){let $={...A.metadata},Z=A.content,V=A.resultExtras;if(typeof $.slug==="string")$.slug=f,Z=GA(Z,"slug",f),V={...V,slug:f};return{...A,id:f,content:Z,metadata:$,...V&&{resultExtras:V}}}async updatePreallocatedStub(f,A){let $=await this.context.entityService.getEntity({entityType:this.entityType,id:f,visibilityScope:"restricted"});if(!$)throw Error(`Pre-allocated entity stub not found: ${this.entityType}/${f}`);let Z=this.mergeStubWithGenerated($,A);return this.context.entityService.updateEntity({entity:{...$,id:f,entityType:this.entityType,content:Z.content,metadata:Z.metadata}})}mergeStubWithGenerated(f,A){let $=qZ(Q$(f.content).frontmatter),Z=qZ(f.metadata),V=RA(A.metadata),H=Q$(A.content),M=RA(H.frontmatter),X=RA({...$,...V,...M});return this.context.entities.getEffectiveFrontmatterSchema(this.entityType)?.parse(X),{content:mZ(X,H.content),metadata:{...Z,...V}}}async markPreallocatedStubFailed(f,A){let $=J$(f);if(!$)return;try{let Z=await this.context.entityService.getEntity({entityType:this.entityType,id:$,visibilityScope:"restricted"});if(!Z)return;await this.context.entityService.updateEntity({entity:{...Z,content:GA(GA(Z.content,"status","failed"),"error",A),metadata:{...Z.metadata,status:"failed",error:A}}})}catch(Z){this.logger.warn("Failed to mark generation stub as failed",{error:Z,entityId:$,entityType:this.entityType})}}async enqueueGenericCoverImageIfRequested(f,A,$,Z){let V=QZ(f);if(!V)return;await this.reportProgress($,{progress:90,message:"Queueing cover image generation"});let H=Z.title??A;await this.context.jobs.enqueue({type:EZ.generate,data:{prompt:V.prompt??`Editorial cover image for: ${H}. `,title:`${H} Cover`,aspectRatio:"16:9",targetEntityType:this.entityType,targetEntityId:A,entityTitle:H,entityContent:Z.content},toolContext:{interfaceType:"job",actor:{kind:"service",serviceId:"generation-job-handler"}}})}failEarly(f){throw new q$(f)}}class q$ extends Error{constructor(f){super(f);this.name="GenerationFailure"}}function T$(f,A){f.messaging.subscribe(Of.progress,async($)=>{try{let Z=tf.safeParse($.payload);if(!Z.success)return A.onInvalidSchema(),{success:!1};let V=Z.data;return await A.onProgress(V,V.metadata),{success:!0}}catch(Z){return A.onError(Z),{success:!1}}})}function E$(f){let A=f.status==="completed"?"\u2705":"\u274C",$=f.status==="completed"?"completed":"failed",Z=f.metadata.operationType.replace(/_/g," "),V=f.metadata.operationTarget?`: ${f.metadata.operationTarget}`:"",H=`${A} **${Z}${V}** ${$}`;if(f.message)H+=`
|
|
4
4
|
${f.message}`;return H}function m$(f){let A=f.metadata.operationType.replace(/_/g," "),$=f.metadata.operationTarget?`: ${f.metadata.operationTarget}`:"",Z=`\uD83D\uDD04 **${A}${$}**`;if(f.progress&&f.progress.total>0)Z+=` ${f.progress.current}/${f.progress.total} (${f.progress.percentage}%)`;if(f.message)Z+=`
|
|
5
5
|
${f.message}`;return Z}var Y8=U.enum(["tool:invoking","tool:completed","tool:failed"]),L8=U.object({toolName:U.string().min(1),conversationId:U.string().min(1),interfaceType:U.string().min(1),channelId:U.string().min(1).optional(),channelName:U.string().min(1).optional(),toolCallId:U.string().min(1).optional(),error:U.string().optional()}),F8=["tool:invoking","tool:completed","tool:failed"];function S$(f,A){for(let $ of F8)f.messaging.subscribe($,async(Z)=>{try{let V=Y8.safeParse(Z.type),H=L8.safeParse(Z.payload);if(!V.success||!H.success)return A.onInvalidSchema(),{success:!1};return await A.onToolActivity({type:V.data,...H.data}),{success:!0}}catch(V){return A.onError(V),{success:!1}}})}class z${scope;fibers;delayMs;clock;closePromise=null;closed=!1;constructor(f,A){this.delayMs=f,this.clock=A?.clock,this.scope=G.runSync(v.make()),this.fibers=G.runSync(v.extend(Hf.make(),this.scope))}schedule(f,A){if(this.closed)return;let $=G.sleep(this.delayMs).pipe(G.andThen(G.sync(A))),Z=this.clock?G.withClock($,this.clock):$,V=G.runFork(Z);Hf.unsafeSet(this.fibers,f,V)}close(){return this.closed=!0,this.closePromise??=G.runPromise(v.close(this.scope,u.void)),this.closePromise}}function Jf(f,A){return{state:A,toolName:f.toolName,conversationId:f.conversationId,interfaceType:f.interfaceType,...f.channelId!==void 0&&{channelId:f.channelId},...f.channelName!==void 0&&{channelName:f.channelName},...f.error!==void 0&&{error:f.error}}}function y$(f){return`${f.conversationId}:${f.toolName}`}function h$(f){if(f.startsWith("playbook_"))return"playbook";return(f.startsWith("system_")?f.slice(7):f).replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").trim().toLowerCase()}function zZ(f){switch(f){case"running":return"Tool running";case"completed":return"Tool completed";case"awaiting-approval":return"Approval required";case"failed":return"Tool failed"}}function yZ(f){switch(f){case"running":return"Tool running";case"completed":return"Tool completed";case"awaiting-approval":return"Tool awaiting approval";case"failed":return"Tool failed"}}function hZ(f){let A=y$(f),$=h$(f.toolName),Z=zZ(f.state),V=yZ(f.state),H=`${V}: ${$}`;return{key:A,label:$,title:Z,fallbackPrefix:V,fallback:f.error?`${H}: ${f.error}`:H}}function vZ(f,A){return f.pendingConfirmations?.some(($)=>$.toolName===A)===!0||C8(f.cards).some(($)=>$.toolName===A)}function C8(f){return f?.filter((A)=>A.kind==="tool-approval"&&A.state==="approval-requested")??[]}var jZ=500,N8=500;class v${transport;cleanupSupervisor=new z$(N8);progressEvents=new Map;progressMessageTracking=new Map;agentResponseTracking=new Map;pendingToolCompletions=new Map;progressCallback;isProcessingInput=!1;currentChannelId=null;bufferedCompletionMessages=[];constructor(f){this.transport=f}hasProgressCallback(){return this.progressCallback!==void 0}registerProgressCallback(f){this.progressCallback=f,f(this.getActiveProgressEvents())}unregisterProgressCallback(){this.progressCallback=void 0}getProgressEvents(){return Array.from(this.progressEvents.values())}getActiveProgressEvents(){return Array.from(this.progressEvents.values()).filter((f)=>f.status==="processing")}trackAgentResponseForJob(f,A,$){this.agentResponseTracking.set(f,{messageId:A,channelId:$,lastUpdate:Date.now()}),this.transport.logger().debug("Tracking agent response for job",{jobId:f,messageId:A,channelId:$})}startProcessingInput(f=null){this.isProcessingInput=!0,this.currentChannelId=f}endProcessingInput(){this.isProcessingInput=!1;for(let{message:f,channelId:A}of this.bufferedCompletionMessages)this.transport.sendMessageToChannel({channelId:A,message:f});this.bufferedCompletionMessages=[],this.currentChannelId=null}getCurrentChannelId(){return this.currentChannelId}async close(){await this.cleanupSupervisor.close(),this.progressEvents.clear(),this.progressMessageTracking.clear(),this.agentResponseTracking.clear(),this.pendingToolCompletions.clear(),this.bufferedCompletionMessages=[],this.isProcessingInput=!1,this.currentChannelId=null,this.progressCallback=void 0}async handleProgressEvent(f){if(!this.shouldHandleProgressEvent(f))return;this.updateProgressState(f);let A=f.metadata.channelId??null,$=f.metadata.rootJobId;if(await this.handleProcessingProgress(f,A,$))return;if(f.status==="completed"||f.status==="failed")await this.handleTerminalProgress(f,A,$);await this.transport.onProgressUpdate(f),this.logProgressProcessed(f)}async handleToolActivityEvent(f){if(f.interfaceType!==this.transport.interfaceId())return;switch(f.type){case"tool:invoking":this.pendingToolCompletions.delete(this.getToolCompletionKey(f)),await this.transport.handleToolStatusUpdate(Jf(f,"running"));return;case"tool:completed":if(this.isProcessingInput){this.pendingToolCompletions.set(this.getToolCompletionKey(f),f);return}await this.transport.handleToolStatusUpdate(Jf(f,"completed"));return;case"tool:failed":this.pendingToolCompletions.delete(this.getToolCompletionKey(f)),await this.transport.handleToolStatusUpdate(Jf(f,"failed"));return}}async handleAgentResponseToolStatuses(f,A){if(this.pendingToolCompletions.size===0)return;let $=this.transport.interfaceId(),Z=Array.from(this.pendingToolCompletions.values()).filter((V)=>V.interfaceType===$&&V.conversationId===A);for(let V of Z){this.pendingToolCompletions.delete(this.getToolCompletionKey(V));let H=vZ(f,V.toolName)?"awaiting-approval":"completed";await this.transport.handleToolStatusUpdate(Jf(V,H))}}shouldHandleProgressEvent(f){let A=f.metadata.interfaceType;return!A||A===this.transport.interfaceId()}updateProgressState(f){this.progressEvents.set(f.id,f),this.notifyProgressCallback()}async handleProcessingProgress(f,A,$){if(f.status!=="processing"||!this.transport.supportsMessageEditing())return!1;let Z=this.agentResponseTracking.get(f.id);if(Z)return await this.editTrackedProgressMessage(f,Z),!0;let V=this.transport.formatProgressOutput(f),H=this.progressMessageTracking.get($),M=Date.now();if(H){if(M-H.lastUpdate>=jZ)await this.transport.editMessage({channelId:H.channelId,messageId:H.messageId,newMessage:V}),H.lastUpdate=M}else if(A&&!this.isProcessingInput)await this.sendInitialProgressMessage($,A,V,M);return!1}async editTrackedProgressMessage(f,A){let $=Date.now();if($-A.lastUpdate<jZ)return;await this.transport.editMessage({channelId:A.channelId,messageId:A.messageId,newMessage:this.transport.formatProgressOutput(f)}),A.lastUpdate=$}async sendInitialProgressMessage(f,A,$,Z){let V=await this.transport.sendMessageWithId({channelId:A,message:$});if(!V)return;this.progressMessageTracking.set(f,{messageId:V,channelId:A,lastUpdate:Z}),this.transport.logger().debug("Tracking progress message",{rootJobId:f,messageId:V,channelId:A})}async handleTerminalProgress(f,A,$){let Z=this.transport.formatCompletionOutput(f),V=this.progressMessageTracking.get($),H=this.agentResponseTracking.get(f.id);if(this.transport.logger().debug("Completion event received",{eventId:f.id,rootJobId:$,hasProgressTracking:!!V,hasAgentTracking:!!H,supportsEditing:this.transport.supportsMessageEditing()}),this.transport.supportsMessageEditing())await this.updateTrackedCompletion(f,Z,V,H,$);if(!V&&!H&&A)this.sendOrBufferCompletionMessage(Z,A);this.scheduleProgressCleanup(f.id)}async updateTrackedCompletion(f,A,$,Z,V){if(Z){if(await this.transport.editMessage({channelId:Z.channelId,messageId:Z.messageId,newMessage:A}),this.agentResponseTracking.delete(f.id),$)this.progressMessageTracking.delete(V);return}if($)await this.transport.editMessage({channelId:$.channelId,messageId:$.messageId,newMessage:A}),this.progressMessageTracking.delete(V)}sendOrBufferCompletionMessage(f,A){if(this.isProcessingInput){this.bufferedCompletionMessages.push({message:f,channelId:A});return}this.transport.sendMessageToChannel({channelId:A,message:f})}scheduleProgressCleanup(f){this.cleanupSupervisor.schedule(f,()=>{this.progressEvents.delete(f),this.notifyProgressCallback()})}logProgressProcessed(f){this.transport.logger().debug("Progress event processed",{eventId:f.id,status:f.status,operationType:f.metadata.operationType,targetChannel:f.metadata.channelId})}getToolCompletionKey(f){return`${f.interfaceType}:${f.conversationId}:${f.toolName}`}notifyProgressCallback(){this.progressCallback?.(this.getProgressEvents())}}var j$=1e5,G8=[".md",".txt",".markdown"],R8=["text/plain","text/markdown","text/x-markdown"],K8=/https?:\/\/[^\s<>"{}|\\^`[\]]+?(?=[,;:\s]|$)/gi,P8=["meet.google.com","zoom.us","teams.microsoft.com","whereby.com","gather.town","calendly.com","cal.com","discord.com","discord.gg","cdn.discordapp.com","media.discordapp.net","giphy.com","tenor.com","wetransfer.com","file.io"],b$=U.object({captureUrls:U.boolean().default(!1),blockedUrlDomains:U.array(U.string()).default(P8)});function bZ(f,A){if(A&&R8.some(($)=>A.startsWith($)))return!0;return G8.some(($)=>f.toLowerCase().endsWith($))}function gZ(f){return f<=j$}function uZ(f){if(f.includes(0))return!1;try{return new TextDecoder("utf-8",{fatal:!0}).decode(f),!0}catch{return!1}}function IZ(f,A){return`User uploaded a file "${f}":
|
|
@@ -16,5 +16,5 @@ Result:`);if($===-1)return;let Z=f.slice($+9).trim();if(!Z)return;try{return JSO
|
|
|
16
16
|
`)}function OU(f){return{identity:f.identity,interfaceType:f.interfaceType,role:f.role??"user",...f.displayName?{displayName:f.displayName}:{},...f.username?{username:f.username}:{},...f.isBot!==void 0?{isBot:o8(f.isBot)}:{}}}function o8(f){if(typeof f==="boolean")return f;return f.toLowerCase()==="true"}function wU(f){return{...f.messageId?{messageId:f.messageId}:{},...f.channelId?{channelId:f.channelId}:{},...f.channelName?{channelName:f.channelName}:{},...f.threadId?{threadId:f.threadId}:{},...f.metadata?{metadata:f.metadata}:{}}}function xU(f){if(f.skippedMessages.length===0)return{message:f.message};return{message:["Messages received while the previous response was still running (oldest first, for context only):",...f.skippedMessages.map(t8),"","Latest message to answer:",f.message].join(`
|
|
17
17
|
`),metadata:{supersededMessageCount:f.skippedMessages.length,supersededMessageIds:f.skippedMessages.map((Z)=>Z.id).filter((Z)=>Z!==void 0)}}}function t8(f){let A=f.text.trim(),$=f.authorName?.trim();return $?`- ${$}: ${A}`:`- ${A}`}async function MV(f){let{entityType:A,title:$,deriveId:Z,regeneratePrompt:V,context:H}=f,M=Z($),X=await H.entityService.getEntity({entityType:A,id:M});if(!X||X.metadata.status==="generating")return $;H.logger.debug(`Entity ID collision: ${A}/${M}, asking AI for a new title`);let Y=U.object({title:U.string().max(80).describe("A short, unique title (2-6 words)")}),{object:F}=await H.ai.generateObject(`The title "${$}" is already taken. ${V}`,Y),N=F.title;return H.logger.debug(`AI suggested new title: "${N}"`),N}class SA{tail=Promise.resolve();run(f){let A=this.tail.then(()=>f());return this.tail=A.then(()=>{return},()=>{return}),A}async settle(){await this.tail}}var XV="current";class JU{store;schema;createEmpty;key;queue=new SA;statePromise;constructor(f){this.store=f.runtimeState.scoped({namespace:f.namespace,schema:f.schema}),this.schema=f.schema,this.createEmpty=f.createEmpty,this.key=f.key??XV}mutate(f){return this.queue.run(async()=>{let A=await this.load(),$=await f(A);return await this.persist(A),$})}async snapshot(){return await this.settle(),structuredClone(await this.load())}settle(){return this.queue.settle()}load(){return this.statePromise??=this.store.get(this.key).then((f)=>f??this.createEmpty()),this.statePromise}async persist(f){await this.store.set(this.key,this.schema.parse(f))}}var t6=["GET","POST","PUT","DELETE","OPTIONS"];function YV(f,A={}){return new Response(JSON.stringify(f),{status:A.status??200,headers:{"Content-Type":"application/json; charset=utf-8",...A.headers}})}var t$="cms:register-workspace";var LV=U.object({workspaceUrl:U.string()});async function FV(f,A){let $=await f.messaging.send({type:t$,payload:A});if(!("success"in $)||!$.success)return;let Z=LV.safeParse($.data);return Z.success?Z.data.workspaceUrl:void 0}var e$=zf.extend({id:U.literal("brain-character"),entityType:U.literal("brain-character")}),zA=U.object({name:U.string().describe("The brain's friendly display name"),role:U.string().describe("The brain's primary role"),purpose:U.string().describe("The brain's purpose and goals"),values:U.array(U.string()).describe("Core values that guide behavior")});var QU=U.record(U.string(),U.unknown());class yA extends yf{constructor(){super({entityType:"brain-character",purpose:"The brain's own identity, character, and purpose (singleton).",schema:e$,frontmatterSchema:zA,isSingleton:!0,hasBody:!1})}createCharacterContent(f){return this.buildMarkdown("",f)}parseCharacterBody(f){return this.parseFrontmatter(f)}toMarkdown(f){let A=this.parseFrontmatter(f.content);return this.buildMarkdown("",QU.parse(A))}fromMarkdown(f){return{content:f,entityType:"brain-character"}}extractMetadata(f){let A=this.parseFrontmatter(f.content);return{role:A.role,values:A.values}}generateFrontMatter(f){let A=this.parseFrontmatter(f.content);return this.buildMarkdown("",QU.parse(A))}}class hA extends vA{adapter=new yA;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(f,A,$){return new hA(f,A,$)}constructor(f,A,$){super(f,A,"brain-character",$??hA.getDefaultCharacter(),hf("brain character is loaded at bootstrap before any user is in scope"))}parseBody(f){return this.adapter.parseCharacterBody(f)}createContent(f){return this.adapter.createCharacterContent(f)}getCharacter(){return this.get()}getCharacterContent(){return this.getContent()}}var f0=zf.extend({id:U.literal("anchor-profile"),entityType:U.literal("anchor-profile")}),qU=U.enum(["person","team","organization"]),Yf=U.object({name:U.string().describe("Name of the anchor"),organization:U.string().optional().describe("Organization the anchor belongs to"),description:U.string().optional().describe("Short description or biography"),avatar:U.string().optional().describe("URL or asset path to avatar/logo"),website:U.string().optional().describe("Primary website URL"),email:U.string().optional().describe("Contact email"),socialLinks:U.array(U.object({platform:U.enum(["github","instagram","linkedin","email","website"]).describe("Social media platform"),url:U.string().describe("Profile or contact URL"),label:U.string().optional().describe("Optional display label")})).optional().describe("Social media and contact links")});var CV=U.record(U.string(),U.unknown());class jA extends yf{constructor(){super({entityType:"anchor-profile",purpose:"The profile of the brain's Anchor (singleton).",schema:f0,frontmatterSchema:Yf,isSingleton:!0,hasBody:!0})}createProfileContent(f){let A=Yf.parse(f);return this.buildMarkdown("",A)}parseProfileBody(f,A){if(A){let{metadata:$,content:Z}=xf(f,A);return Z?{...$,story:Z}:$}return this.parseFrontmatter(f)}fromMarkdown(f){return{content:f,entityType:"anchor-profile"}}extractMetadata(f){let A=this.parseFrontmatter(f.content);return{name:A.name,email:A.email,website:A.website}}generateFrontMatter(f){let A=this.parseFrontmatter(f.content);return this.buildMarkdown("",CV.parse(A))}}class vf extends vA{adapter=new jA;static getDefaultProfile(){return{name:"Unknown"}}static createFresh(f,A,$){return new vf(f,A,$)}constructor(f,A,$){super(f,A,"anchor-profile",$??vf.getDefaultProfile(),hf("anchor profile is loaded at bootstrap before any user is in scope"))}parseBody(f){return this.adapter.parseProfileBody(f)}createContent(f){return this.adapter.createProfileContent(f)}getProfile(){return this.get()}getProfileContent(){return this.getContent()}}var bA=U.enum(["person","team","organization"]),NV=U.object({kind:U.string().trim().min(1),category:bA,labels:U.object({singular:U.string().trim().min(1),plural:U.string().trim().min(1)})});function GV(f){if(typeof f!=="object"||f===null||!("shape"in f)||!("safeParse"in f)||typeof f.safeParse!=="function")throw Error("Profile kind fields must be a Zod object schema")}class TU{selectedKind;registrations=new Map;finalized=!1;resolved=null;selectedDefinition;constructor(f){let A=f?.trim();this.selectedKind=A===""?void 0:A}register(f,A){if(this.finalized)throw Error("Profile kind registration is closed");let $=NV.parse(A);GV(A.fields);let Z=Object.freeze({...A,kind:$.kind,category:$.category,labels:Object.freeze({...$.labels})}),V=this.registrations.get($.kind)??[];V.push({pluginId:f,definition:Z}),this.registrations.set($.kind,V)}unregisterPlugin(f){for(let[A,$]of this.registrations){let Z=$.filter((V)=>V.pluginId!==f);if(Z.length===0)this.registrations.delete(A);else this.registrations.set(A,Z)}}finalize(){if(this.finalized)return this.resolved;let A=[...this.registrations.entries()].filter(([,Z])=>Z.length>1).sort(([Z],[V])=>Z.localeCompare(V))[0];if(A){let[Z,V]=A,H=V.map((M)=>M.pluginId).sort().join(", ");throw Error(`Profile kind "${Z}" is registered by multiple plugins: ${H}`)}if(!this.selectedKind)return this.finalized=!0,this.resolved=null,null;let $=this.registrations.get(this.selectedKind)?.[0];if(!$)throw Error(`Selected profile kind "${this.selectedKind}" is not registered`);return this.selectedDefinition=$.definition,this.resolved=Object.freeze({kind:$.definition.kind,category:$.definition.category,labels:Object.freeze({...$.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 EU=30000;class $0{logger;resolver;links=[];actorIndex=new Map;negativeActorIndex=new Map;static createFresh(f,A){return new $0(f,A)}constructor(f,A){this.logger=f.child("CanonicalIdentityService"),this.resolver=A}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(f){let A=A0(f),$=this.actorIndex.get(A);if(!$)return null;if($.expiresAt<=Date.now())return this.actorIndex.delete(A),null;return $.resolution}async enrichActor(f){if(f.identity.kind==="user"&&f.identity.canonicalId||f.role!=="user")return f;let A=this.resolveActor(f.identity);if(A)return this.enrichedActor(f,A);let $=A0(f.identity),Z=this.negativeActorIndex.get($);if(Z&&Z>Date.now())return f;this.negativeActorIndex.delete($);let V=await this.resolver?.(f.identity);if(!V)return this.negativeActorIndex.set($,Date.now()+EU),f;let H={identity:f.identity,...f.displayName?{label:f.displayName}:{}},M={...V,actors:[H],matchedActor:H};return this.actorIndex.set($,{resolution:M,expiresAt:Date.now()+EU}),this.links=[...this.links.filter((X)=>X.userId!==M.userId),M],this.enrichedActor(f,M)}enrichedActor(f,A){return{...f,identity:{kind:"user",userId:A.userId,canonicalId:A.canonicalId},...A.displayName?{displayName:A.displayName}:{}}}}var mU="https://rizom.ai/ext/anchor-profile/v1",SU=U.looseObject({id:U.string(),description:U.string(),name:U.string().optional(),tags:U.array(U.string()).optional().default([])}),zU=Yf.extend({kind:U.string().trim().min(1).optional(),category:bA.optional()}).superRefine((f,A)=>{if(f.kind===void 0!==(f.category===void 0))A.addIssue({code:"custom",message:"Anchor kind and category must be provided together"})}),RV=U.looseObject({uri:U.string(),params:U.record(U.string(),U.unknown()).optional()}),yU=U.looseObject({name:U.string(),url:U.string(),description:U.string().optional(),skills:U.array(SU).optional().default([]),capabilities:U.looseObject({extensions:U.array(RV).optional().default([])}).optional()});function KV(f){let A=yU.safeParse(f);if(!A.success)return null;let $=A.data,V=($.capabilities?.extensions??[]).find((M)=>M.uri===mU),H=null;if(V?.params){let M=zU.safeParse(V.params);if(M.success)H=M.data}return{brainName:$.name,url:$.url,description:$.description??"",skills:$.skills.map((M)=>({id:M.id,name:M.name??M.id,description:M.description,tags:M.tags})),anchor:H}}var PV=U.object({name:U.string(),description:U.string(),tags:U.array(U.string()),examples:U.array(U.string())});import{EventEmitter as jU}from"events";var T={REGISTERED:"registered",INITIALIZED:"initialized",ERROR:"error",DISABLED:"disabled"},p={REGISTERED:"plugin:registered",BEFORE_INITIALIZE:"plugin:before_initialize",INITIALIZED:"plugin:initialized",ERROR:"plugin:error",DISABLED:"plugin:disabled"};class l extends Error{pluginId;constructor(f,A){super(`Plugin ${f}: ${A}`);this.name="PluginError",this.pluginId=f}}class Z0{scope;ingress=new Set;closePromise=null;closed=!1;constructor(){this.scope=G.runSync(v.make())}addFinalizer(f){if(this.closed)throw Error("Cannot register a resource after plugin teardown");G.runSync(v.addFinalizer(this.scope,G.promise(async()=>{await f()})))}addIngress(f){if(this.closed)throw Error("Cannot register ingress after plugin teardown");this.ingress.add(f)}close(f=u.void){return this.closed=!0,this.closePromise??=this.closeScope(f),this.closePromise}async closeScope(f){let A,$=!1,Z=[...this.ingress].reverse();for(let X of Z)try{X.stopAdmission()}catch(Y){if(!$)A=Y;$=!0}let V=await Promise.allSettled(Z.map((X)=>Promise.resolve().then(()=>X.drain())));this.ingress.clear();let H=V.find((X)=>X.status==="rejected");if(!$&&H)A=H.reason,$=!0;let M=await G.runPromiseExit(v.close(this.scope,f));if(!$&&u.isFailure(M))A=MA.squash(M.cause),$=!0;if($)throw A}}function hU(f,A){let $=f.getMessageBus(),Z=new Set,V={send:(R)=>$.send(R),subscribe:(R,B,K)=>{let x=!0,y=new Set,Q=(cA)=>{if(!x)return{noop:!0};let M0,X0=new Promise((o)=>{M0=o});y.add(X0);let pA=()=>{y.delete(X0),M0()},Y0;try{Y0=Promise.resolve(B(cA))}catch(o){throw pA(),o}return Y0.then((o)=>{return pA(),o},(o)=>{throw pA(),o})},IA=$.subscribe(R,Q,K),Kf={type:R,originalHandler:B,stopAdmission:()=>{if(!x)return;x=!1,IA(),Z.delete(Kf)}};Z.add(Kf);try{A.addIngress({stopAdmission:Kf.stopAdmission,drain:async()=>{await Promise.all(y)}})}catch(cA){throw Kf.stopAdmission(),cA}return Kf.stopAdmission},unsubscribe:(R,B)=>{let K=[...Z].filter((x)=>x.type===R&&x.originalHandler===B);if(K.length===0){$.unsubscribe(R,B);return}for(let x of K)x.stopAdmission()}},H=f.getAttachmentRegistry(),M={...H,register:(R,B,K)=>{let x=!0,y=H.register(R,B,K),Q=()=>{if(!x)return;x=!1,y()};return A.addFinalizer(Q),Q}},X=f.getEntityRegistry(),Y=new Proxy(X,{get(R,B){let K=Reflect.get(R,B,R);if(B==="registerEntityType"&&typeof K==="function")return(...x)=>{let y=Reflect.apply(K,R,x),Q=x[0];if(typeof Q==="string")A.addFinalizer(()=>R.unregisterEntityType(Q));return y};return typeof K==="function"?K.bind(R):K}}),F=f.getProfileKindRegistry(),N=new Proxy(F,{get(R,B){let K=Reflect.get(R,B,R);if(B==="register"&&typeof K==="function")return(...x)=>{let y=Reflect.apply(K,R,x),Q=x[0];if(typeof Q==="string")A.addFinalizer(()=>R.unregisterPlugin(Q));return y};return typeof K==="function"?K.bind(R):K}}),C=f.getChannelRegistry(),W=new Proxy(C,{get(R,B){let K=Reflect.get(R,B,R);if((B==="registerDescriptor"||B==="registerDeliveryProvider")&&typeof K==="function")return(...x)=>{let y=Reflect.apply(K,R,x),Q=x[0];if(typeof Q==="string")A.addFinalizer(()=>R.unregisterPlugin(Q));return y};return typeof K==="function"?K.bind(R):K}}),_=f.getInboxRegistry(),q=new Proxy(_,{get(R,B){let K=Reflect.get(R,B,R);if(B==="registerSource"&&typeof K==="function")return(...x)=>{let y=Reflect.apply(K,R,x),Q=x[0];if(typeof Q==="string")A.addFinalizer(()=>R.unregisterPlugin(Q));return y};return typeof K==="function"?K.bind(R):K}}),E=f.getDataSourceRegistry(),I=new Proxy(E,{get(R,B){let K=Reflect.get(R,B,R);if(B==="register"&&typeof K==="function")return(...x)=>{let y=Reflect.apply(K,R,x),Q=x[0];if(typeof Q==="object"&&Q!==null&&"id"in Q&&typeof Q.id==="string"){let IA=Q.id.includes(":")?Q.id:`shell:${Q.id}`;A.addFinalizer(()=>R.unregister(IA))}return y};return typeof K==="function"?K.bind(R):K}}),r=f.getInsightsRegistry(),z=new Proxy(r,{get(R,B){let K=Reflect.get(R,B,R);if(B==="register"&&typeof K==="function")return(...x)=>{let y=Reflect.apply(K,R,x),Q=x[0];if(typeof Q==="string")A.addFinalizer(()=>R.unregister(Q));return y};return typeof K==="function"?K.bind(R):K}}),c=new Proxy(f,{get(R,B){if(B==="getMessageBus")return()=>V;if(B==="getAttachmentRegistry")return()=>M;if(B==="getEntityRegistry")return()=>Y;if(B==="getDataSourceRegistry")return()=>I;if(B==="getProfileKindRegistry")return()=>N;if(B==="getChannelRegistry")return()=>W;if(B==="getInboxRegistry")return()=>q;if(B==="getInsightsRegistry")return()=>z;let K=Reflect.get(R,B,R);return typeof K==="function"?K.bind(R):K}});return XZ(f,c),c}class U0{plugins;events;daemonRegistry;logger;projectionRegistry;resourceScopes=new Map;releasePromises=new Map;constructor(f,A,$,Z,V){this.plugins=f,this.events=A,this.daemonRegistry=$,this.projectionRegistry=Z,this.logger=V.child("PluginLifecycle")}async initializePlugin(f,A,$){let Z=this.plugins.get(f);if(!Z)throw new l(f,"Registration failed: Plugin is not registered");let V=Z.plugin,H=new Z0;H.addFinalizer(()=>A.unregisterPluginCapabilities?.(f)),H.addFinalizer(()=>A.getJobQueueService().unregisterPluginHandlers(f)),H.addFinalizer(()=>this.projectionRegistry.unregisterPlugin(f)),this.resourceScopes.set(f,H),this.releasePromises.delete(f),this.logger.debug(`Initializing plugin: ${f}`);try{this.events.emit(p.BEFORE_INITIALIZE,f,V);let M=await V.register(hU(A,H),$);return Z.status=T.INITIALIZED,this.logger.debug(`Initialized plugin: ${f}`),this.events.emit(p.INITIALIZED,f,V),M}catch(M){throw this.logger.error(`Error initializing plugin ${f}: ${S(M)}`),await this.failPluginInitialization(f,M),M}}async finalizePluginRegistration(f){let A=this.plugins.get(f);if(!A)throw new l(f,"Registration finalization failed: Plugin is not registered");if(A.status!==T.INITIALIZED)return;try{await A.plugin.finalizeRegistration?.(),this.logger.debug(`Registration finalized for plugin: ${f}`)}catch($){throw await this.failPluginInitialization(f,$),$}}async readyPlugin(f){let A=this.plugins.get(f);if(!A)throw new l(f,"Ready failed: Plugin is not registered");if(A.status!==T.INITIALIZED){this.logger.debug(`Skipping ready hook for non-initialized plugin: ${f}`);return}try{await A.plugin.ready?.(),this.logger.debug(`Ready hook completed for plugin: ${f}`)}catch($){let Z=Nf($);A.status=T.ERROR,A.error=Z;try{this.events.emit(p.ERROR,f,Z)}catch(V){this.logger.error(`Plugin error listener failed for ${f}`,V)}throw Z}}async startPluginDaemons(f){let A=this.plugins.get(f);if(A?.status!==T.INITIALIZED)return;try{await this.daemonRegistry.startPlugin(f),this.logger.debug(`Started daemons for plugin: ${f}`)}catch($){if(A.plugin.requiresDaemonStartup?.())throw $;this.logger.warn(`Daemon ${f} failed to start: ${S($)}`)}}async failPluginInitialization(f,A){let $=this.plugins.get(f);if(!$)return;let Z=$.status!==T.ERROR,V=Nf(A);if($.status=T.ERROR,$.error=V,await this.releasePluginResources(f,u.fail(A)),Z)try{this.events.emit(p.ERROR,f,V)}catch(H){this.logger.error(`Plugin error listener failed for ${f}`,H)}}async disablePlugin(f){let A=this.plugins.get(f);if(!A){this.logger.warn(`Cannot disable plugin ${f}: not registered`);return}if(A.status===T.DISABLED)return;this.logger.debug(`Disabling plugin: ${f}`);let $=A.status===T.ERROR;await this.releasePluginResources(f,u.void);let Z=this.plugins.get(f);if(!$&&Z&&Z.status!==T.DISABLED)Z.status=T.DISABLED,this.events.emit(p.DISABLED,f,Z.plugin);this.logger.debug(`Disabled plugin: ${f}`)}releasePluginResources(f,A){let $=this.releasePromises.get(f);if($)return $;let Z=this.releasePluginResourcesOnce(f,A);return this.releasePromises.set(f,Z),Z}async releasePluginResourcesOnce(f,A){let $=this.plugins.get(f);if(!$)return;try{await this.daemonRegistry.stopPlugin(f),this.logger.debug(`Stopped daemons for plugin: ${f}`)}catch(V){this.logger.error(`Failed to stop daemons for plugin: ${f}`,V)}let Z=this.resourceScopes.get(f);if(this.resourceScopes.delete(f),Z)try{await Z.close(A)}catch(V){this.logger.error(`Failed to close resources for plugin ${f}`,V)}if($.plugin.shutdown)try{await $.plugin.shutdown(),this.logger.debug(`Shutdown completed for plugin: ${f}`)}catch(V){this.logger.error(`Plugin shutdown failed for ${f}:`,V)}for(let V of this.daemonRegistry.getByPlugin(f))try{await this.daemonRegistry.unregister(V.name)}catch(H){this.logger.error(`Failed to unregister daemon ${V.name} for plugin ${f}`,H)}}}class V0{plugins;events;logger;constructor(f,A,$){this.plugins=f,this.events=A,this.logger=$.child("DependencyResolver")}async resolveInitializationOrder(f){this.logger.debug("Resolving plugin initialization order...");let A=Array.from(this.plugins.keys()),$=new Set,Z=!0;while(Z&&$.size<A.length){Z=!1;for(let M of A){if($.has(M))continue;if(!this.plugins.get(M))continue;if(this.getUnmetDependencies(M).length===0)try{await f(M),$.add(M),Z=!0}catch(F){let N=S(F);this.logger.error(`Failed to initialize plugin ${M}: ${N}`),$.add(M),Z=!0}}}let V=A.filter((M)=>!$.has(M));if(V.length>0){let M=V.join(", ");this.logger.error(`Failed to initialize plugins due to dependency issues: ${M}`);for(let X of V){let Y=this.getUnmetDependencies(X);this.logger.error(`Plugin ${X} has unmet dependencies: ${Y.join(", ")}`);let F=this.plugins.get(X);if(F)F.status=T.ERROR,F.error=new l(X,`Unmet dependencies: ${Y.join(", ")}`);this.events.emit(p.ERROR,X,F?.error)}}let H=new Set;for(let[M,X]of this.plugins)if(X.status===T.INITIALIZED)H.add(M);return this.logger.debug(`Resolved ${H.size} of ${A.length} plugins`),{initialized:H,failed:V}}getUnmetDependencies(f){let A=this.plugins.get(f);if(!A)return[];let{dependencies:$}=A,Z=[];for(let V of $){let H=this.plugins.get(V);if(!H){Z.push(V);continue}if(H.status!==T.INITIALIZED)Z.push(V)}return Z}}class H0{logger;projectionRegistry;constructor(f,A){this.logger=f.child("CapabilityRegistrar"),this.projectionRegistry=A}async registerCapabilities(f,A,$,Z){if(!Z?.executionOnly&&$.tools.length>0)f.registerTools(A,$.tools),this.logger.debug(`Registered ${$.tools.length} tools from ${A}`);if(!Z?.executionOnly&&$.resources.length>0)f.registerResources(A,$.resources),this.logger.debug(`Registered ${$.resources.length} resources from ${A}`);if(!Z?.executionOnly&&$.instructions)f.registerInstructions(A,$.instructions),this.logger.debug(`Registered instructions from ${A}`);let V=$.projectionRules??[];try{for(let H of V)this.projectionRegistry.registerRule(A,H)}catch(H){throw this.projectionRegistry.unregisterPlugin(A),H}if(V.length>0)this.logger.debug(`Registered ${V.length} projection rules from ${A}`)}}class gA{projections=new Map;rules=new Map;static createFresh(){return new gA}constructor(){}registerRule(f,A){if(!Object.isFrozen(A))throw Error(`Projection rule "${A.id}" must be created with defineProjectionRule`);let $=this.projections.get(A.id);if($)throw Error(`Projection "${A.id}" is already registered by "${$.pluginId}"`);let Z={id:A.id,pluginId:f,targetType:A.targetType,sources:A.sources.map((H)=>({kind:H.kind,types:[...H.types],...H.excludeTypes?{excludeTypes:[...H.excludeTypes]}:{}}))};this.projections.set(A.id,Z),this.rules.set(A.id,A);let V=!0;return()=>{if(!V)return;if(V=!1,this.rules.get(A.id)===A)this.rules.delete(A.id);if(this.projections.get(A.id)===Z)this.projections.delete(A.id)}}unregisterPlugin(f){for(let[A,$]of this.projections)if($.pluginId===f)this.projections.delete(A),this.rules.delete(A)}list(){return Array.from(this.projections.values()).sort((f,A)=>f.id.localeCompare(A.id)).map(_V)}listRules(){return[...this.rules.values()].sort((f,A)=>f.id.localeCompare(A.id))}validate(f){let A=this.list(),$=new Set(f.map(({type:M})=>M));for(let M of A)if(!$.has(M.targetType))throw Error(`Projection "${M.id}" targets unregistered entity type "${M.targetType}"`);let Z=f.filter(({projectionSource:M})=>M).map(({type:M})=>M).sort(),V=BV(A,Z),H=OV(A,V)[0];if(H){let M=wV(H,V);throw Error(`Projection cycle is not supported: ${[...M,M[0]].join(" -> ")}`)}return DV({projections:A,edges:V,unknownSourceTypes:WV(A,$)})}}function WV(f,A){let $=[];for(let Z of f){let V=[...new Set(Z.sources.flatMap((H)=>[...H.types,...H.excludeTypes??[]]).filter((H)=>H!=="*"&&!A.has(H)))].sort();if(V.length>0)$.push({projectionId:Z.id,types:V})}return $}function DV(f){for(let A of f.projections){for(let $ of A.sources){if(Object.freeze($.types),$.excludeTypes)Object.freeze($.excludeTypes);Object.freeze($)}Object.freeze(A.sources),Object.freeze(A)}for(let A of f.edges)Object.freeze(A.causes),Object.freeze(A);for(let A of f.unknownSourceTypes)Object.freeze(A.types),Object.freeze(A);return Object.freeze(f.unknownSourceTypes),Object.freeze(f.projections),Object.freeze(f.edges),Object.freeze(f)}function _V(f){return{...f,sources:f.sources.map((A)=>({...A,types:[...A.types],...A.excludeTypes?{excludeTypes:[...A.excludeTypes]}:{}}))}}function BV(f,A){let $=new Map;for(let Z of f)for(let V of f){let H=kV(Z,V,A);if(H.length===0)continue;$.set(`${Z.id}\x00${V.id}`,new Set(H))}return Array.from($,([Z,V])=>{let[H="",M=""]=Z.split("\x00");return{from:H,to:M,causes:[...V].sort()}}).sort((Z,V)=>Z.from.localeCompare(V.from)||Z.to.localeCompare(V.to))}function kV(f,A,$){let Z=[];for(let V of A.sources){let H=new Set(V.excludeTypes??[]);if((V.types.includes("*")?[...V.types.filter((X)=>X!=="*"),...$]:V.types).includes(f.targetType)&&!H.has(f.targetType))Z.push(`entity:${f.targetType}`)}return[...new Set(Z)]}function OV(f,A){let $=f.map(({id:C})=>C).sort(),Z=vU($,A),V=new Map,H=new Map,M=[],X=new Set,Y=[],F=0,N=(C)=>{V.set(C,F),H.set(C,F),F++,M.push(C),X.add(C);for(let E of Z.get(C)??[])if(!V.has(E))N(E),H.set(C,Math.min(H.get(C)??0,H.get(E)??0));else if(X.has(E))H.set(C,Math.min(H.get(C)??0,V.get(E)??0));if(H.get(C)!==V.get(C))return;let W=[],_;do{if(_=M.pop(),!_)break;X.delete(_),W.push(_)}while(_!==C);let q=Z.get(C)?.includes(C)??!1;if(W.length>1||q)Y.push(W.sort())};for(let C of $)if(!V.has(C))N(C);return Y.sort((C,W)=>(C[0]??"").localeCompare(W[0]??""))}function wV(f,A){let $=new Set(f),Z=vU(f,A),V=[...f].sort()[0];if(!V)return[];if(Z.get(V)?.includes(V))return[V];let H=(M,X)=>{for(let Y of Z.get(M)??[]){if(!$.has(Y))continue;if(Y===V)return X;if(X.includes(Y))continue;let F=H(Y,[...X,Y]);if(F)return F}return};return H(V,[V])??[...f].sort()}function vU(f,A){let $=new Map;for(let Z of f)$.set(Z,[]);for(let Z of A){let V=$.get(Z.from);if(V&&!V.includes(Z.to))V.push(Z.to)}for(let Z of $.values())Z.sort();return $}async function bU(f){let $=(await G.runPromise(G.all(f.map((Z)=>G.either(G.tryPromise({try:Z,catch:(V)=>V}))),{concurrency:"unbounded"}))).find(gU.isLeft);if($)throw $.left}class uA{plugins=new Map;logger;events=new jU;daemonRegistry;shell=null;initializedPluginIds=[];pluginLifecycle;dependencyResolver;capabilityRegistrar;projectionRegistry=gA.createFresh();projectionGraph;static createFresh(f,A){return new uA(f,A)}setShell(f){this.shell=f}constructor(f,A){this.logger=f.child("PluginManager"),this.events=new jU,this.daemonRegistry=A,this.pluginLifecycle=new U0(this.plugins,this.events,this.daemonRegistry,this.projectionRegistry,f),this.dependencyResolver=new V0(this.plugins,this.events,f),this.capabilityRegistrar=new H0(f,this.projectionRegistry)}registerPlugin(f){if(!f.id)throw new l("unknown","Registration failed: Plugin must have an id");if(this.logger.debug(`Registering plugin: ${f.id} (${f.version})`),this.plugins.has(f.id)){let V=this.plugins.get(f.id)?.plugin.version;throw new l(f.id,`Registration failed: Plugin is already registered with version ${V}`)}let A=f.dependencies??[],$={plugin:f,status:T.REGISTERED,dependencies:A};this.plugins.set(f.id,$),this.logger.debug(`Registered plugin: ${f.id} (${f.version})`),this.events.emit(p.REGISTERED,f.id,f)}async initializePlugins(f){this.logger.debug("Initializing plugins..."),this.initializedPluginIds=[];let A=await this.dependencyResolver.resolveInitializationOrder(async($)=>{await this.initializePlugin($,f)});this.logger.debug(`Initialized ${A.initialized.size} of ${this.plugins.size} plugins`)}async initializePlugin(f,A){if(!this.shell)throw new l(f,"Cannot initialize plugin: Shell not set. Call setShell() first.");let $=this.shell;try{let Z=await this.pluginLifecycle.initializePlugin(f,$,A);await this.capabilityRegistrar.registerCapabilities($,f,Z,{executionOnly:A?.executionOnly}),this.initializedPluginIds.push(f)}catch(Z){throw await this.pluginLifecycle.failPluginInitialization(f,Z),Z}}async finalizePluginRegistrations(){this.logger.debug("Finalizing plugin registrations...");for(let $ of this.initializedPluginIds)await this.pluginLifecycle.finalizePluginRegistration($);if(!this.shell)throw Error("Cannot validate projections before the shell is set");let f=this.shell.getEntityRegistry(),A=this.projectionRegistry.validate(f.getAllEntityTypes().map(($)=>{let Z=f.getEntityTypeConfig($);return{type:$,projectionSource:Z.projectionSource!==!1&&Z.projectionSourceRole!=="excluded"}}));this.projectionGraph=A;for(let $ of A.unknownSourceTypes)this.logger.warn("Projection declares entity source types no installed plugin registers",{projectionId:$.projectionId,types:$.types});this.logger.debug("Validated projection graph",{projections:A.projections.length,edges:A.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 bU(this.initializedPluginIds.map((f)=>()=>this.pluginLifecycle.readyPlugin(f)))}catch(f){for(let A of this.initializedPluginIds){let $=this.plugins.get(A);if($?.status===T.ERROR)await this.pluginLifecycle.failPluginInitialization(A,$.error??f)}throw f}}async startPluginDaemons(){this.logger.debug("Starting plugin daemons..."),await bU(this.initializedPluginIds.map((f)=>()=>this.pluginLifecycle.startPluginDaemons(f)))}getPlugin(f){return this.plugins.get(f)?.plugin}getPluginStatus(f){return this.plugins.get(f)?.status}hasPlugin(f){return this.plugins.has(f)}isPluginInitialized(f){return this.plugins.get(f)?.status===T.INITIALIZED}getAllPluginIds(){return Array.from(this.plugins.keys())}getAllPlugins(){return new Map(this.plugins)}getFailedPlugins(){return Array.from(this.plugins.entries()).filter((f)=>f[1].status===T.ERROR&&f[1].error!==void 0).map(([f,A])=>({id:f,error:A.error}))}getPluginPackageName(f){return this.plugins.get(f)?.plugin.packageName}async disablePlugin(f){await this.pluginLifecycle.disablePlugin(f)}async shutdownPlugins(){let f=new Set;for(let A of[...this.initializedPluginIds].reverse())await this.disablePlugin(A),f.add(A);for(let A of[...this.plugins.keys()].reverse())if(!f.has(A))await this.disablePlugin(A)}on(f,A){this.events.on(f,A)}once(f,A){this.events.once(f,A)}off(f,A){this.events.off(f,A)}getEventEmitter(){return this.events}}export{d1 as cc,s as dc,rf as ec,tf as fc,L as gc,O as hc,Cf as ic,M$ as jc,X$ as kc,Y$ as lc,L$ as mc,wf as nc,F$ as oc,C$ as pc,N$ as qc,J as rc,h as sc,e as tc,ff as uc,R0 as vc,K0 as wc,sU as xc,cf as yc,uU as zc,IU as Ac,nA as Bc,dA as Cc,ZA as Dc,u1 as Ec,HA as Fc,$Z as Gc,I1 as Hc,_$ as Ic,sA as Jc,c1 as Kc,lU as Lc,p1 as Mc,l1 as Nc,n1 as Oc,LA as Pc,NZ as Qc,KZ as Rc,PZ as Sc,DZ as Tc,_Z as Uc,f8 as Vc,A8 as Wc,O$ as Xc,CA as Yc,Xf as Zc,X8 as _c,w$ as $c,sf as ad,af as bd,K1 as cd,SZ as dd,F1 as ed,D1 as fd,x0 as gd,J0 as hd,Q0 as id,_1 as jd,y$ as kd,h$ as ld,hZ as md,Gf as nd,KA as od,PA as pd,Qf as qd,WA as rd,pZ as sd,I$ as td,lZ as ud,Rf as vd,sZ as wd,aZ as xd,rZ as yd,oZ as zd,eZ as Ad,c$ as Bd,p$ as Cd,ZU as Dd,l$ as Ed,kA as Fd,HU as Gd,OA as Hd,n$ as Id,MU as Jd,XU as Kd,LU as Ld,FU as Md,wA as Nd,GU as Od,RU as Pd,JA as Qd,Ef as Rd,mf as Sd,KU as Td,PU as Ud,WU as Vd,o$ as Wd,Sf as Xd,BU as Yd,kU as Zd,OU as _d,wU as $d,xU as ae,MV as be,JU as ce,t6 as de,YV as ee,t$ as fe,FV as ge,zA as he,yA as ie,hA as je,qU as ke,Yf as le,jA as me,vf as ne,TU as oe,$0 as pe,mU as qe,KV as re,PV as se,l as te,uA as ue};
|
|
18
18
|
|
|
19
|
-
//# debugId=
|
|
20
|
-
//# sourceMappingURL=index-
|
|
19
|
+
//# debugId=351DED77675943DF64756E2164756E21
|
|
20
|
+
//# sourceMappingURL=index-q41qdf7x.js.map
|