@rizom/brain 0.2.0-alpha.263 → 0.2.0-alpha.264
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 +941 -941
- package/dist/chunks/{app-g6q939g3.js → app-1ndrgdmg.js} +2 -2
- package/dist/chunks/{blog-post-adapter-0qsz1np7.js → blog-post-adapter-2gw2r57p.js} +2 -2
- package/dist/chunks/index-1bnxn2w3.js +20 -0
- package/dist/chunks/{index-jpbc5wsq.js.map → index-1bnxn2w3.js.map} +3 -3
- package/dist/chunks/{index-kjmk8h5s.js → index-30xjh0hd.js} +8 -8
- package/dist/chunks/{index-kjmk8h5s.js.map → index-30xjh0hd.js.map} +1 -1
- package/dist/chunks/{index-jbep378h.js → index-b2segdse.js} +3 -3
- package/dist/chunks/{index-jbep378h.js.map → index-b2segdse.js.map} +1 -1
- package/dist/chunks/{index-pfdzna2q.js → index-nd3sc6wc.js} +3 -3
- package/dist/chunks/{index-pfdzna2q.js.map → index-nd3sc6wc.js.map} +1 -1
- package/dist/chunks/{index-m02t96vk.js → index-w0gcaka3.js} +3 -3
- package/dist/chunks/{linkedin-template-xm5pp9zz.js → linkedin-template-zt2v1zj3.js} +2 -2
- package/dist/chunks/{rss-datasource-7fc3082p.js → rss-datasource-f41cn0ma.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/index-jpbc5wsq.js +0 -20
- /package/dist/chunks/{app-g6q939g3.js.map → app-1ndrgdmg.js.map} +0 -0
- /package/dist/chunks/{blog-post-adapter-0qsz1np7.js.map → blog-post-adapter-2gw2r57p.js.map} +0 -0
- /package/dist/chunks/{index-m02t96vk.js.map → index-w0gcaka3.js.map} +0 -0
- /package/dist/chunks/{linkedin-template-xm5pp9zz.js.map → linkedin-template-zt2v1zj3.js.map} +0 -0
- /package/dist/chunks/{rss-datasource-7fc3082p.js.map → rss-datasource-f41cn0ma.js.map} +0 -0
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
// @bun
|
|
2
|
-
import{$e as xf,Af as v,Bf as $A,Cf as G,Df as Hf,Ef as UA,Gf as ZA,Pf as bf,Re as g,Sf as l$,Te as x,Ue as _,Vf as vf,We as E,Xe as Ff,Xf as D$,Ye as OZ,Yf as Tf,_e as Jf,af as X$,ag as uf,bg as If,cf as Y$,df as zZ,ef as $f,ff as i,fg as jf,hf as j,hg as gA,if as O,jf as t,lf as b,pf as cf,qf as df,uf as c0,xf as MA,zf as u}from"./index-316pn0s9.js";import{sg as ef}from"./index-ba0xxwak.js";import{Lg as ZU,Og as iA}from"./index-pqwt7pdt.js";import{eh as UU}from"./index-1ty28bth.js";import{Ah as YU,Eh as Af,Fh as RZ,Gh as vZ,Hh as VZ,Oh as PZ,Ri as S$,Si as yU,Uh as S,Ui as WA,Vh as Cf,Wh as EU,Xh as Mf,Yh as Uf,_h as B$,ci as zU,di as Qf,ii as Df,li as NA,vh as sf,wh as af,xh as of}from"./index-3w937c1f.js";import{fj as U}from"./index-329h2b0h.js";var p0=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:iA}),l0=U.object({id:U.string(),conversationId:U.string(),role:Mf,content:U.string(),timestamp:U.string(),metadata:iA});var sA=U.object({name:U.string(),role:U.string(),purpose:U.string(),values:U.array(U.string())}),aA=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 GZ(f){return x`count(${f||x.raw("*")})`.mapWith(Number)}function rA(f){return PZ(oA(f))}function oA(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)=>oA(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)}:${oA(H,$)}`).join(",")}}`}function tA(f){if(f!==null&&typeof f==="object"){for(let A of Object.values(f))tA(A);Object.freeze(f)}return f}var d0=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 i0(f){let A=d0.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,L={kind:"entity",types:V,...H?{excludeTypes:H}:{}};return Object.freeze(L)});return Object.freeze({id:A.id,version:A.version,sources:Object.freeze($),targetType:A.targetType,inputSchema:f.inputSchema,selectInput:async(Z,V,H)=>{let L=await f.selectInput(Z,V,H),X=uf.parse(L);return tA(f.inputSchema.parse(X))},fingerprint:rA,derive:async(Z,V,H)=>{let L=f.inputSchema.parse(Z),X=U.array(If).parse(await f.derive(L,V,H));for(let Y of X){let M=Y.operation==="upsert"?Y.entity.entityType:Y.entityType;if(M!==A.targetType)throw Error(`Projection rule "${A.id}" cannot write entity type "${M}"`)}return tA(X)}})}var NZ={digest:"conversation:digest"};var w=t("conversations",{id:O("id").primaryKey(),sessionId:O("session_id").notNull(),interfaceType:O("interface_type").notNull(),channelId:O("channel_id").notNull(),personId:O("person_id"),started:O("started").notNull(),lastActive:O("last_active").notNull(),metadata:O("metadata"),created:O("created").notNull(),updated:O("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:O("id").primaryKey(),conversationId:O("conversation_id").notNull().references(()=>w.id,{onDelete:"cascade"}),role:O("role").notNull(),content:O("content").notNull(),timestamp:O("timestamp").notNull(),metadata:O("metadata")},(f)=>({conversationIdx:b("idx_messages_conversation").on(f.conversationId),timestampIdx:b("idx_messages_timestamp").on(f.timestamp)})),e=t("summary_tracking",{conversationId:O("conversation_id").primaryKey().references(()=>w.id,{onDelete:"cascade"}),lastSummarizedAt:O("last_summarized_at"),lastMessageId:O("last_message_id"),messagesSinceSummary:j("messages_since_summary").default(0),updated:O("updated").notNull()});function WZ(f){return cf({url:f.url,schema:{conversations:w,messages:h,summaryTracking:e},authToken:f.authToken,authTokenEnv:"CONVERSATION_DATABASE_AUTH_TOKEN"})}var s0=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 s0.parse(f)}var lf="conversation:messageAdded",eA="conversation:started",Wf=U.object({identity:Af,interfaceType:U.string(),role:Mf,displayName:U.string().optional(),username:U.string().optional(),isBot:U.boolean().optional()}),a0=U.preprocess(o0,Wf);function o0(f){if(!pf(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:RZ({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 Rf=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()}),BZ=U.looseObject({actor:a0.optional(),source:Rf.optional()});function _Z(f){if(typeof f==="string")try{let A=JSON.parse(f);return pf(A)?A:null}catch{return null}return pf(f)?f:null}function r0(f){if(f.role!=="assistant")return!1;if(f.content.trim().length===0)return!1;let A=_Z(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(!pf(V))return!1;if(V.kind==="tool-approval")return!0;return V.kind==="actions"&&V.id==="actions:upload-intent"})}function pf(f){return typeof f==="object"&&f!==null&&!Array.isArray(f)}var t0=U.object({id:U.string(),conversationId:U.string(),role:U.string(),content:U.string(),timestamp:U.string(),metadata:U.string().nullable()}),DZ=U.object({conversationId:U.string(),messageCount:U.number(),messages:U.array(t0),windowStart:U.number(),windowEnd:U.number(),windowSize:U.number(),timestamp:U.string()});class nf{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 df(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 nf(f,A,$,Z)}static createFreshFromConfig(f,A,$,Z){let{db:V,client:H,url:L}=WZ($),X=new nf(V,f,A,Z);return X.dbClient=H,X.dbUrl=L,X}async startConversation(f){let{sessionId:A,interfaceType:$,channelId:Z,personId:V,metadata:H}=f,L=new Date().toISOString();if(await this.getConversation(A))return await this.db.update(w).set({lastActive:L,updated:L}).where(_(w.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:L,lastActive:L,created:L,updated:L,metadata:JSON.stringify(H)};await this.db.insert(w).values(Y);let M={conversationId:A,messagesSinceSummary:0,updated:L};return await this.db.insert(e).values(M),this.logger.debug("Started new conversation",{conversationId:A,sessionId:A,interfaceType:$}),await this.messageBus.send({type:eA,payload:{conversationId:A,sessionId:A,interfaceType:$,timestamp:L},sender:"conversation-service",broadcast:!0}),A}async addMessage(f){let{conversationId:A,role:$,content:Z,metadata:V}=f,H=new Date().toISOString(),L=g(12),X={id:L,conversationId:A,role:$,content:Z,timestamp:H,metadata:V?JSON.stringify(V):null};await this.db.insert(h).values(X),await this.db.update(w).set({lastActive:H,updated:H}).where(_(w.id,A)),await this.db.update(e).set({messagesSinceSummary:x`${e.messagesSinceSummary} + 1`,lastMessageId:L,updated:H}).where(_(e.conversationId,A)),this.logger.debug("Added message to conversation",{conversationId:A,role:$,messageId:L}),await this.messageBus.send({type:lf,payload:{conversationId:A,messageId:L,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(_(h.conversationId,f)).orderBy($f(h.timestamp)).limit(H).offset(V)}else return(await this.db.select().from(h).where(_(h.conversationId,f)).orderBy(i(h.timestamp)).limit($)).reverse()}async getConversation(f){return(await this.db.select().from(w).where(_(w.id,f)).limit(1))[0]??null}async listConversations(f={}){let{limit:A=100,updatedAfter:$,interfaceType:Z,sessionId:V,channelId:H,personId:L}=f,X=[$?OZ(w.updated,$):void 0,Z?_(w.interfaceType,Z):void 0,V?_(w.sessionId,V):void 0,H?_(w.channelId,H):void 0,L?_(w.personId,L):void 0].filter((M)=>M!==void 0),Y=this.db.select().from(w).orderBy(i(w.lastActive)).limit(A);if(X.length===0)return Y;return Y.where(E(...X))}async searchConversations(f,A){let $=`%${f.toLowerCase()}%`;return(await this.db.selectDistinct({conversation:w}).from(w).leftJoin(h,_(h.conversationId,w.id)).where(A?x`lower(${h.content}) LIKE ${$} AND ${w.sessionId} = ${A}`:x`lower(${h.content}) LIKE ${$}`).orderBy(i(w.lastActive))).map((V)=>V.conversation)}async countMessages(f){let[A]=await this.db.select({count:GZ()}).from(h).where(_(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(w).set({metadata:JSON.stringify(Z),updated:$}).where(_(w.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(w).where(_(w.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,L=await this.getMessages(f,{range:{start:V,end:H}}),X={conversationId:f,messageCount:A,messages:L,windowStart:V,windowEnd:H,windowSize:L.length,timestamp:$};await this.messageBus.send({type:NZ.digest,payload:X,sender:"conversation-service",broadcast:!0}),this.logger.debug("Broadcast conversation digest",{conversationId:f,messageCount:A,windowStart:V,windowEnd:H,windowSize:L.length})}}var f$=U.object({kind:U.string().min(1),id:U.string().min(1)}),kZ=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:f$.optional()}),K1=U.custom((f)=>f instanceof Uint8Array),C1=U.object({kind:U.literal("file"),filename:U.string().min(1),mediaType:U.string().min(1),data:K1,sizeBytes:U.number().nonnegative().optional(),source:f$.optional()}),JZ=U.discriminatedUnion("kind",[kZ,C1]),G1=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:Wf.optional(),source:Rf.optional(),attachments:U.array(JZ).optional()});var P1=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()}),xZ=U.object({name:U.string(),pluginId:U.string(),status:U.string(),health:P1.optional()});var QZ=U.enum(["admin","trusted","public"]),Bf=U.object({label:U.string(),url:U.string(),pluginId:U.string(),priority:U.number().default(100),visibility:QZ.default("public")}),A$=U.enum(["human","agent","admin","protocol"]),$$=U.enum(["available","coming-soon","disabled"]),_f=U.object({id:U.string(),label:U.string(),description:U.string().optional(),href:U.string(),kind:A$,pluginId:U.string(),priority:U.number().default(100),visibility:QZ.default("public"),status:$$.default("available")}),rf=U.object({entityType:U.string(),count:U.number()}),wZ=U.object({model:U.string(),version:U.string(),uptime:U.number(),entities:U.number(),entityCounts:U.array(rf),embeddings:U.number(),ai:U.object({model:U.string(),embeddingModel:U.string()}),daemons:U.array(xZ),endpoints:U.array(Bf),interactions:U.array(_f)});var N1=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:N1.optional()}),R1=U.object({model:U.string(),version:U.string(),uptime:U.number(),entities:U.number(),entityCounts:U.array(rf),embeddings:U.number(),ai:U.object({model:U.string(),embeddingModel:U.string()}),daemons:U.array(W1),endpoints:U.array(Bf),interactions:U.array(_f)});var TZ=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()}),qZ=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()})}),mZ=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:qZ.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()})}),B1=U.object({status:U.enum(["ready","not_ready"]),operationalStatus:U.enum(["operational","degraded"]),checkedAt:U.iso.datetime(),checks:U.array(TZ),resources:mZ});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 L=$+H.progress/(H.total??100)*V;await this.callback({...H,progress:L,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 _1=U.object({enabled:U.boolean().describe("Whether the plugin is enabled"),debug:U.boolean().describe("Enable debug logging for this plugin")});class tf extends Error{pluginId;issues;constructor(f,A){super(`Invalid plugin config for ${f}`);this.name="PluginConfigValidationError",this.pluginId=f,this.issues=A}}var D1=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??ef.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 tf(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 $=D1.safeParse(A.payload);if(!$.success)return{success:!1,error:"Invalid tool execution request format"};let{toolName:Z,args:V,progressToken:H,hasProgress:L,interfaceType:X,actor:Y,displayName:M,conversationId:C,channelId:K,channelName:R,runId:B,toolCallId:q,userPermissionLevel:k,isAnchor:I,signal:o}=$.data,c=(await this.getTools()).find((W)=>W.name===Z);if(!c)return{success:!1,error:`Tool not found: ${Z}`};let N={interfaceType:X,actor:Y,...M&&{displayName:M},...C&&{conversationId:C},...K&&{channelId:K},...R&&{channelName:R},...B&&{runId:B},...q&&{toolCallId:q},...k&&{userPermissionLevel:k},...I!==void 0&&{isAnchor:I},...o&&{signal:o},...L&&H!==void 0&&{progressToken:H,sendProgress:async(W)=>{await f.messaging.send({type:Df.progress(this.id),payload:{progressToken:H,notification:W}})}}};return{success:!0,data:await c.handler(V,N)}}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 Z$=U.enum(["file_operations","content_operations","data_processing","batch_processing"]),k1=U.object({pluginId:U.string().optional(),progressToken:U.union([U.string(),U.number()]).optional(),operationType:Z$,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:Z$,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()}),gH=U.enum(["none","skip","replace","coalesce"]);var U$=U.enum(["pending","processing","completed","failed"]),SZ=U.enum(["completed","failed"]),P={PENDING:"pending",PROCESSING:"processing",COMPLETED:"completed",FAILED:"failed"},J1=U.object({id:U.string(),type:U.string(),status:U$,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()}),x1=U.object({jobId:U.string(),type:U.string(),status:SZ,result:U.unknown().optional(),error:U.string().optional()}),V$=U.object({success:U.literal(!1),error:U.string().optional()}),fA=U.object({id:U.string(),type:U.enum(["job","batch"]),status:U$,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 F=t("job_queue",{id:O("id").primaryKey().$defaultFn(()=>g()),type:O("type").notNull(),data:O("data").notNull(),result:O("result",{mode:"json"}),progress:O("progress",{mode:"json"}).$type(),source:O("source"),metadata:O("metadata",{mode:"json"}).$type().notNull(),status:O("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:O("lastError"),createdAt:j("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:j("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:j("startedAt"),completedAt:j("completedAt"),attemptId:O("attemptId"),workerSlotId:O("workerSlotId"),workerSessionId:O("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)})),J=t("job_worker_sessions",{slotId:O("slotId").primaryKey(),sessionId:O("sessionId").notNull().unique(),startedAt:j("startedAt").notNull(),heartbeatAt:j("heartbeatAt").notNull()},(f)=>({heartbeatIdx:b("idx_job_worker_sessions_heartbeat").on(f.heartbeatAt)}));function EZ(f){return cf({url:f.url,schema:{jobQueue:F,jobWorkerSessions:J},authToken:f.authToken,authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN"})}class H${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()}),Of=15000;var w1=U.looseObject({deduplicationKey:U.string().optional()});class L${findDuplicate(f,A,$){if(!A||A==="none")return null;let Z=this.filterByDeduplicationKey(f,$).sort((H,L)=>L.createdAt-H.createdAt||L.id.localeCompare(H.id)),V=Z.find((H)=>H.status===P.PENDING)??null;if(A==="skip"||A==="replace")return V;return V??Z[0]??null}filterByDeduplicationKey(f,A){if(!A)return f;return f.filter(($)=>{let Z=w1.safeParse($.metadata);return Z.success&&Z.data.deduplicationKey===A})}}var kf=3,AA=new Map;class M${db;transactionClient;databaseUrl;logger;deduplicator=new L$;constructor(f,A,$,Z){this.db=f,this.transactionClient=A,this.databaseUrl=$,this.logger=Z.child("JobQueueRepository")}async insert(f){await this.db.insert(F).values(f)}async enqueueAtomic(f){let A=AA.get(this.databaseUrl),$=()=>{},Z=new Promise((V)=>{$=V});AA.set(this.databaseUrl,Z),await A;try{let V=await this.acquireWriteTransaction(f);try{let H=await this.decideEnqueue(V,f);return await this.commitWriteTransaction(V,f),H}catch(H){if(!V.closed)try{await V.rollback()}catch(L){this.logger.error("Failed to roll back atomic enqueue",{type:f.jobData.type,rollbackError:L})}throw H}finally{V.close()}}finally{if($(),AA.get(this.databaseUrl)===Z)AA.delete(this.databaseUrl)}}async decideEnqueue(f,A){let{jobData:$,strategy:Z,deduplicationKey:V,beforeInsert:H}=A,L=Z??"none",X=async()=>{await H?.(),await this.insertJob(f,$)};if(L==="none")return await X(),{kind:"inserted",jobId:$.id};let Y=await this.getActiveDeduplicationCandidates(f,$.type),M=this.deduplicator.findDuplicate(Y,L,V);if(!M)return await X(),{kind:"inserted",jobId:$.id};if(L==="skip")return{kind:"skipped",jobId:M.id};if(L==="coalesce"){if((await f.execute({sql:"UPDATE `job_queue` SET `scheduledFor` = ? WHERE `id` = ? AND `status` = ?",args:[Date.now(),M.id,M.status]})).rowsAffected!==1)throw Error(`Atomic coalesce lost selected job ${M.id}`);return{kind:"coalesced",jobId:M.id}}await H?.();let C=Date.now();if((await f.execute({sql:"UPDATE `job_queue`\n SET `status` = ?,\n `lastError` = ?,\n `completedAt` = ?,\n `runtimeUpdatedAt` = max(?, coalesce((SELECT max(`runtimeUpdatedAt`) FROM `job_queue`), 0) + 1)\n WHERE `id` = ? AND `status` = ?",args:[P.FAILED,"Replaced by newer job",C,C,M.id,P.PENDING]})).rowsAffected!==1)throw Error(`Atomic replace lost selected job ${M.id}`);return await this.insertJob(f,$),{kind:"replaced",jobId:$.id,replacedJobId:M.id}}async getActiveDeduplicationCandidates(f,A){return(await f.execute({sql:"SELECT `id`, `status`, `createdAt`, `metadata`\n FROM `job_queue`\n WHERE `type` = ? AND `status` IN (?, ?)",args:[A,P.PENDING,P.PROCESSING]})).rows.map((Z)=>this.parseDeduplicationCandidate(Z))}parseDeduplicationCandidate(f){let{id:A,status:$,createdAt:Z,metadata:V}=f;if(typeof A!=="string"||$!==P.PENDING&&$!==P.PROCESSING||typeof Z!=="number"&&typeof Z!=="bigint"||typeof V!=="string")throw Error("Invalid active job row returned during atomic enqueue");let H=JSON.parse(V);return{id:A,status:$,createdAt:Number(Z),metadata:H}}async insertJob(f,A){if((await f.execute({sql:"INSERT INTO `job_queue` (\n `id`, `type`, `data`, `result`, `source`, `metadata`,\n `status`, `priority`, `retryCount`, `maxRetries`,\n `lastError`, `createdAt`, `scheduledFor`, `startedAt`,\n `completedAt`\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",args:[A.id,A.type,A.data,this.serializeJson(A.result),A.source,JSON.stringify(A.metadata),A.status,A.priority,A.retryCount,A.maxRetries,A.lastError,A.createdAt,A.scheduledFor,A.startedAt,A.completedAt]})).rowsAffected!==1)throw Error(`Atomic enqueue did not insert job ${A.id}`)}serializeJson(f){if(f===void 0||f===null)return null;return JSON.stringify(f)}async commitWriteTransaction(f,A){let $;for(let Z=1;Z<=kf;Z++)try{await f.commit();return}catch(V){if(!this.isSerializationConflict(V)||f.closed)throw V;if($=V,Z<kf)await new Promise((H)=>setTimeout(H,Z*5))}throw this.transactionConflictError("commit",A,$)}async acquireWriteTransaction(f){let A;for(let $=1;$<=kf;$++)try{return await this.transactionClient.transaction("write")}catch(Z){if(!this.isSerializationConflict(Z))throw Z;if(A=Z,$<kf)await new Promise((V)=>setTimeout(V,$*5))}throw this.transactionConflictError("acquire",f,A)}transactionConflictError(f,A,$){let Z=A.strategy??"none",V=A.deduplicationKey?"present":"absent";return Error(`Failed to ${f} atomic enqueue transaction for type "${A.jobData.type}" after ${kf} attempts (strategy: ${Z}, key: ${V})`,{cause:$})}isSerializationConflict(f){for(let A=f;A!==void 0;){let $=typeof A==="object"&&A!==null&&"code"in A?String(A.code):"",Z=S(A,"");if(/SQLITE_(?:BUSY|LOCKED)/u.test($)||/SQLITE_(?:BUSY|LOCKED)|database is locked|transaction (?:busy|conflict)/iu.test(Z))return!0;A=A instanceof Error?A.cause:void 0}return!1}async startWorkerSession(f,A,$=Date.now()){await this.db.insert(J).values({slotId:f,sessionId:A,startedAt:$,heartbeatAt:$}).onConflictDoUpdate({target:J.slotId,set:{sessionId:A,startedAt:$,heartbeatAt:$}})}async heartbeatWorkerSession(f,A,$=Date.now()){return(await this.db.update(J).set({heartbeatAt:$}).where(E(_(J.slotId,f),_(J.sessionId,A))).returning({slotId:J.slotId})).length===1}async endWorkerSession(f,A){return(await this.db.delete(J).where(E(_(J.slotId,f),_(J.sessionId,A))).returning({slotId:J.slotId})).length===1}async complete(f,A,$){let Z=Date.now(),H=(await this.db.update(F).set({status:P.COMPLETED,result:A,lastError:null,completedAt:Z,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(Z)}).where(this.attemptWriteGuard(f,$)).returning({id:F.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(F).set({data:JSON.stringify(A)}).where(this.attemptWriteGuard(f,$)).returning({id:F.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(F).set({attemptHeartbeatAt:Z,runtimeUpdatedAt:this.nextRuntimeUpdatedAt(Z),progress:$}).where(this.attemptWriteGuard(f,A)).returning({id:F.id})).length===1}async renewAttemptLease(f,A,$,Z){return(await this.db.update(F).set({attemptHeartbeatAt:$,leaseExpiresAt:$+Z}).where(this.attemptWriteGuard(f,A)).returning({id:F.id})).length===1}async fail(f,A,$,Z=Date.now()){let H=(await this.db.select({retryCount:F.retryCount,maxRetries:F.maxRetries,type:F.type,scheduledFor:F.scheduledFor,startedAt:F.startedAt,runtimeUpdatedAt:F.runtimeUpdatedAt}).from(F).where(this.attemptWriteGuard(f,$)).limit(1))[0];if(!H)return!1;let L=H.retryCount<H.maxRetries,X=L?H.retryCount+1:H.retryCount,Y=Math.min(1000*2**H.retryCount,60000),M=L?Z+Y:H.scheduledFor;if((await this.db.update(F).set({status:L?P.PENDING:P.FAILED,retryCount:X,lastError:A.message,scheduledFor:M,completedAt:L?null:Z,runtimeUpdatedAt:L?H.runtimeUpdatedAt:this.nextRuntimeUpdatedAt(Z),startedAt:L?null:H.startedAt,attemptId:null,workerSlotId:null,workerSessionId:null,leaseExpiresAt:null,attemptHeartbeatAt:null}).where(E(this.attemptWriteGuard(f,$),_(F.retryCount,H.retryCount))).returning({id:F.id})).length!==1)return!1;if(L)this.logger.debug("Job scheduled for retry",{jobId:f,retryCount:X,backoffMs:Y,scheduledFor:new Date(M).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(F).where(_(F.id,f)).limit(1))[0]??null}async getStatusByEntityId(f){return(await this.db.select().from(F).where(x`json_extract(${F.data}, '$.id') = ${f}`).orderBy(i(F.createdAt)).limit(1))[0]??null}async getStats(){let f=await this.db.select({status:F.status,count:x`count(*)`}).from(F).groupBy(F.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-Of,[$,Z,V]=await Promise.all([this.db.select({type:F.type,status:F.status,count:x`count(*)`}).from(F).groupBy(F.type,F.status),this.db.select({oldestPendingAt:x`min(case when ${F.status} = ${P.PENDING} then ${F.createdAt} end)`,oldestProcessingAt:x`min(case when ${F.status} = ${P.PROCESSING} then ${F.startedAt} end)`,staleLeaseCount:x`coalesce(sum(case when ${F.status} = ${P.PROCESSING} and ${F.leaseExpiresAt} is not null and ${F.leaseExpiresAt} <= ${f} then 1 else 0 end), 0)`}).from(F),this.db.select({total:x`count(*)`,active:x`coalesce(sum(case when ${J.heartbeatAt} > ${A} then 1 else 0 end), 0)`,stale:x`coalesce(sum(case when ${J.heartbeatAt} <= ${A} then 1 else 0 end), 0)`,latestHeartbeatAt:x`max(${J.heartbeatAt})`}).from(J)]),H={pending:0,processing:0,completed:0,failed:0},L=$.map((C)=>{let K=Number(C.count);return H[C.status]+=K,{type:C.type,status:C.status,count:K}}),X=Z[0],Y=V[0],M=(C)=>C===null||C===void 0?null:Math.max(0,f-Number(C));return{totals:H,byType:L,oldestPendingAgeMs:M(X?.oldestPendingAt),oldestProcessingAgeMs:M(X?.oldestProcessingAt),staleLeaseCount:Number(X?.staleLeaseCount??0),workerSessions:{total:Number(Y?.total??0),active:Number(Y?.active??0),stale:Number(Y?.stale??0),latestHeartbeatAgeMs:M(Y?.latestHeartbeatAt)}}}async getRuntimeUpdates(f,A){return(await this.db.select().from(F).where(x`(${F.runtimeUpdatedAt}, ${F.id}) > (${f.updatedAt}, ${f.jobId})`).orderBy($f(F.runtimeUpdatedAt),$f(F.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(F).where(E(Ff(_(F.status,P.COMPLETED),_(F.status,P.FAILED)),Jf(F.completedAt,A)))).rowsAffected}async getActiveJobs(f){let A=Ff(_(F.status,P.PENDING),_(F.status,P.PROCESSING)),$=f&&f.length>0?E(A,xf(F.type,f)):A;return this.db.select().from(F).where($).orderBy(i(F.createdAt))}async getFailedJobs(f){let A=_(F.status,P.FAILED),$=f&&f.length>0?E(A,xf(F.type,f)):A;return this.db.select().from(F).where($).orderBy(i(F.createdAt))}async claimNextReady(f){let{now:A,attemptId:$,workerSlotId:Z,workerSessionId:V,leaseDurationMs:H,workerSessionTimeoutMs:L,executableTypes:X}=f,Y=A-L,M=this.db.select({slotId:J.slotId}).from(J).where(E(_(J.slotId,Z),_(J.sessionId,V))),C=this.db.select({slotId:J.slotId}).from(J).where(E(_(J.slotId,F.workerSlotId),_(J.sessionId,F.workerSessionId))),K=this.db.select({slotId:J.slotId}).from(J).where(E(_(J.slotId,F.workerSlotId),_(J.sessionId,F.workerSessionId),Jf(J.heartbeatAt,Y))),R=E(_(F.status,P.PROCESSING),Ff(X$(F.attemptId),zZ(C),E(Jf(F.leaseExpiresAt,A),Y$(K)))),B=x`${F.status} = ${P.PROCESSING} AND ${F.retryCount} + 1 > ${F.maxRetries}`,q=this.db.select({id:F.id}).from(F).where(E(xf(F.type,X),Ff(E(_(F.status,P.PENDING),Jf(F.scheduledFor,A)),R))).orderBy($f(F.priority),$f(F.createdAt)).limit(1),I=(await this.db.update(F).set({status:x`CASE WHEN ${B} THEN ${P.FAILED} ELSE ${P.PROCESSING} END`,retryCount:x`CASE WHEN ${F.status} = ${P.PROCESSING} THEN ${F.retryCount} + 1 ELSE ${F.retryCount} END`,lastError:x`CASE WHEN ${F.status} = ${P.PROCESSING} THEN 'Attempt lease expired' ELSE ${F.lastError} END`,startedAt:x`CASE WHEN ${B} THEN ${F.startedAt} ELSE ${A} END`,completedAt:x`CASE WHEN ${B} THEN ${A} ELSE NULL END`,attemptId:x`CASE WHEN ${B} THEN ${F.attemptId} ELSE ${$} END`,workerSlotId:x`CASE WHEN ${B} THEN ${F.workerSlotId} ELSE ${Z} END`,workerSessionId:x`CASE WHEN ${B} THEN ${F.workerSessionId} ELSE ${V} END`,leaseExpiresAt:x`CASE WHEN ${B} THEN ${F.leaseExpiresAt} ELSE ${A+H} END`,attemptHeartbeatAt:x`CASE WHEN ${B} THEN ${F.attemptHeartbeatAt} ELSE ${A} END`,runtimeUpdatedAt:x`CASE WHEN ${B} THEN ${this.nextRuntimeUpdatedAt(A)} ELSE ${F.runtimeUpdatedAt} END`}).where(E(xf(F.id,q),Y$(M))).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 x`max(${f}, coalesce((select max(${F.runtimeUpdatedAt}) from ${F}), 0) + 1)`}attemptWriteGuard(f,A){return A?E(_(F.id,f),_(F.status,P.PROCESSING),_(F.attemptId,A)):E(_(F.id,f),X$(F.attemptId),Ff(_(F.status,P.PENDING),_(F.status,P.PROCESSING)))}}import{AsyncLocalStorage as T1}from"async_hooks";class Kf{storage=new T1;static createFresh(){return new Kf}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=q1(Z);return this.storage.run(Object.freeze({provenance:V,operationId:A}),$)}}function q1(f){if(Object.freeze(f.projectionLineage),f.sourceEntity)Object.freeze(f.sourceEntity);return Object.freeze(f)}class F${client;logger;handlerRegistry;repository;walInitialization=null;walInitializationSettled=!1;closeRequested=!1;clientClosed=!1;inFlightEnqueues=0;databaseUrl;operationContext;projectionAdmission;directWorkerSlotId=`direct:${g()}`;directWorkerSessionId=g();directLeaseDurationMs;directSessionStart=null;close(){this.closeRequested=!0,this.closeClientWhenReady()}static createFresh(f,A,$){return new F$(f,A??ef.getInstance(),$)}constructor(f,A,$){let{db:Z,client:V,url:H}=EZ(f);this.client=V,this.databaseUrl=H,this.logger=A.child("JobQueueService"),this.operationContext=$?.operationContext??Kf.createFresh(),this.projectionAdmission=$?.projectionAdmission,this.handlerRegistry=new H$(this.logger,$?.handlerRegistrationMode??"combined"),this.repository=new M$(Z,V,H,this.logger),this.directLeaseDurationMs=f.claimTimeoutMs??300000}initialize(){if(this.closeRequested)return Promise.resolve();return this.walInitialization??=this.initializeWALMode(),this.walInitialization}async initializeWALMode(){try{await df(this.client,this.databaseUrl)}catch(f){this.logger.warn("Failed to enable WAL mode (non-fatal)",f)}finally{this.walInitializationSettled=!0,this.closeClientWhenReady()}}closeClientWhenReady(){if(!this.closeRequested||this.inFlightEnqueues>0||this.walInitialization!==null&&!this.walInitializationSettled)return;this.closeClient()}closeClient(){if(this.clientClosed)return;this.clientClosed=!0,this.client.close()}registerHandler(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 enqueue(f){if(this.closeRequested)throw Error("Cannot enqueue a job after the queue service is closed");this.inFlightEnqueues++;try{return await this.enqueueValidated(f)}finally{this.inFlightEnqueues--,this.closeClientWhenReady()}}async enqueueValidated(f){let{type:A,data:$,options:Z}=f,V=this.handlerRegistry.getValidator(A);if(!V)throw Error(`No job type declared: ${A}`);let H=V.validateAndParse($);if(H===null)throw Error(`Invalid job data for type: ${A}`);let L=Date.now(),X=g(),Y=Z?.rootJobId??this.operationContext.current()?.provenance.rootJobId??X,M=this.createJobProvenance(X,Y,Z),C=Z?.metadata??{operationType:"data_processing"},{provenance:K,...R}=C,B={id:X,type:A,data:JSON.stringify(H),status:P.PENDING,priority:Z?.priority??0,maxRetries:Z?.maxRetries??3,retryCount:0,source:Z?.source??null,metadata:{...R,...Z?.deduplicationKey&&{deduplicationKey:Z.deduplicationKey},rootJobId:Y,provenance:M},createdAt:L,scheduledFor:Z?.delayMs?L+Z.delayMs:L,result:null,lastError:null,startedAt:null,completedAt:null},q;try{let k=await this.repository.enqueueAtomic({jobData:B,strategy:Z?.deduplication,deduplicationKey:Z?.deduplicationKey,beforeInsert:async()=>{q=await this.projectionAdmission?.reserveJobAdmission(M)}});if(q?.commit(),k.kind==="skipped")this.logger.debug("Skipping duplicate job (already pending)",{type:A,existingJobId:k.jobId});else if(k.kind==="coalesced")this.logger.debug("Coalescing with existing job",{type:A,existingJobId:k.jobId});else{if(k.kind==="replaced")this.logger.debug("Replacing duplicate job",{type:A,oldJobId:k.replacedJobId});this.logger.debug("Job enqueued",{id:k.jobId,type:A,priority:B.priority,rootJobId:B.metadata.rootJobId})}return k.jobId}catch(k){throw q?.rollback(),this.logger.error("Failed to enqueue job",{type:A,error:S(k)}),k}}createJobProvenance(f,A,$){let Z=this.operationContext.current(),V=$?.metadata.provenance??Z?.provenance,H=V?.rootJobId===A?V:void 0,L=Z?.provenance.rootJobId===A?Z.operationId:void 0,X=$?.projection,Y=X?[...H?.projectionLineage??[],X.id]:[...H?.projectionLineage??[]],M=X?.id??H?.projectionId;return Uf.parse({rootJobId:A,causationId:L??H?.causationId??f,...M?{projectionId:M}:{},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 yZ extends Error{constructor(f,A){super(`Job ${f} exceeded its ${A}ms execution deadline`);this.name="JobDeadlineExceededError"}}class K${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 K$(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??Kf.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??Of,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($A.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(ZA.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}),L={kind:f,awaitInFlightPoll:A,promise:H,resolve:Z,reject:V};return this.transitionQueue.push(L),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((L)=>{if(L)return;let X=Error("Job attempt was superseded");A.abort(X),this.markUnhealthy(X.message)}).catch((L)=>{let X=Cf(L);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((R)=>({kind:"success",value:R}),(R)=>({kind:"failure",error:R})),H,L=new Promise((R)=>{H=setTimeout(()=>R({kind:"deadline"}),Math.max(1,A))}),X=await Promise.race([V,L]);if(X.kind!=="deadline"){if(H)clearTimeout(H);if(X.kind==="failure")throw X.error;return X.value}let Y=new yZ(f,A);$.abort(Y);let M,C=new Promise((R)=>{M=setTimeout(()=>R({kind:"grace-expired"}),Math.max(1,this.config.cancellationGraceMs))});if((await Promise.race([V,C])).kind!=="grace-expired"){if(M)clearTimeout(M);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,L=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 M=this.progressMonitor.createProgressReporter(f.id,A),C=$.executionTimeoutMs??this.config.defaultExecutionTimeoutMs,K=await this.executeWithDeadline(f.type,C,Z,()=>$.process(Y,f.id,M,Z.signal));await L();let R=V$.safeParse(K);if(R.success){let q=R.data.error??"Handler returned failure",k=Error(q);if(await this.jobQueueService.fail(f.id,k,A))await this.emitTerminalFailure(f,k,$,A);return{jobId:f.id,type:f.type,status:P.FAILED,error:q}}if(!await this.jobQueueService.complete(f.id,K,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:K}}catch(X){let Y=Cf(X);await L();try{let C=JSON.parse(f.data),K=$.validateAndParse(C);if(K!==null&&$.onError){let R=this.progressMonitor.createProgressReporter(f.id,A),B=new AbortController;await this.executeWithDeadline(`${f.type}:onError`,this.config.errorCallbackTimeoutMs,B,()=>$.onError?.(Y,K,f.id,R,B.signal)??Promise.resolve())}}catch(C){this.logger.error("Job handler error callback failed",{jobId:f.id,error:C})}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 L=this.progressMonitor.createProgressReporter(f.id,Z),X=new AbortController;await this.executeWithDeadline(`${f.type}:onTerminalError`,this.config.errorCallbackTimeoutMs,X,()=>$.onTerminalError?.(A,H,f.id,L,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,hZ=3600000;class C${jobQueue;logger;batches=new Map;cleanupFiber=null;cleanupSupervisor=null;inFlightCleanups=new Set;activeTransition=null;transitionQueue=[];acceptingCleanup=!0;clock;static createFresh(f,A,$){return new C$(f,A,$)}constructor(f,A,$){this.jobQueue=f,this.logger=A,this.clock=$?.clock}start(f=hZ){return this.requestTransition("start",f)}stop(){return this.requestTransition("stop",hZ)}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(ZA.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());UA.unsafeAdd(this.cleanupSupervisor.fibers,f)}async stopCleanup(){this.acceptingCleanup=!1;let f=this.cleanupFiber;if(this.cleanupFiber=null,f)await G.runPromise($A.interrupt(f));let A=this.cleanupSupervisor;if(A)await G.runPromise(UA.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}),L={kind:f,intervalMs:A,promise:H,resolve:Z,reject:V};return this.transitionQueue.push(L),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(UA.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 L={...A,rootJobId:$,metadata:{...A.metadata,operationTarget:H.type}},X=await this.jobQueue.enqueue({type:H.type,data:H.data,options:L});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((M)=>this.jobQueue.getStatus(M))),Z=0,V=0,H=0,L=[];for(let[M,C]of $.entries()){if(!C){V++;let K=A.operations[M],R=A.jobIds[M]??"unknown";L.push(`Missing job ${R}${K?` for ${K.type}`:""}`);continue}switch(C.status){case"completed":Z++;break;case"failed":if(V++,C.lastError)L.push(C.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 M=0;M<A.jobIds.length;M++){let C=$[M];if(C&&C.status!=="completed"&&C.status!=="failed"){let K=A.operations[M];if(K)Y=`Processing ${K.type}`;break}}return{batchId:f,totalOperations:A.operations.length,completedOperations:Z,failedOperations:V,errors:L,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 L=await this.getBatchStatus(Z);if(L&&(L.status===P.COMPLETED||L.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 G${jobQueueService;messageBus;batchJobManager;logger;mode;pollTimer;pollCursor={updatedAt:0,jobId:""};polling=!1;static createFresh(f,A,$,Z,V="combined"){return new G$(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:Qf.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:Qf.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,L=await this.batchJobManager.getBatchStatus(H);if(L){let X=L.metadata??V;await this.emitBatchProgress(H,L,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 E1=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=E1.safeParse(f);return A.success?A.data:{}}}function P$(f,A,$){return async(Z)=>{let{type:V,data:H,toolContext:L=null,options:X,projection:Y}=Z,M=L?vZ(L):void 0,{metadata:C,...K}=X??{},R={operationType:"data_processing",pluginId:A,...C,...L&&{interfaceType:L.interfaceType,conversationId:L.conversationId,channelId:L.channelId,requestedByActor:L.actor,...M?{requestedByUserId:M}:{},requestedByInterface:L.interfaceType}};if(L&&!M)delete R.requestedByUserId;let B={...K,source:A,...X?.rootJobId&&{rootJobId:X.rootJobId},...Y&&{projection:Y},metadata:R},q=$&&!V.includes(":")?`${A}:${V}`:V;return f.enqueue({type:q,data:H,options:B})}}function N$(f,A){return async($,Z)=>{let V=g(),H=$.map((X)=>({...X,type:X.type.includes(":")?X.type:`${A}:${X.type}`})),L={...Z,source:A,rootJobId:V,metadata:{...Z?.metadata,operationType:"batch_processing",pluginId:A}};return await f.enqueueBatch(H,L,V,A),V}}function W$(f,A){return($,Z)=>{let V=$.includes(":")?$:`${A}:${$}`;f.registerHandler(V,Z,A)}}var z1=U.custom((f)=>typeof f==="object"&&f!==null&&("safeParse"in f)),y1=U.object({name:U.string(),schema:z1});function jZ(f){return y1.safeParse(f).success}function h1(f){if(!f)return;return{status:f.status,message:f.message,lastCheck:f.lastCheck?.toISOString(),details:f.details}}function bZ(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:h1(A.health)})),endpoints:f.endpoints,interactions:f.interactions}}function v1(f){let A=Mf.safeParse(f);return A.success?A.data:"user"}function VA(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 gZ(f){return{id:f.id,conversationId:f.conversationId,role:v1(f.role),content:f.content,timestamp:f.timestamp,metadata:ff(f.metadata)}}function uZ(f){return sA.parse(f)}function IZ(f){return aA.parse(f)}function cZ(f){return async()=>{return bZ(await f.getAppInfo())}}function pZ(f,A){return{get:()=>uZ(f.getIdentity()),getProfile:()=>IZ(f.getProfile()),getAppInfo:A}}function lZ(f,A){let $=f.getProfileKindRegistry();return{register:(Z)=>{$.register(A,Z)},getResolved:()=>$.getResolved(),getSelectedDefinition:()=>$.getSelectedDefinition()}}function R$(f){let A=f.getChannelRegistry();return{listDescriptors:()=>A.listDescriptors(),getDescriptor:($)=>A.getDescriptor($),getDeliveryProvider:($)=>A.getDeliveryProvider($)}}function nZ(f,A){let $=f.getInboxRegistry();return{registerSource:(Z)=>{$.registerSource(A,Z)},listSources:()=>$.listSources(),getSource:(Z)=>$.getSource(Z)}}function dZ(f,A){let $=f.getChannelRegistry();return{...R$(f),registerDescriptor:(Z)=>{$.registerDescriptor(A,Z)},registerDeliveryProvider:(Z)=>{$.registerDeliveryProvider(A,Z)}}}function iZ(f,A,$,Z=!1){let V=f.getMessageBus();return{send:async(L)=>{return V.send({...L,sender:A})},subscribe:(L,X)=>{if(Z)return()=>{};if(jZ(L)){let Y=L,M=X,C=async(K)=>{let R=Y.schema.safeParse(K.payload);if(!R.success)return $.warn(`Invalid payload for channel ${Y.name}`,{error:R.error.message}),{noop:!0};let{payload:B,...q}=K;return M(R.data,q)};return V.subscribe(Y.name,C)}return V.subscribe(L,X)},subscribeExecution:(L,X)=>V.subscribe(L,X)}}function sZ(f,A){let $=f.getJobQueueService();return{...f.jobs,enqueue:P$($,A,!0),enqueueBatch:N$(f.jobs,A),registerHandler:W$($,A)}}function aZ(f){let A=f.getPermissionService();return{assertEntityActionAllowed:($,Z,V)=>{A.assertEntityActionAllowed($,Z,V.userPermissionLevel)}}}function oZ(f){return{get:async(A)=>{let Z=await f.getConversationService().getConversation(A);return Z?VA(Z):null},search:async(A)=>{return(await f.getConversationService().searchConversations(A)).map(VA)},list:async(A)=>{return(await f.getConversationService().listConversations(A)).map(VA)},getMessages:async(A,$)=>{return(await f.getConversationService().getMessages(A,$)).map(gZ)},countMessages:async(A)=>{return f.getConversationService().countMessages(A)}}}function rZ(f,A){return{registerHandler:($,Z)=>{f.registerEvalHandler(A,$,Z)}}}function tZ(f){return{register:(A,$)=>{f.getInsightsRegistry().register(A,$)}}}function eZ(f){return{has:(A)=>f.getPluginPackageName(A)!==void 0}}function fU(f,A){return{register:($)=>{f.registerEndpoint({...$,pluginId:A})}}}function AU(f,A){return{register:($)=>{f.registerInteraction({...$,pluginId:A})}}}function $U(f,A){return{registerWidget:async($)=>{await f.send({type:B$.registerWidget,payload:{...$,pluginId:A}})},unregisterWidget:async($)=>{await f.send({type:B$.unregisterWidget,payload:{pluginId:A,...$?{widgetId:$}:{}}})}}}function Lf(f,A,$){let Z=f.getEntityService(),V=f.getLogger().child(A),H=f.getDomain(),L=f.getLocalSiteUrl(),X=f.shouldPreferLocalUrls(),Y=f.getThemeCSS(),M=cZ(f),C=f.getAttachmentRegistry(),K=f.getRuntimeUploadRegistry(),R=f.getRuntimeState(),B=$?.executionOnly===!0,q=iZ(f,A,V,B);return{pluginId:A,executionOnly:B,logger:V,entityService:Z,semantic:{project:(k)=>Z.projectSemanticSpace(k)},identity:pZ(f,M),profileKinds:lZ(f,A),channels:R$(f),inbox:nZ(f,A),appInfo:M,readiness:()=>f.getRuntimeReadiness(),judge:(k)=>f.judge(k),domain:H,siteUrl:H?`https://${H}`:void 0,localSiteUrl:L,previewUrl:H?`https://${ZU(H)}`:void 0,preferLocalUrls:X,themeCSS:Y,entityDisplay:$?.entityDisplay,spaces:f.getSpaces(),permissions:aZ(f),messaging:q,dashboard:$U(q,A),jobs:sZ(f,A),attachments:C,uploads:K,runtimeState:R,recurringChecks:f.getRecurringChecks(A),conversations:oZ(f),dataDir:f.getDataDir(),eval:B?{registerHandler:()=>{}}:rZ(f,A),insights:B?{register:()=>{}}:tZ(f),plugins:eZ(f),endpoints:B?{register:()=>{}}:fU(f,A),interactions:B?{register:()=>{}}:AU(f,A)}}function j1(f){return f.replace(/:/g,"-")}function b1(f){return f.split(/[:.-]/).map((A)=>A.charAt(0).toUpperCase()+A.slice(1)).join(" ")}var _$=new Map;async function HA(f,A,$){let Z=_$.get(A);if(Z!==void 0)return Z;let V=j1(A),H;try{H=await f.getEntity({entityType:"prompt",id:V})}catch{return $}if(H?.content){let L=Tf(H.content,U.record(U.string(),U.unknown())).content;return _$.set(A,L),L}try{let L=b1(A),X=D$($,{title:L,target:A});await f.createEntity({entity:{id:V,entityType:"prompt",content:X,metadata:{title:L,target:A,slug:V}}})}catch{}return _$.set(A,$),$}async function g1(f,A){let $=f.list().filter((Z)=>!!Z.basePrompt);return await Promise.all($.map((Z)=>HA(A,Z.name,Z.basePrompt))),$.length}function LA(f){let A=f.getEntityService(),$=f.getEntityRegistry(),Z=f.getDataSourceRegistry();return{register:(V,H,L,X)=>{$.registerEntityType(V,H,L,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 XA(f){return{resolve:(A,$)=>{return HA(f,A,$)}}}function YA(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 O$(f,A,$){let Z=Lf(f,A,$),V=f.getEntityService();return{...Z,entityService:V,entities:LA(f),ai:YA(f),prompts:XA(V),permissions:Z.permissions}}function k$(f,A,$){let Z=Lf(f,A,$),V=f.getEntityService(),H=f.getRenderService(),L=f.getContentService(),X=f.getPermissionService();return{...Z,permissions:{...Z.permissions,getConfiguredPrincipalSeeds:()=>X.getConfiguredPrincipalSeeds(),replaceRuntimePrincipalState:(Y)=>X.replaceRuntimePrincipalState(Y)},entityService:V,entities:LA(f),webRoutes:{getRoutes:()=>f.getPluginWebRoutes()},templates:{register:(Y,M)=>{f.registerTemplates(Y,M??A)},format:(Y,M)=>{return L.formatContent(Y,M,{pluginId:A})},parse:(Y,M)=>{return L.parseContent(Y,M,A)},resolve:async(Y,M)=>{return await L.resolveContent(Y,M,A)},getCapabilities:(Y)=>{let M=Y.includes(":")?Y:`${A}:${Y}`,C=f.getTemplate(M);if(!C)return null;let K=UU.getCapabilities(C);return{canGenerate:K.canGenerate,canFetch:K.canFetch,canRender:K.canRender,isStaticOnly:K.isStaticOnly}}},views:{get:(Y)=>{return H.get(Y)??void 0},list:()=>{return H.list()},hasRenderer:(Y,M="web")=>{return H.hasRenderer(Y,M)},getRenderer:(Y,M="web")=>{return H.getRenderer(Y,M)},validate:(Y,M)=>{return H.validate(Y,M)}},prompts:XA(V),ai:YA(f),registerInstructions:(Y)=>{f.registerInstructions(A,Y)}}}class VU extends Zf{type="service";getApiRoutes(){return[]}getWebRoutes(){return[]}async register(f,A){let $=k$(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 u1=U.object({});class J$ 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 $=O$(f,this.id,A);this.context=$,this.setupMessageHandlers($);let Z=this.getProjectionRules($),V=this.getEntityTypeConfig(),H=Z.some((R)=>R.targetType===this.entityType),L=V?.projectionSource!==!1&&V?.projectionSourceRole!=="excluded"&&(V?.projectionSource===!0||V?.projectionSourceRole!==void 0),X=H&&!L?{...V,projectionSource:!1,projectionSourceRole:"excluded"}:V;if($.entities.register(this.entityType,this.schema,this.adapter,X),this.interceptCreate!==J$.prototype.interceptCreate)$.entities.registerCreateInterceptor(this.entityType,(R,B)=>this.interceptCreate(R,B,$));let Y=this.createGenerationHandler($);if(Y)$.jobs.registerHandler(`${this.entityType}:generation`,Y);let M=this.getTemplates();if(M&&Object.keys(M).length>0)f.registerTemplates(M,this.id);let C=this.getDataSources();for(let R of C)$.entities.registerDataSource(R);await this.onRegister(this.context);let K=await this.getInstructions();return{tools:[],resources:[],...K&&{instructions:K},...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 I1({context:f,targetType:A,desired:$,getId:Z,toEntityInput:V,equals:H,deleteStale:L=!1,outputVisibility:X="public",concurrency:Y=1,logger:M}){let C=new Map;for(let z of $)C.set(Z(z),z);let K=(await f.entityService.listEntities({entityType:A,options:{filter:{visibilityScope:X}}})).filter((z)=>z.visibility===X),R=new Map(K.map((z)=>[z.id,z])),B=0,q=0,k=0,I=0,o=Math.max(1,Y);if(L){let z=K.filter((c)=>!C.has(c.id));await HU(z,o,async(c)=>{await f.entityService.deleteEntity({entityType:A,id:c.id}),k++})}return await HU(Array.from(C),o,async([z,c])=>{let N=R.get(z),D={...V(c,z),visibility:X};try{if(!N){await f.entityService.createEntity({entity:D}),B++;return}if(H?.(N,c)??!1){I++;return}await f.entityService.updateEntity({entity:{...N,...D,id:z,entityType:A,visibility:X}}),q++}catch(W){M?.error("Failed to reconcile entity",{targetType:A,id:z,error:S(W)})}}),{created:B,updated:q,deleted:k,skipped:I}}async function HU(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 c1({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 p1({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()},L=await f.updateEntity({entity:H,...$!==void 0?{options:{expectedContentHash:$}}:{}});return{entityId:L.entityId,updated:!0,mutation:L,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 l1({entityService:f,entityType:A,id:$,error:Z,content:V}){let H=await f.getEntity({entityType:A,id:$});if(!H)return{found:!1};let L={...H,content:V??H.content,metadata:{...H.metadata,status:"failed",processingError:Z},updated:new Date().toISOString()},X=await f.updateEntity({entity:L});return{found:!0,entityId:X.entityId,mutation:X,previousEntity:H}}function LU(f){return YU(f)}function XU(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 MU(f){return{chat:async(A,$,Z,V)=>{let H=XU(Z),L=V?await f.chat(A,$,H,V):await f.chat(A,$,H);return LU(L)},confirmPendingAction:async(A,$,Z,V,H)=>{let L=XU(V);if(!L)throw Error("Confirmation requires caller context.");let X=H?await f.confirmPendingAction(A,$,Z,L,H):await f.confirmPendingAction(A,$,Z,L);return LU(X)},invalidate:()=>{f.invalidateAgent()}}}var FA=new WeakMap;function n1(f,A){if(FA.has(f))throw Error("HTTP route snapshot provider is already bound");FA.set(f,A)}function FU(f,A){let $=FA.get(f);if(!$)throw Error("HTTP route snapshot provider is not bound");n1(A,$)}function KU(f){let A=FA.get(f);if(!A)throw Error("HTTP route snapshot provider is not bound");return A()}function KA(f,A,$){let Z=Lf(f,A,$),V=f.getMCPService(),H=f.getPermissionService(),L=MU(f.getAgentService());return{...Z,mcpTransport:V,agent:L,permissions:{...Z.permissions,getUserLevel:(X,Y,M)=>{return H.determineUserLevel(X,Y,M)},isAnchor:(X,Y)=>H.isAnchor(X,Y)},daemons:{register:(X,Y)=>{let M=`${A}:${X}`;f.registerDaemon(M,Y,A),Z.logger.debug(`Registered daemon: ${M}`)}},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:()=>KU(f)},plugins:{has:(X)=>f.hasPlugin(X)}}}function x$(f,A,$){return{...KA(f,A,$),channels:dZ(f,A)}}var d1=3600000;class CA extends Zf{type="interface";daemon;jobTrackingEntries=new Map;jobTrackingTtlMs=d1;createContext(f,A){return KA(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 PU=/^[a-z][a-z0-9-]*$/,i1=U.strictObject({source:U.string().min(1).max(500),flags:U.string().regex(/^[imu]*$/).optional()}),s1=U.strictObject({type:U.string().trim().regex(PU),displayName:U.string().trim().min(1).max(100),subjectLabel:U.string().trim().min(1).max(100),subjectPattern:i1.optional(),manualDelivery:U.boolean().optional()});class NU{descriptorRegistrations=new Map;providerRegistrations=new Map;activeDescriptors=new Map;activeProviders=new Map;finalized=!1;registerDescriptor(f,A){this.assertRegistrationOpen();let $=CU(f),Z=s1.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 $=CU(f),Z=Q$(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(Q$(f))}getDeliveryProvider(f){return this.assertFinalized(),this.activeProviders.get(Q$(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 GU("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 GU("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,L=V[0]?.pluginId;if(H!==L){if(f)throw Error(`Delivery provider for channel "${Z}" must be registered by descriptor owner "${H??"unknown"}", not "${L??"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 CU(f){let A=f.trim();if(!A)throw Error("Channel registration plugin id is required");return A}function Q$(f){let A=f.trim();if(!PU.test(A))throw Error(`Invalid channel type: ${f}`);return A}function GU(f,A,$){let Z=$.map((V)=>V.pluginId).sort().join(", ");return Error(`${f} "${A}" is registered by multiple plugins: ${Z}`)}var GA=/^[a-z][a-z0-9-]*$/,WU=U.strictObject({id:U.string().trim().regex(GA),label:U.string().trim().min(1).max(100),confirm:U.boolean().optional()}),RU=U.strictObject({entityType:U.string().trim().min(1).max(100),entityId:U.string().trim().min(1).max(300)}),BU=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:RU.optional(),actions:U.array(WU).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)}}),_U=U.array(BU).max(1000),DU=U.strictObject({permissionLevel:U.enum(["admin","trusted","public"])}),OU=U.strictObject({sourceId:U.string().trim().regex(GA),displayName:U.string().trim().min(1).max(100)});class kU{registrations=new Map;activeSources=new Map;finalized=!1;registerSource(f,A){this.assertRegistrationOpen();let $=r1(f),Z=OU.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=a1(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(t1(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((L)=>L.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 a1(f,A){return Object.freeze({...f,list:async()=>{return _U.parse(await A.list()).map(o1)},act:async($,Z,V)=>{let H=U.string().trim().min(1).max(300).parse($),L=U.string().trim().regex(GA).parse(Z);await A.act(H,L,DU.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 r1(f){let A=f.trim();if(!A)throw Error("Inbox registration plugin id is required");return A}function t1(f){return U.string().trim().regex(GA).parse(f)}var e1={pluginsRegistered:"system:plugins:registered",initialSyncCompleted:"sync:initial:completed",shellReady:"system:shell:ready"};function f8(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 w${providers=new Map;static createFresh(){return new w$}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 A8,readdir as $8,readFile as JU,rm as xU,stat as Z8,writeFile as QU}from"fs/promises";import{basename as U8,dirname as V8,join as n}from"path";var PA=/^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,wU=86400000,TU=200;class Xf extends Error{code;constructor(f,A){super(A);this.code=f,this.name="RuntimeUploadStoreError"}}var H8=U.object({id:U.string().regex(PA),ref:U.object({kind:U.string().min(1),id:U.string().regex(PA)}),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 L8(f){return{scoped:(A)=>f.scoped(A)}}function qU(f){return U8(f)==="brain-data"?n(V8(f),"data"):f}class T${dataDir;constructor(f){this.dataDir=qU(f.dataDir)}static createFresh(f){return new T$(f)}scoped(f){return new q$({...f,dataDir:this.dataDir})}}class q${options;retentionMs;maxCount;createUploadId;getNow;constructor(f){this.options=f,this.retentionMs=f.retentionMs??wU,this.maxCount=f.maxCount??TU,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 A8(Z,{recursive:!0}),await QU(n(Z,"content"),f.content),await QU(n(Z,"metadata.json"),`${JSON.stringify($,null,2)}
|
|
3
|
-
`,"utf8"),await this.prune(),$}async remove(f){this.assertValidUploadId(f),await xU(this.getUploadDir(f),{recursive:!0,force:!0})}async read(f){let A=await this.readRecord(f);try{let $=await JU(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 JU(n(this.getUploadDir(f),"metadata.json"),"utf8"),$=H8.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 $8(f),Z=(await Promise.all(A.map(async(L)=>{try{let X=await Z8(n(f,L));return X.isDirectory()?{entry:L,mtimeMs:X.mtimeMs}:null}catch{return null}}))).filter((L)=>L!==null).sort((L,X)=>X.mtimeMs-L.mtimeMs),V=this.getNow().getTime()-this.retentionMs,H=Z.filter((L,X)=>X>=this.maxCount||L.mtimeMs<V);await Promise.all(H.map((L)=>xU(n(f,L.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(!PA.test(f))throw new Xf("invalid_ref","Invalid upload ref")}}var B2=U.object({id:U.string(),type:U.string(),version:U.string(),status:U.string()}),_2=U.object({name:U.string(),description:U.string()});var M8=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()});function m$(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 mU(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 SU(f){let A={...f};return delete A.status,delete A.error,RA(A)}class hU 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 $=mU(f);if(typeof A!=="object")return A;let Z=m$(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=m$(f),H=V?this.applyPreallocatedEntityId(V,Z):Z;await this.reportProgress($,{progress:NA.SAVE,message:`Saving ${this.entityType} to database`});let L=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,L.entityId,$,H),await this.enqueueGenericCoverImageIfRequested(f,L.entityId,$,H),await this.reportProgress($,{progress:NA.COMPLETE,message:`${H.title??this.entityType} created successfully`}),{success:!0,entityId:L.entityId,...H.resultExtras}}catch(Z){if(Z instanceof E$)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),EU.failure(Z)}}applyPreallocatedEntityId(f,A){let $={...A.metadata},Z=A.content,V=A.resultExtras;if(typeof $.slug==="string")$.slug=f,Z=WA(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 $=SU(S$(f.content).frontmatter),Z=SU(f.metadata),V=RA(A.metadata),H=S$(A.content),L=RA(H.frontmatter),X=RA({...$,...V,...L});return this.context.entities.getEffectiveFrontmatterSchema(this.entityType)?.parse(X),{content:yU(X,H.content),metadata:{...Z,...V}}}async markPreallocatedStubFailed(f,A){let $=m$(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:WA(WA(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=mU(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:zU.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 E$(f)}}class E$ extends Error{constructor(f){super(f);this.name="GenerationFailure"}}function z$(f,A){f.messaging.subscribe(Qf.progress,async($)=>{try{let Z=fA.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 y$(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
|
-
${f.message}`;return H}function h$(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
|
-
${f.message}`;return Z}var F8=U.enum(["tool:invoking","tool:completed","tool:failed"]),K8=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()}),C8=["tool:invoking","tool:completed","tool:failed"];function v$(f,A){for(let $ of C8)f.messaging.subscribe($,async(Z)=>{try{let V=F8.safeParse(Z.type),H=K8.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 j${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 qf(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 b$(f){return`${f.conversationId}:${f.toolName}`}function g$(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 vU(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 jU(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 bU(f){let A=b$(f),$=g$(f.toolName),Z=vU(f.state),V=jU(f.state),H=`${V}: ${$}`;return{key:A,label:$,title:Z,fallbackPrefix:V,fallback:f.error?`${H}: ${f.error}`:H}}function gU(f,A){return f.pendingConfirmations?.some(($)=>$.toolName===A)===!0||G8(f.cards).some(($)=>$.toolName===A)}function G8(f){return f?.filter((A)=>A.kind==="tool-approval"&&A.state==="approval-requested")??[]}var uU=500,P8=500;class u${transport;cleanupSupervisor=new j$(P8);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(qf(f,"running"));return;case"tool:completed":if(this.isProcessingInput){this.pendingToolCompletions.set(this.getToolCompletionKey(f),f);return}await this.transport.handleToolStatusUpdate(qf(f,"completed"));return;case"tool:failed":this.pendingToolCompletions.delete(this.getToolCompletionKey(f)),await this.transport.handleToolStatusUpdate(qf(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=gU(f,V.toolName)?"awaiting-approval":"completed";await this.transport.handleToolStatusUpdate(qf(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($),L=Date.now();if(H){if(L-H.lastUpdate>=uU)await this.transport.editMessage({channelId:H.channelId,messageId:H.messageId,newMessage:V}),H.lastUpdate=L}else if(A&&!this.isProcessingInput)await this.sendInitialProgressMessage($,A,V,L);return!1}async editTrackedProgressMessage(f,A){let $=Date.now();if($-A.lastUpdate<uU)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 I$=1e5,N8=[".md",".txt",".markdown"],W8=["text/plain","text/markdown","text/x-markdown"],R8=/https?:\/\/[^\s<>"{}|\\^`[\]]+?(?=[,;:\s]|$)/gi,B8=["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"],c$=U.object({captureUrls:U.boolean().default(!1),blockedUrlDomains:U.array(U.string()).default(B8)});function IU(f,A){if(A&&W8.some(($)=>A.startsWith($)))return!0;return N8.some(($)=>f.toLowerCase().endsWith($))}function cU(f){return f<=I$}function pU(f){if(f.includes(0))return!1;try{return new TextDecoder("utf-8",{fatal:!0}).decode(f),!0}catch{return!1}}function lU(f,A){return`User uploaded a file "${f}":
|
|
6
|
-
|
|
7
|
-
${A}`}function nU(f,A){let $=f.match(R8)??[];return[...new Set($)].filter((Z)=>{try{let{hostname:V}=new URL(Z);return!A.some((H)=>V===H||V.endsWith(`.${H}`))}catch{return!1}})}function Gf(f,A){let $=f.attachment.source;if(($?.entityType==="document"||$?.entityType==="image")&&$.entityId)return{entityType:$.entityType,id:$.entityId};return p$(f.attachment.downloadUrl??f.attachment.url,A)}function p$(f,A="http://local"){if(!f)return;let $;try{$=new URL(f,A)}catch{return}let Z=$.searchParams.get("id")?.trim();if(!Z)return;if($.pathname==="/api/chat/attachments/document")return{entityType:"document",id:Z};if($.pathname==="/api/chat/attachments/image")return{entityType:"image",id:Z};return}function BA(f,A){let $=_8(A,f==="document"?/^application\/pdf$/i:/^image\/[a-z0-9.+-]+$/i);if(!$)return;if(f==="document"&&$.mimeType.toLowerCase()!=="application/pdf")return;return $}function _A(f,A,$,Z){let V=f?.filename;if(typeof V==="string"&&V.trim())return V;if($==="document")return`${A}.pdf`;let H=f?.format;if(typeof H==="string"&&H.trim())return`${A}.${H==="jpeg"?"jpg":H}`;let L=Z.split("/")[1]?.split("+")[0]??"png";return`${A}.${L}`}function _8(f,A){let $=f.match(/^data:([^;]+);base64,(.+)$/i),Z=$?.[1],V=$?.[2];if(!Z||!V||!A.test(Z))return;let H=Buffer.from(V,"base64");return{mimeType:Z,data:H.buffer.slice(H.byteOffset,H.byteOffset+H.byteLength)}}async function mf({entityRef:f,userLevel:A,getEntity:$,getVisibleEntity:Z}){let V=l$(A),H=await Z(f,V);if(H)return{status:"visible",entity:H};return Boolean(await $(f))?{status:"denied"}:{status:"missing"}}function DA(f){return f==="admin"||f==="trusted"}async function dU(f){let A=new Set;for(let $ of f.cards??[]){if($.kind!=="attachment")continue;let Z=Gf($,f.displayBaseUrl);if(!Z)continue;if((await mf({entityRef:Z,userLevel:f.userLevel,getEntity:f.getEntity,getVisibleEntity:f.getVisibleEntity})).status==="denied")A.add($.id)}return A}class n$ extends CA{createContext(f,A){return x$(f,this.id,A)}isUploadableTextFile(f,A){return IU(f,A)}isFileSizeAllowed(f){return cU(f)}formatFileUploadMessage(f,A){return lU(f,A)}getMaxFileUploadBytes(){return I$}isLikelyTextContent(f){return pU(f)}async resolveNativeArtifactDelivery(f){let A=[],$=new Set;if(!this.context||!f.cards)return{files:A,deniedCardIds:$};let Z=this.context;for(let V of f.cards){if(V.kind!=="attachment")continue;let H=Gf(V,f.displayBaseUrl);if(!H)continue;let L=await mf({entityRef:H,userLevel:f.userPermissionLevel,getEntity:(Y)=>Z.entityService.getEntity(Y),getVisibleEntity:(Y,M)=>Z.entityService.getEntity({...Y,visibilityScope:M})});if(L.status==="denied"){$.add(V.id);continue}if(L.status!=="visible")continue;if(!DA(f.userPermissionLevel))continue;if(typeof L.entity.content!=="string")continue;let X=BA(H.entityType,L.entity.content);if(!X)continue;if(f.maxBytes!==void 0&&X.data.byteLength>f.maxBytes){this.logger.debug("Skipping oversized native artifact upload",{cardId:V.id,sizeBytes:X.data.byteLength});continue}A.push({cardId:V.id,data:new Uint8Array(X.data),filename:V.attachment.filename??_A(L.entity.metadata,H.id,H.entityType,X.mimeType),mimeType:X.mimeType})}return{files:A,deniedCardIds:$}}extractCaptureableUrls(f,A){return nU(f,A)}async captureUrlViaAgent(f,A,$,Z,V){if(!this.context)return;let H=this.context.permissions.getUserLevel(Z,$,V);await this.context.agent.chat(`Save this link: ${f}`,`links-${A}`,{userPermissionLevel:H,interfaceType:Z,channelId:A})}progress=new u$({interfaceId:()=>this.id,logger:()=>this.logger,sendMessageToChannel:(f)=>this.sendMessageToChannel(f),sendMessageWithId:(f)=>this.sendMessageWithId(f),editMessage:(f)=>this.editMessage(f),supportsMessageEditing:()=>this.supportsMessageEditing(),formatProgressOutput:(f)=>this.formatProgressOutput(f),formatCompletionOutput:(f)=>this.formatCompletionOutput(f),onProgressUpdate:(f)=>this.onProgressUpdate(f),handleToolStatusUpdate:(f)=>this.handleToolStatusUpdate(f)});sendMessageToChannel(f){return}sendMessageWithId(f){return Promise.resolve(void 0)}editMessage(f){return Promise.resolve(!1)}supportsMessageEditing(){return!1}registerProgressCallback(f){this.progress.registerProgressCallback(f)}unregisterProgressCallback(){this.progress.unregisterProgressCallback()}hasProgressCallback(){return this.progress.hasProgressCallback()}trackAgentResponseForJob(f,A,$){this.progress.trackAgentResponseForJob(f,A,$)}async onRegister(f){await super.onRegister(f),z$(f,{onProgress:async(A,$)=>{await this.handleProgressEvent(A,$)},onError:(A)=>{this.logger.error("Error handling progress event",{error:A,interfaceId:this.id})},onInvalidSchema:()=>{this.logger.warn("Invalid progress event schema",{interfaceId:this.id})}}),v$(f,{onToolActivity:async(A)=>{await this.handleToolActivityEvent(A)},onError:(A)=>{this.logger.error("Error handling tool activity event",{error:A,interfaceId:this.id})},onInvalidSchema:()=>{this.logger.warn("Invalid tool activity event schema",{interfaceId:this.id})}}),this.logger.debug("Message interface registered with progress and tool handlers",{id:this.id})}async onShutdown(){await this.progress.close(),await super.onShutdown()}async handleProgressEvent(f,A){await this.progress.handleProgressEvent(f)}formatProgressOutput(f){return h$(f)}formatCompletionOutput(f){return y$(f)}async onProgressUpdate(f){}async handleToolActivityEvent(f){await this.progress.handleToolActivityEvent(f)}async handleToolStatusUpdate(f){}async handleAgentResponseToolStatuses(f,A){await this.progress.handleAgentResponseToolStatuses(f,A)}getProgressEvents(){return this.progress.getProgressEvents()}getActiveProgressEvents(){return this.progress.getActiveProgressEvents()}startProcessingInput(f=null){this.progress.startProcessingInput(f)}endProcessingInput(){this.progress.endProcessingInput()}getCurrentChannelId(){return this.progress.getCurrentChannelId()}}function iU(f){let A=oU(f.status),$=sU(f),Z=aU(f),V=Z?`${A}: ${$} ${Z}`:`${A}: ${$}`;return{title:A,label:$,...Z?{amount:Z}:{},...f.message?{message:f.message}:{},fallback:f.message?`${V}
|
|
8
|
-
${f.message}`:V}}function sU(f){let A=f.metadata.operationType.replace(/_/g," ");return f.metadata.operationTarget?`${A}: ${f.metadata.operationTarget}`:A}function aU(f){if(!f.progress||f.progress.total<=0)return;return`${f.progress.current}/${f.progress.total} (${f.progress.percentage}%)`}function oU(f){switch(f){case"pending":return"Job queued";case"processing":return"Job processing";case"completed":return"Job completed";case"failed":return"Job failed"}}var D8=new Set(["yes","y","ok","sure","proceed","confirm","go"]),O8=new Set(["no","n","cancel","abort","stop","nope"]);function Pf(f){let A=f.toLowerCase().trim();if(A==="")return;if(D8.has(A))return{confirmed:!0};if(O8.has(A))return{confirmed:!1};return}function rU(f){return f?.filter((A)=>A.kind==="tool-approval"&&A.state==="approval-requested")??[]}function tU(f){return f?.find((A)=>A.kind==="tool-approval"&&(A.state==="output-available"||A.state==="output-error"||A.state==="output-denied"))}function eU(f,A){if(A.length===0)return f;if(f.trim().length>0)return f;if(A.length===1)return A[0]?.summary??f;return"Multiple approvals required."}function f0(f){let A=f.state==="output-error"?"failed":f.state==="output-denied"?"declined":"completed";return{resolution:A,summary:f.summary,toolName:f.toolName,error:A==="failed"?f.error:void 0}}function $0({message:f,approvalIds:A}){if(A.size===0)return{kind:"not-confirmation"};let $=d$(f,A);if(!$)return{kind:"notice",message:"Please reply with yes to confirm or no/cancel to abort."};if(!$.approvalId&&V0(f))return{kind:"notice",message:`No matching pending approval id. Pending approval ids: ${A0(A)}.`};if(A.size>1&&!$.approvalId)return{kind:"notice",message:`Multiple approvals are pending; include one approval id with yes or no/cancel: ${A0(A)}.`};let Z=$.approvalId??k8(A);if(!Z)return{kind:"notice",message:"No pending approval to resolve."};return{kind:"confirm",approvalId:Z,confirmed:$.confirmed}}function d$(f,A){let $=Pf(f),Z=Z0(f,A);if($)return{...$,...Z?{approvalId:Z}:{}};let V=f.split(/\s+/).map((H)=>Pf(H)).find((H)=>H!==void 0);if(!V)return;return{...V,...Z?{approvalId:Z}:{}}}function Z0(f,A){if(!A||A.size===0)return;let $=f.toLowerCase();return[...A].sort((Z,V)=>V.length-Z.length).find((Z)=>U0($,Z.toLowerCase()))}function U0(f,A){let $=A.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^a-z0-9_-])${$}($|[^a-z0-9_-])`).test(f)}function V0(f){return/(^|[^a-z0-9_-])approval[:-][a-z0-9_-]+/i.test(f)}function k8(f){for(let A of f)return A;return}function A0(f){return[...f].join(", ")}var J8=U.object({kind:U.string().min(1),id:U.string().min(1)}),x8=U.object({kind:U.string().min(1),filename:U.string().min(1),mediaType:U.string().min(1),sizeBytes:U.number().nonnegative().optional(),source:J8.optional()}),Q8=U.array(x8),M6=U.array(af),w8=U.array(sf),T8=U.record(U.string(),U.unknown());function Ef(f){if(typeof f==="string")try{return Sf(JSON.parse(f))}catch{return null}return Sf(f)}function i$(f){let A=Ef(f),$=Q8.safeParse(A?.attachments);return $.success?$.data:[]}function H0(f){let $=Ef(f)?.cards;if(!Array.isArray($))return[];return $.map((Z)=>of.safeParse(Z)).filter((Z)=>Z.success).map((Z)=>Z.data)}function OA(f,A){let $=[],Z=new Set;for(let V of f){let H=Sf(V);if(!H)continue;if(A.role&&H.role!==A.role)continue;for(let L of i$(H.metadata)){if(L.source?.kind!==A.sourceKind)continue;if(Z.has(L.source.id))continue;Z.add(L.source.id),$.push(L.source.id)}}return $}function kA(f){let A=new Set;for(let $ of f){let Z=Sf($);if(!Z)continue;let H=Ef(Z.metadata)?.cards;if(!Array.isArray(H))continue;let L=H.filter((Y)=>Sf(Y)?.kind==="tool-approval"),X=w8.safeParse(L);if(!X.success)continue;for(let Y of X.data)if(Y.state==="approval-requested")A.add(Y.id);else A.delete(Y.id)}return A}function Sf(f){let A=T8.safeParse(f);return A.success?A.data:null}class s${options;pendingByConversation=new Map;constructor(f){this.options=f}rememberFromResponse(f,A){if(!A.pendingConfirmations||A.pendingConfirmations.length===0)return;this.pendingByConversation.set(f,new Set(A.pendingConfirmations.map(($)=>$.id)))}replaceApprovals(f,A){if(A.length===0){this.pendingByConversation.delete(f);return}this.pendingByConversation.set(f,new Set(A))}async getApprovalIds(f){let A=this.pendingByConversation.get(f);if(A&&A.size>0)return new Set(A);let $=await this.restoreApprovalIds(f);if($.size>0)this.pendingByConversation.set(f,$);return new Set($)}removeApproval(f,A){let $=this.pendingByConversation.get(f);if(!$)return;if($.delete(A),$.size===0)this.pendingByConversation.delete(f)}deleteConversation(f){this.pendingByConversation.delete(f)}syncFromResponse(f,A,$){if(A.pendingConfirmations===void 0)return;let Z=new Set(A.pendingConfirmations.map((V)=>V.id).filter((V)=>V!==$));if(Z.size===0){this.pendingByConversation.delete(f);return}this.pendingByConversation.set(f,Z)}formatRemainingApprovalHelp(f,A){if(A.pendingConfirmations!==void 0)return;let $=this.pendingByConversation.get(f);if(!$||$.size===0)return;return`Remaining pending approval ids: ${[...$].map((Z)=>`\`${Z}\``).join(", ")}.`}async restoreApprovalIds(f){try{let A=await this.options.loadMessages(f);return kA(A)}catch(A){return this.options.onRestoreError?.(A,f),new Set}}}var q8=U.record(U.string(),U.unknown());function L0(f){let A=q8.safeParse(f);return A.success?A.data:null}function JA(f,A){return L0(f)?.[A]}function d(f,A){let $=JA(f,A);return typeof $==="string"?$:void 0}function X0(f,A){let $=JA(f,A);return typeof $==="boolean"?$:void 0}function m8(f){return Array.isArray(f.toolResults)?f.toolResults[0]:void 0}function S8(f){if(!Array.isArray(f.cards))return;return f.cards.find((A)=>d(A,"kind")==="tool-approval")}function E8(f){return JA(f,"data")}function z8(f){let $=f.indexOf(`
|
|
9
|
-
|
|
10
|
-
Result:`);if($===-1)return;let Z=f.slice($+9).trim();if(!Z)return;try{return JSON.parse(Z)}catch{return}}function y8(f){if(!f)return;let A=f.replace(/^system[_-]/,"").split(/[_-]+/).filter(Boolean);if(A.length===0)return;let $=A.join(" ");return`${$.charAt(0).toUpperCase()}${$.slice(1)}`}function xA(f,A){if(A==="declined")return{label:"Declined",variant:"declined"};let $=S8(f),Z=m8(f),V=y8(d($,"toolName")??d(Z,"toolName")),H=JA($,"output")??E8(Z)??z8(f.text),L=d($,"state"),X=X0(H,"success"),Y=d($,"error")??d(H,"error")??d(H,"message");if(L==="output-error")return{label:`${V?`${V} failed`:"Action failed"}${Y?` \xB7 ${Y}`:""}`,variant:"error"};if(L==="output-available")return{label:V?`${V} completed`:"Action completed",variant:"success"};if(L==="output-denied")return{label:V?`${V} denied`:"Action denied",variant:"declined"};if(X===!1)return{label:`${V?`${V} failed`:"Action failed"}${Y?` \xB7 ${Y}`:""}`,variant:"error"};if(f.text.startsWith("Error:"))return{label:`Action failed \xB7 ${f.text.replace(/^Error:\s*/,"")}`,variant:"error"};if(f.text.startsWith("Failed:"))return{label:`${V?`${V} failed`:"Action failed"}${Y?` \xB7 ${Y}`:""}`,variant:"error"};if(X===!0)return{label:V?`${V} completed`:"Action completed",variant:"success"};if(f.text.startsWith("Completed:"))return{label:V?`${V} completed`:"Action completed",variant:"success"};return{label:f.text?`Approved \xB7 ${f.text}`:"Approved",variant:"success"}}function Y0(f){switch(f){case"success":return"Approval confirmed";case"declined":return"Approval declined";case"error":return"Action failed"}}function QA(f){if(typeof f==="string")return f;if(typeof f==="number"||typeof f==="boolean")return String(f);let A=L0(f);if(!A)return;let $=d(A,"error")??d(A,"message");if(X0(A,"success")===!1)return $?`Failed \xB7 ${$}`:"Failed";return}function a$(f){return["Approvals pending:",...f.map((A)=>`${A.id}: ${A.summary}`),"Reply yes <approval-id> to confirm one item, or no <approval-id> to abort it."].join(`
|
|
11
|
-
`)}function M0(f){if(!f||f.length===0)return;if(f.length===1){let A=f[0];if(!A)return;return[`Approval required: ${A.summary}`,"Reply yes to confirm or no/cancel to abort."].join(`
|
|
12
|
-
`)}return a$(f)}function F0({response:f,confirmed:A,remainingApprovalHelp:$,deniedCardIds:Z,formatCard:V,formatPendingConfirmationHelp:H}){let L=xA(f,A?"approved":"declined"),X=f.pendingConfirmations&&f.pendingConfirmations.length>1?H(f.pendingConfirmations):void 0,Y=[L.label,...K0(f.cards,Z).map(V),X,$].filter(b8);return{variant:L.variant,parts:Y}}function K0(f,A){return(f??[]).filter(($)=>$.kind==="attachment"&&Boolean(A?.has($.id)))}function h8(f,A){return(f??[]).filter(($)=>$.kind==="attachment"&&!A?.has($.id))}function v8(f,A){let $=Boolean(A?.length);return(f??[]).filter((Z)=>{if(Z.kind==="attachment")return!1;return!($&&Z.kind==="tool-approval"&&Z.state==="approval-requested")})}function C0(f,A){let $=f.pendingConfirmations??[],Z=[{kind:"text",text:f.text},...K0(f.cards,A.deniedCardIds).map((V)=>({kind:"denied-artifact",card:V})),...h8(f.cards,A.deniedCardIds).map((V)=>({kind:"artifact",card:V})),...v8(f.cards,f.pendingConfirmations).map((V)=>({kind:"supplemental",card:V}))];if($.length>0)Z.push({kind:"approvals",cards:(f.cards??[]).filter((V)=>V.kind==="tool-approval"&&V.state==="approval-requested"),confirmations:$});return{directives:Z,jobIds:j8(f)}}function j8(f){let A=new Set;for(let $ of f.toolResults??[])if($.jobId)A.add($.jobId);for(let $ of f.cards??[])if($.kind==="attachment"&&$.jobId)A.add($.jobId);return[...A]}function b8(f){return Boolean(f?.trim())}function G0({disposition:f,filename:A}){return`${f}; filename="${g8(A)}"; filename*=UTF-8''${u8(A)}`}function g8(f){return f.replace(/[^\x20-\x7E]|["\\\r\n]/g,"_")}function u8(f){return encodeURIComponent(f).replace(/[!'()*]/g,(A)=>`%${A.charCodeAt(0).toString(16).toUpperCase()}`)}function wA(f){let A=P0(r$(f,"attachment"));if(!A)return null;let $=a(f,"jobId"),Z=a(f,"description"),V=a(A,"mediaType"),H=a(A,"filename"),L=o$(c8(A,"sizeBytes")),X=a(A,"url"),Y=a(A,"downloadUrl"),M=a(A,"previewUrl");return{...$!==void 0?{jobId:$}:{},title:a(f,"title")??"Generated artifact",...Z!==void 0?{description:Z}:{},...V!==void 0?{mediaType:V}:{},...H!==void 0?{filename:H}:{},...L!==void 0?{sizeLabel:L}:{},...X!==void 0?{url:X}:{},...Y!==void 0?{downloadUrl:Y}:{},...M!==void 0?{previewUrl:M}:{}}}function o$(f){if(f===void 0)return;if(!Number.isFinite(f)||f<0)return;if(f<1024)return`${f} B`;let A=["KB","MB","GB"],$=f/1024;for(let Z of A){if($<1024||Z==="GB")return`${$.toFixed($>=10?0:1)} ${Z}`;$/=1024}return}var I8=U.record(U.string(),U.unknown());function P0(f){let A=I8.safeParse(f);return A.success?A.data:null}function r$(f,A){return P0(f)?.[A]}function a(f,A){let $=r$(f,A);return typeof $==="string"?$:void 0}function c8(f,A){let $=r$(f,A);return typeof $==="number"?$:void 0}var W0="upload.txt";var R0=5000000,p8=[".md",".txt",".markdown"],l8=["text/plain","text/markdown","text/x-markdown"],t$=new Map([[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".webp","image/webp"],[".gif","image/gif"],[".pdf","application/pdf"]]),n8=new Set(t$.values());function qA(f,A="upload.txt"){let $=f.split(/[\\/]/).at(-1)?.trim()??"",Z=Array.from($).filter((V)=>{let H=V.charCodeAt(0);return H>31&&H!==127}).join("").slice(0,160);return Z.length>0?Z:A}function mA(f,A){let $=A?.trim()??"";if($.length>0)return $;let Z=f.toLowerCase();if(Z.endsWith(".md")||Z.endsWith(".markdown"))return"text/markdown";if(Z.endsWith(".txt"))return"text/plain";return"application/octet-stream"}function zf(f,A){let $=A?.trim()??"",Z=$.split(";",1)[0]?.toLowerCase()??$;if(Z.length>0&&Z!=="application/octet-stream")return Z;let V=mA(f,void 0);if(V!=="application/octet-stream")return V;let H=f.toLowerCase();for(let[L,X]of t$)if(H.endsWith(L))return X;return"application/octet-stream"}function yf(f,A){if(A&&l8.some(($)=>A.toLowerCase().startsWith($)))return!0;return p8.some(($)=>f.toLowerCase().endsWith($))}function SA(f){return f<=1e5}function EA(f){return f<=5000000}function zA(f,A){let $=zf(f,A);if(n8.has($))return!0;return t$.has(d8(f))}function B0(f,A){let $=zf(f,A);if(yf(f,$))return"text";if(zA(f,$))return"file";return}function _0(f,A){if(A<=0)return!0;return f==="text"?SA(A):EA(A)}function e$(f){if(f.includes(0))return!1;try{return new TextDecoder("utf-8",{fatal:!0}).decode(f),!0}catch{return!1}}function fZ(f){let A=qA(f.filename,f.fallbackFilename),$=mA(A,f.mediaType);if(!yf(A,$))return{ok:!1,code:"unsupported_type",message:`Unsupported file upload type: ${A}`};if(!SA(f.content.byteLength))return{ok:!1,code:"file_too_large",message:`File upload too large: ${A}`};if(!e$(f.content))return{ok:!1,code:"binary_content",message:`Unsupported file upload type: ${A}`};return{ok:!0,filename:A,mediaType:$,sizeBytes:f.content.byteLength,text:new TextDecoder("utf-8").decode(f.content).replace(/^\uFEFF/,"")}}function D0(f){let A=qA(f.filename,f.fallbackFilename),$=zf(A,f.mediaType);if(yf(A,$)){let Z=fZ({filename:A,mediaType:$,content:f.content,...f.fallbackFilename!==void 0&&{fallbackFilename:f.fallbackFilename}});return Z.ok?{...Z,kind:"text"}:Z}if(!zA(A,$))return{ok:!1,code:"unsupported_type",message:`Unsupported file upload type: ${A}`};if(!EA(f.content.byteLength))return{ok:!1,code:"file_too_large",message:`File upload too large: ${A}`};if(!i8(f.content,$))return{ok:!1,code:"unsupported_type",message:`Unsupported file upload type: ${A}`};return{ok:!0,kind:"file",filename:A,mediaType:$,sizeBytes:f.content.byteLength}}function d8(f){let A=f.lastIndexOf(".");return A>=0?f.slice(A).toLowerCase():""}function i8(f,A){switch(A){case"image/png":return N0(f,[137,80,78,71]);case"image/jpeg":return N0(f,[255,216,255]);case"image/gif":return TA(f,"GIF87a")||TA(f,"GIF89a");case"image/webp":return TA(f,"RIFF")&&O0(f,"WEBP",8);case"application/pdf":return TA(f,"%PDF-");default:return!1}}function N0(f,A){return A.every(($,Z)=>f[Z]===$)}function TA(f,A){return O0(f,A,0)}function O0(f,A,$){return Array.from(A).every((Z,V)=>f[$+V]===Z.charCodeAt(0))}class AZ{options;recentUploads=new Map;maxRecent;constructor(f){this.options=f,this.maxRecent=f.maxRecent??20}remember(f,A){if(A.length===0)return;let $=this.recentUploads.get(f)??[];this.recentUploads.set(f,[...$,...A].slice(-this.maxRecent))}clear(){this.recentUploads.clear()}async selectPriorUploads({conversationId:f,currentAttachments:A,canRestore:$}){if(A.length>0)return A;if(!$)return A;let Z=await this.getRecentUploads(f);if(Z.length===0)return A;return Z}async getRecentUploads(f){let A=this.recentUploads.get(f)??[];if(A.length>0)return A;let $=await this.restoreRecentUploads(f);if($.length>0)this.recentUploads.set(f,$.slice(-this.maxRecent));return $}async restoreRecentUploads(f){let A=await this.loadMessages(f),$=[this.options.sourceKind,...this.options.legacySourceKinds??[]],Z=[];for(let V of $){let H=OA(A,{sourceKind:V,role:"user"});for(let L of H){let X=await this.restoreAttachment(L,V);if(X)Z.push(X)}}return Z}async loadMessages(f){try{return await this.options.loadMessages(f)}catch(A){return this.options.onLoadError?.(A,f),[]}}async restoreAttachment(f,A){try{return await this.options.restoreAttachment(f,A)}catch($){this.options.onRestoreError?.($,f);return}}}function k0(f){return typeof f==="object"&&f!==null&&!Array.isArray(f)}function s8(f){return k0(f)&&f.kind==="upload"&&typeof f.id==="string"}function hf(f){if(s8(f))return"uploaded file";if(Array.isArray(f))return f.map((A)=>hf(A));if(!k0(f))return f;return yA(f)}function yA(f){return Object.fromEntries(Object.entries(f).map(([A,$])=>[A,hf($)]))}function J0(f){if(f.kind!=="tool-approval")return f;return{...f,...f.input!==void 0?{input:yA(f.input)}:{},...f.output!==void 0?{output:hf(f.output)}:{}}}function x0(f,A){if(f.kind==="attachment")return a8(f,A);if(f.kind==="tool-approval")return o8(f);if(f.kind==="sources")return r8(f,A);return t8(f,A)}function a8(f,A){if(A.deniedCardIds?.has(f.id))return"Artifact: Not available at your access level.";let $=wA(f);if(!$)return"Artifact: Generated artifact";let Z=[`Artifact: ${$.title}`];if($.description)Z.push($.description);if($.filename)Z.push(`File: ${$.filename}`);if($.mediaType)Z.push(`Type: ${$.mediaType}`);if($.sizeLabel)Z.push(`Size: ${$.sizeLabel}`);let V=A.resolveUrl($.previewUrl),H=A.resolveUrl($.url),L=A.resolveUrl($.downloadUrl);if(V&&!A.isHiddenUrl(V))Z.push(`Preview: ${V}`);if(H&&!A.isHiddenUrl(H))Z.push(`Open: ${H}`);if(L&&!A.isHiddenUrl(L))Z.push(`Download: ${L}`);return Z.join(`
|
|
13
|
-
`)}function o8(f){let A=[`Approval: ${f.summary||f.toolName}`];if(A.push(`Status: ${f.state}`),f.preview)A.push(f.preview);let $=QA(f.output);if($)A.push(`Result: ${$}`);if(f.error)A.push(`Error: ${f.error}`);return A.join(`
|
|
14
|
-
`)}function r8(f,A){let $=[`Sources: ${f.title??"Retrieved context"}`];for(let Z of f.sources){let V=A.resolveUrl(Z.url),H=V&&!A.isHiddenUrl(V)?` \u2014 ${V}`:"";$.push(`- ${Z.title??Z.source}${H}`)}return $.join(`
|
|
15
|
-
`)}function t8(f,A){let $=[`Actions: ${f.title??"Suggested actions"}`];for(let Z of f.actions){let V=Z.type==="event"&&A.eventActionUnavailableLabel?` (${A.eventActionUnavailableLabel})`:"";$.push(`- ${Z.label}${V}`)}return $.join(`
|
|
16
|
-
`)}function Q0(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:e8(f.isBot)}:{}}}function e8(f){if(typeof f==="boolean")return f;return f.toLowerCase()==="true"}function w0(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 T0(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(fV),"","Latest message to answer:",f.message].join(`
|
|
17
|
-
`),metadata:{supersededMessageCount:f.skippedMessages.length,supersededMessageIds:f.skippedMessages.map((Z)=>Z.id).filter((Z)=>Z!==void 0)}}}function fV(f){let A=f.text.trim(),$=f.authorName?.trim();return $?`- ${$}: ${A}`:`- ${A}`}async function YV(f){let{entityType:A,title:$,deriveId:Z,regeneratePrompt:V,context:H}=f,L=Z($),X=await H.entityService.getEntity({entityType:A,id:L});if(!X||X.metadata.status==="generating")return $;H.logger.debug(`Entity ID collision: ${A}/${L}, asking AI for a new title`);let Y=U.object({title:U.string().max(80).describe("A short, unique title (2-6 words)")}),{object:M}=await H.ai.generateObject(`The title "${$}" is already taken. ${V}`,Y),C=M.title;return H.logger.debug(`AI suggested new title: "${C}"`),C}class hA{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 MV="current";class q0{store;schema;createEmpty;key;queue=new hA;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??MV}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 U7=["GET","POST","PUT","DELETE","OPTIONS"];function FV(f,A={}){return new Response(JSON.stringify(f),{status:A.status??200,headers:{"Content-Type":"application/json; charset=utf-8",...A.headers}})}var $Z="cms:register-workspace";var KV=U.object({workspaceUrl:U.string()});async function CV(f,A){let $=await f.messaging.send({type:$Z,payload:A});if(!("success"in $)||!$.success)return;let Z=KV.safeParse($.data);return Z.success?Z.data.workspaceUrl:void 0}var ZZ=vf.extend({id:U.literal("brain-character"),entityType:U.literal("brain-character")}),vA=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 m0=U.record(U.string(),U.unknown());class jA extends jf{constructor(){super({entityType:"brain-character",purpose:"The brain's own identity, character, and purpose (singleton).",schema:ZZ,frontmatterSchema:vA,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("",m0.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("",m0.parse(A))}}class bA extends gA{adapter=new jA;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 bA(f,A,$)}constructor(f,A,$){super(f,A,"brain-character",$??bA.getDefaultCharacter(),bf("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 UZ=vf.extend({id:U.literal("anchor-profile"),entityType:U.literal("anchor-profile")}),S0=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 GV=U.record(U.string(),U.unknown());class uA extends jf{constructor(){super({entityType:"anchor-profile",purpose:"The profile of the brain's Anchor (singleton).",schema:UZ,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}=Tf(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("",GV.parse(A))}}class gf extends gA{adapter=new uA;static getDefaultProfile(){return{name:"Unknown"}}static createFresh(f,A,$){return new gf(f,A,$)}constructor(f,A,$){super(f,A,"anchor-profile",$??gf.getDefaultProfile(),bf("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 IA=U.enum(["person","team","organization"]),PV=U.object({kind:U.string().trim().min(1),category:IA,labels:U.object({singular:U.string().trim().min(1),plural:U.string().trim().min(1)})});function NV(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 E0{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 $=PV.parse(A);NV(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((L)=>L.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 z0=30000;class HZ{logger;resolver;links=[];actorIndex=new Map;negativeActorIndex=new Map;static createFresh(f,A){return new HZ(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=VZ(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 $=VZ(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()+z0),f;let H={identity:f.identity,...f.displayName?{label:f.displayName}:{}},L={...V,actors:[H],matchedActor:H};return this.actorIndex.set($,{resolution:L,expiresAt:Date.now()+z0}),this.links=[...this.links.filter((X)=>X.userId!==L.userId),L],this.enrichedActor(f,L)}enrichedActor(f,A){return{...f,identity:{kind:"user",userId:A.userId,canonicalId:A.canonicalId},...A.displayName?{displayName:A.displayName}:{}}}}var y0="https://rizom.ai/ext/anchor-profile/v1",h0=U.looseObject({id:U.string(),description:U.string(),name:U.string().optional(),tags:U.array(U.string()).optional().default([])}),v0=Yf.extend({kind:U.string().trim().min(1).optional(),category:IA.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"})}),WV=U.looseObject({uri:U.string(),params:U.record(U.string(),U.unknown()).optional()}),j0=U.looseObject({name:U.string(),url:U.string(),description:U.string().optional(),skills:U.array(h0).optional().default([]),capabilities:U.looseObject({extensions:U.array(WV).optional().default([])}).optional()});function RV(f){let A=j0.safeParse(f);if(!A.success)return null;let $=A.data,V=($.capabilities?.extensions??[]).find((L)=>L.uri===y0),H=null;if(V?.params){let L=v0.safeParse(V.params);if(L.success)H=L.data}return{brainName:$.name,url:$.url,description:$.description??"",skills:$.skills.map((L)=>({id:L.id,name:L.name??L.id,description:L.description,tags:L.tags})),anchor:H}}var BV=U.object({name:U.string(),description:U.string(),tags:U.array(U.string()),examples:U.array(U.string())});import{EventEmitter as u0}from"events";var m={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 LZ{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 L=await G.runPromiseExit(v.close(this.scope,f));if(!$&&u.isFailure(L))A=MA.squash(L.cause),$=!0;if($)throw A}}function b0(f,A){let $=f.getMessageBus(),Z=new Set,V={send:(N)=>$.send(N),subscribe:(N,D,W)=>{let Q=!0,y=new Set,T=(nA)=>{if(!Q)return{noop:!0};let FZ,KZ=new Promise((r)=>{FZ=r});y.add(KZ);let dA=()=>{y.delete(KZ),FZ()},CZ;try{CZ=Promise.resolve(D(nA))}catch(r){throw dA(),r}return CZ.then((r)=>{return dA(),r},(r)=>{throw dA(),r})},lA=$.subscribe(N,T,W),Nf={type:N,originalHandler:D,stopAdmission:()=>{if(!Q)return;Q=!1,lA(),Z.delete(Nf)}};Z.add(Nf);try{A.addIngress({stopAdmission:Nf.stopAdmission,drain:async()=>{await Promise.all(y)}})}catch(nA){throw Nf.stopAdmission(),nA}return Nf.stopAdmission},unsubscribe:(N,D)=>{let W=[...Z].filter((Q)=>Q.type===N&&Q.originalHandler===D);if(W.length===0){$.unsubscribe(N,D);return}for(let Q of W)Q.stopAdmission()}},H=f.getAttachmentRegistry(),L={...H,register:(N,D,W)=>{let Q=!0,y=H.register(N,D,W),T=()=>{if(!Q)return;Q=!1,y()};return A.addFinalizer(T),T}},X=f.getEntityRegistry(),Y=new Proxy(X,{get(N,D){let W=Reflect.get(N,D,N);if(D==="registerEntityType"&&typeof W==="function")return(...Q)=>{let y=Reflect.apply(W,N,Q),T=Q[0];if(typeof T==="string")A.addFinalizer(()=>N.unregisterEntityType(T));return y};return typeof W==="function"?W.bind(N):W}}),M=f.getProfileKindRegistry(),C=new Proxy(M,{get(N,D){let W=Reflect.get(N,D,N);if(D==="register"&&typeof W==="function")return(...Q)=>{let y=Reflect.apply(W,N,Q),T=Q[0];if(typeof T==="string")A.addFinalizer(()=>N.unregisterPlugin(T));return y};return typeof W==="function"?W.bind(N):W}}),K=f.getChannelRegistry(),R=new Proxy(K,{get(N,D){let W=Reflect.get(N,D,N);if((D==="registerDescriptor"||D==="registerDeliveryProvider")&&typeof W==="function")return(...Q)=>{let y=Reflect.apply(W,N,Q),T=Q[0];if(typeof T==="string")A.addFinalizer(()=>N.unregisterPlugin(T));return y};return typeof W==="function"?W.bind(N):W}}),B=f.getInboxRegistry(),q=new Proxy(B,{get(N,D){let W=Reflect.get(N,D,N);if(D==="registerSource"&&typeof W==="function")return(...Q)=>{let y=Reflect.apply(W,N,Q),T=Q[0];if(typeof T==="string")A.addFinalizer(()=>N.unregisterPlugin(T));return y};return typeof W==="function"?W.bind(N):W}}),k=f.getDataSourceRegistry(),I=new Proxy(k,{get(N,D){let W=Reflect.get(N,D,N);if(D==="register"&&typeof W==="function")return(...Q)=>{let y=Reflect.apply(W,N,Q),T=Q[0];if(typeof T==="object"&&T!==null&&"id"in T&&typeof T.id==="string"){let lA=T.id.includes(":")?T.id:`shell:${T.id}`;A.addFinalizer(()=>N.unregister(lA))}return y};return typeof W==="function"?W.bind(N):W}}),o=f.getInsightsRegistry(),z=new Proxy(o,{get(N,D){let W=Reflect.get(N,D,N);if(D==="register"&&typeof W==="function")return(...Q)=>{let y=Reflect.apply(W,N,Q),T=Q[0];if(typeof T==="string")A.addFinalizer(()=>N.unregister(T));return y};return typeof W==="function"?W.bind(N):W}}),c=new Proxy(f,{get(N,D){if(D==="getMessageBus")return()=>V;if(D==="getAttachmentRegistry")return()=>L;if(D==="getEntityRegistry")return()=>Y;if(D==="getDataSourceRegistry")return()=>I;if(D==="getProfileKindRegistry")return()=>C;if(D==="getChannelRegistry")return()=>R;if(D==="getInboxRegistry")return()=>q;if(D==="getInsightsRegistry")return()=>z;let W=Reflect.get(N,D,N);return typeof W==="function"?W.bind(N):W}});return FU(f,c),c}class XZ{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 LZ;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 L=await V.register(b0(A,H),$);return Z.status=m.INITIALIZED,this.logger.debug(`Initialized plugin: ${f}`),this.events.emit(p.INITIALIZED,f,V),L}catch(L){throw this.logger.error(`Error initializing plugin ${f}: ${S(L)}`),await this.failPluginInitialization(f,L),L}}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!==m.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!==m.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=Cf($);A.status=m.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!==m.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!==m.ERROR,V=Cf(A);if($.status=m.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===m.DISABLED)return;this.logger.debug(`Disabling plugin: ${f}`);let $=A.status===m.ERROR;await this.releasePluginResources(f,u.void);let Z=this.plugins.get(f);if(!$&&Z&&Z.status!==m.DISABLED)Z.status=m.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 YZ{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 L of A){if($.has(L))continue;if(!this.plugins.get(L))continue;if(this.getUnmetDependencies(L).length===0)try{await f(L),$.add(L),Z=!0}catch(M){let C=S(M);this.logger.error(`Failed to initialize plugin ${L}: ${C}`),$.add(L),Z=!0}}}let V=A.filter((L)=>!$.has(L));if(V.length>0){let L=V.join(", ");this.logger.error(`Failed to initialize plugins due to dependency issues: ${L}`);for(let X of V){let Y=this.getUnmetDependencies(X);this.logger.error(`Plugin ${X} has unmet dependencies: ${Y.join(", ")}`);let M=this.plugins.get(X);if(M)M.status=m.ERROR,M.error=new l(X,`Unmet dependencies: ${Y.join(", ")}`);this.events.emit(p.ERROR,X,M?.error)}}let H=new Set;for(let[L,X]of this.plugins)if(X.status===m.INITIALIZED)H.add(L);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!==m.INITIALIZED)Z.push(V)}return Z}}class MZ{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 cA{projections=new Map;rules=new Map;static createFresh(){return new cA}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(OV)}listRules(){return[...this.rules.values()].sort((f,A)=>f.id.localeCompare(A.id))}validate(f){let A=this.list(),$=new Set(f.map(({type:L})=>L));for(let L of A)if(!$.has(L.targetType))throw Error(`Projection "${L.id}" targets unregistered entity type "${L.targetType}"`);let Z=f.filter(({projectionSource:L})=>L).map(({type:L})=>L).sort(),V=kV(A,Z),H=xV(A,V)[0];if(H){let L=QV(H,V);throw Error(`Projection cycle is not supported: ${[...L,L[0]].join(" -> ")}`)}return DV({projections:A,edges:V,unknownSourceTypes:_V(A,$)})}}function _V(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 OV(f){return{...f,sources:f.sources.map((A)=>({...A,types:[...A.types],...A.excludeTypes?{excludeTypes:[...A.excludeTypes]}:{}}))}}function kV(f,A){let $=new Map;for(let Z of f)for(let V of f){let H=JV(Z,V,A);if(H.length===0)continue;$.set(`${Z.id}\x00${V.id}`,new Set(H))}return Array.from($,([Z,V])=>{let[H="",L=""]=Z.split("\x00");return{from:H,to:L,causes:[...V].sort()}}).sort((Z,V)=>Z.from.localeCompare(V.from)||Z.to.localeCompare(V.to))}function JV(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 xV(f,A){let $=f.map(({id:K})=>K).sort(),Z=g0($,A),V=new Map,H=new Map,L=[],X=new Set,Y=[],M=0,C=(K)=>{V.set(K,M),H.set(K,M),M++,L.push(K),X.add(K);for(let k of Z.get(K)??[])if(!V.has(k))C(k),H.set(K,Math.min(H.get(K)??0,H.get(k)??0));else if(X.has(k))H.set(K,Math.min(H.get(K)??0,V.get(k)??0));if(H.get(K)!==V.get(K))return;let R=[],B;do{if(B=L.pop(),!B)break;X.delete(B),R.push(B)}while(B!==K);let q=Z.get(K)?.includes(K)??!1;if(R.length>1||q)Y.push(R.sort())};for(let K of $)if(!V.has(K))C(K);return Y.sort((K,R)=>(K[0]??"").localeCompare(R[0]??""))}function QV(f,A){let $=new Set(f),Z=g0(f,A),V=[...f].sort()[0];if(!V)return[];if(Z.get(V)?.includes(V))return[V];let H=(L,X)=>{for(let Y of Z.get(L)??[]){if(!$.has(Y))continue;if(Y===V)return X;if(X.includes(Y))continue;let M=H(Y,[...X,Y]);if(M)return M}return};return H(V,[V])??[...f].sort()}function g0(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 I0(f){let $=(await G.runPromise(G.all(f.map((Z)=>G.either(G.tryPromise({try:Z,catch:(V)=>V}))),{concurrency:"unbounded"}))).find(c0.isLeft);if($)throw $.left}class pA{plugins=new Map;logger;events=new u0;daemonRegistry;shell=null;initializedPluginIds=[];pluginLifecycle;dependencyResolver;capabilityRegistrar;projectionRegistry=cA.createFresh();projectionGraph;static createFresh(f,A){return new pA(f,A)}setShell(f){this.shell=f}constructor(f,A){this.logger=f.child("PluginManager"),this.events=new u0,this.daemonRegistry=A,this.pluginLifecycle=new XZ(this.plugins,this.events,this.daemonRegistry,this.projectionRegistry,f),this.dependencyResolver=new YZ(this.plugins,this.events,f),this.capabilityRegistrar=new MZ(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:m.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 I0(this.initializedPluginIds.map((f)=>()=>this.pluginLifecycle.readyPlugin(f)))}catch(f){for(let A of this.initializedPluginIds){let $=this.plugins.get(A);if($?.status===m.ERROR)await this.pluginLifecycle.failPluginInitialization(A,$.error??f)}throw f}}async startPluginDaemons(){this.logger.debug("Starting plugin daemons..."),await I0(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===m.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===m.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{n1 as ic,s as jc,tf as kc,fA as lc,F as mc,J as nc,Kf as oc,F$ as pc,K$ as qc,C$ as rc,G$ as sc,wf as tc,P$ as uc,N$ as vc,W$ as wc,w as xc,h as yc,e as zc,ff as Ac,BZ as Bc,_Z as Cc,r0 as Dc,nf as Ec,p0 as Fc,l0 as Gc,sA as Hc,aA as Ic,HA as Jc,g1 as Kc,YA as Lc,VU as Mc,u1 as Nc,J$ as Oc,rA as Pc,I1 as Qc,i0 as Rc,c1 as Sc,p1 as Tc,l1 as Uc,CA as Vc,NU as Wc,BU as Xc,_U as Yc,OU as Zc,kU as _c,e1 as $c,f8 as ad,w$ as bd,PA as cd,Xf as dd,L8 as ed,T$ as fd,Bf as gd,_f as hd,M8 as id,hU as jd,G1 as kd,R1 as ld,TZ as md,qZ as nd,mZ as od,B1 as pd,b$ as qd,g$ as rd,bU as sd,Gf as td,BA as ud,_A as vd,mf as wd,DA as xd,dU as yd,n$ as zd,iU as Ad,Pf as Bd,rU as Cd,tU as Dd,eU as Ed,f0 as Fd,$0 as Gd,d$ as Hd,i$ as Id,H0 as Jd,s$ as Kd,xA as Ld,Y0 as Md,QA as Nd,a$ as Od,M0 as Pd,F0 as Qd,C0 as Rd,G0 as Sd,wA as Td,W0 as Ud,R0 as Vd,qA as Wd,zf as Xd,yf as Yd,B0 as Zd,_0 as _d,D0 as $d,AZ as ae,hf as be,J0 as ce,x0 as de,Q0 as ee,w0 as fe,T0 as ge,YV as he,q0 as ie,U7 as je,FV as ke,$Z as le,CV as me,vA as ne,jA as oe,bA as pe,S0 as qe,Yf as re,uA as se,gf as te,E0 as ue,HZ as ve,y0 as we,RV as xe,BV as ye,l as ze,pA as Ae};
|
|
18
|
-
|
|
19
|
-
//# debugId=62E0AD7A66ED48B564756E2164756E21
|
|
20
|
-
//# sourceMappingURL=index-jpbc5wsq.js.map
|
|
File without changes
|
/package/dist/chunks/{blog-post-adapter-0qsz1np7.js.map → blog-post-adapter-2gw2r57p.js.map}
RENAMED
|
File without changes
|
|
File without changes
|
/package/dist/chunks/{linkedin-template-xm5pp9zz.js.map → linkedin-template-zt2v1zj3.js.map}
RENAMED
|
File without changes
|
|
File without changes
|