@rizom/brain 0.2.0-alpha.46 → 0.2.0-alpha.47

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.
@@ -1,4 +1,4 @@
1
- import type { z } from "./utils";
1
+ import type { z } from "zod";
2
2
  import type { DataSource, BaseDataSourceContext, BaseEntity } from "./entities";
3
3
  import type { ApiRouteDefinition, WebRouteDefinition } from "./interfaces";
4
4
 
package/dist/services.js CHANGED
@@ -166,7 +166,7 @@ Please report this to https://github.com/markedjs/marked.`,$){let Y="<p>An error
166
166
  `}format($){try{let X=[`# ${this.config.title}`,""];for(let G of this.config.mappings)this.formatField($,G,X,2);return X.join(`
167
167
  `)}catch{throw Error("Failed to format structured content")}}parse($){try{let X=this.processor.parse($),G=this.extractSections(X,2),Y=this.buildDataFromSections(G,this.config.mappings);return this.schema.parse(Y)}catch{throw Error("Failed to parse structured content")}}formatField($,X,G,Y){let q="#".repeat(Y)+" "+X.label,J=this.getValueByPath($,X.key);if(X.type==="custom"&&X.formatter){if(J!==void 0&&J!==null){G.push(q,"");let V=X.formatter(J);if(V)G.push(V,"")}return}switch(X.type){case"string":case"number":G.push(q,String(J??""),"");break;case"object":if(G.push(q),X.children&&J)for(let V of X.children)this.formatField(J,V,G,Y+1);break;case"array":if(G.push(q,""),Array.isArray(J))if(X.itemType==="object"&&X.itemMappings)J.forEach((V,W)=>{if(G.push(`${"#".repeat(Y+1)} ${X.label.slice(0,-1)} ${W+1}`),G.push(""),X.itemMappings)for(let H of X.itemMappings)this.formatField(V,H,G,Y+2)});else{for(let V of J){let W=this.defaultArrayItemFormat(V);G.push(`- ${W}`)}G.push("")}break}}getValueByPath($,X){let G=X.split("."),Y=$;for(let q of G)if(Y&&typeof Y==="object"&&q in Y)Y=Y[q];else return;return Y}defaultArrayItemFormat($){if(typeof $==="string"||typeof $==="number")return String($);return JSON.stringify($)}extractSections($,X){let G=new Map,Y=null,q=[];for(let J of $.children)if(J.type==="heading"&&J.depth===X){if(Y)G.set(Y.toLowerCase(),q);Y=this.getHeadingText(J),q=[]}else if(Y)q.push(J);if(Y)G.set(Y.toLowerCase(),q);return G}extractSubsections($,X){let G=new Map,Y=null,q=[];for(let J of $)if(J.type==="heading"&&J.depth===X){if(Y)G.set(Y.toLowerCase(),q);Y=this.getHeadingText(J),q=[]}else if(Y)q.push(J);if(Y)G.set(Y.toLowerCase(),q);return G}textNodeSchema=Q.object({type:Q.literal("text"),value:Q.string()});extractTextValue($){let X=this.textNodeSchema.safeParse($);return X.success?X.data.value:""}getHeadingText($){return $.children.filter((G)=>G.type==="text").map((G)=>this.extractTextValue(G)).join("")}buildDataFromSections($,X,G=2){let Y={};for(let q of X){let J=$.get(q.label.toLowerCase());if(q.type==="custom"&&q.parser&&J){let V=this.getTextFromSection(J),W=q.parser(V);this.setValueByPath(Y,q.key,W)}else if(q.type==="object"&&q.children&&J){let V=this.extractSubsections(J,G+1),W=this.buildDataFromSections(V,q.children,G+1);this.setValueByPath(Y,q.key,W)}else if(q.type==="array"&&J)if(q.itemType==="object"&&q.itemMappings){let V=this.extractObjectArrayItems(J,G+1,q.itemMappings);this.setValueByPath(Y,q.key,V)}else{let V=this.extractSimpleArrayItems(J);this.setValueByPath(Y,q.key,V)}else if(J){let V=this.getTextFromSection(J),W=q.type==="number"?Number(V):V;this.setValueByPath(Y,q.key,W)}}return Y}setValueByPath($,X,G){let Y=X.split("."),q=$;for(let V=0;V<Y.length-1;V++){let W=Y[V];if(!W)continue;if(!(W in q))q[W]={};q=q[W]}let J=Y[Y.length-1];if(J)q[J]=G}getTextFromSection($){let X=[];for(let G of $)if(G.type==="paragraph"){let Y=this.extractTextFromParagraph(G);if(Y)X.push(Y)}else if(G.type==="list"){let Y=G;for(let q of Y.children){let J=this.extractTextFromListItem(q);if(J)X.push(`- ${J}`)}}return X.join(`
168
168
  `)}extractTextFromParagraph($){return this.extractInlineText($.children).trim()}extractInlineText($){let X=[];for(let G of $)if(G.type==="text")X.push(this.extractTextValue(G));else if(G.type==="emphasis"){let Y=this.extractInlineText(G.children);if(Y)X.push(`*${Y}*`)}else if(G.type==="strong"){let Y=this.extractInlineText(G.children);if(Y)X.push(`**${Y}**`)}return X.join("")}extractSimpleArrayItems($){let X=[];for(let G of $)if(G.type==="list"){let Y=G;for(let q of Y.children){let J=this.extractTextFromListItem(q);if(J)X.push(J)}}return X}extractObjectArrayItems($,X,G){let Y=[],q=[],J=!1;for(let V of $)if(V.type==="heading"&&V.depth===X){if(J&&q.length>0){let W=this.extractSubsections(q,X+1),H=this.buildDataFromSections(W,G,X+1);Y.push(H)}q=[],J=!0}else if(J)q.push(V);if(J&&q.length>0){let V=this.extractSubsections(q,X+1),W=this.buildDataFromSections(V,G,X+1);Y.push(W)}return Y}extractTextFromListItem($){let X=[];for(let G of $.children)if(G.type==="paragraph"){let Y=this.extractTextFromParagraph(G);if(Y)X.push(Y)}return X.join(`
169
- `)}}var hC=Q.object({slug:Q.string(),title:Q.string(),type:Q.string(),entityId:Q.string(),contentHash:Q.string()});import{webcrypto as vY}from"crypto";var xY="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var jR=128,j2,M4;function PR($){if(!j2||j2.length<$)j2=Buffer.allocUnsafe($*jR),vY.getRandomValues(j2),M4=0;else if(M4+$>j2.length)vY.getRandomValues(j2),M4=0;M4+=$}function kY($=21){PR($|=0);let X="";for(let G=M4-$;G<M4;G++)X+=xY[j2[G]&63];return X}function n0($=12){return kY($)}var q6={START:0,INIT:10,FETCH:20,PROCESS:40,GENERATE:50,EXTRACT:60,SAVE:80,COMPLETE:100};function h1($){return $ instanceof Error?$.message:String($)}function J6($){return $ instanceof Error?$:Error(String($))}var C9={success($){return{success:!0,...$}},failure($){return{success:!1,error:h1($)}}};var CR=Q.object({success:Q.boolean(),entityId:Q.string().optional(),error:Q.string().optional()});var IR=Q.object({status:Q.enum(["healthy","warning","error","unknown"]),message:Q.string().optional(),lastCheck:Q.date().optional(),details:Q.record(Q.string(),Q.unknown()).optional()}),yY=Q.object({name:Q.string(),pluginId:Q.string(),status:Q.string(),health:IR.optional()});import{McpServer as MI}from"@modelcontextprotocol/sdk/server/mcp.js";var T9=Q.enum(["anchor","trusted","public"]);var bR=Q.object({name:Q.string(),description:Q.string(),schema:Q.any(),basePrompt:Q.string().optional(),useKnowledgeContext:Q.boolean().optional(),requiredPermission:T9,formatter:Q.any().optional(),layout:Q.object({component:Q.any(),fullscreen:Q.boolean().optional()}).optional(),dataSourceId:Q.string().optional()});var xR=Q.enum(["site-content-preview","site-content-production"]),vR=Q.object({name:Q.string(),schema:Q.any(),description:Q.string().optional(),pluginId:Q.string(),renderers:Q.object({web:Q.union([Q.function(),Q.string()]).optional()})}),kR=Q.object({enableContentGeneration:Q.boolean().default(!1),outputDir:Q.string(),workingDir:Q.string().optional(),environment:Q.enum(["preview","production"]).default("preview"),siteConfig:Q.object({title:Q.string(),description:Q.string(),url:Q.string().optional()}).optional()}),hR=Q.object({success:Q.boolean(),routesBuilt:Q.number(),errors:Q.array(Q.string()).optional(),warnings:Q.array(Q.string()).optional()});import{ResourceTemplate as RI}from"@modelcontextprotocol/sdk/server/mcp.js";var A5=Q.object({interfaceType:Q.string(),userId:Q.string(),channelId:Q.string().optional(),channelName:Q.string().optional()}),mY=Q.object({success:Q.literal(!0),data:Q.unknown(),message:Q.string().optional()}),uY=Q.object({success:Q.literal(!1),error:Q.string(),code:Q.string().optional()}),pY=Q.object({needsConfirmation:Q.literal(!0),toolName:Q.string(),description:Q.string(),args:Q.unknown()}),S9=Q.union([mY,uY,pY]);var lY=Q.union([Q.object({success:Q.literal(!0),data:Q.unknown(),message:Q.string().optional()}),Q.object({success:Q.literal(!1),error:Q.string(),code:Q.string().optional()})]);var kI=Q.object({id:Q.string(),type:Q.string(),version:Q.string(),status:Q.string()}),hI=Q.object({name:Q.string(),description:Q.string()}),dY=Q.object({label:Q.string(),url:Q.string(),pluginId:Q.string(),priority:Q.number().default(100)}),pR=Q.object({model:Q.string(),version:Q.string(),uptime:Q.number(),entities:Q.number(),embeddings:Q.number(),ai:Q.object({model:Q.string(),embeddingModel:Q.string()}),daemons:Q.array(yY),endpoints:Q.array(dY)}),yI=Q.object({pluginId:Q.string(),tool:Q.object({name:Q.string(),description:Q.string(),inputSchema:Q.record(Q.string(),Q.unknown()),handler:Q.function(),visibility:Q.enum(["public","trusted","anchor"]).optional()}),timestamp:Q.number()}),gI=Q.object({pluginId:Q.string(),resource:Q.object({uri:Q.string(),name:Q.string(),description:Q.string().optional(),mimeType:Q.string().optional(),handler:Q.function()}),timestamp:Q.number()});var lR=Q.object({id:Q.string(),version:Q.string(),type:Q.enum(["core","entity","service","interface"]),description:Q.string().optional(),dependencies:Q.array(Q.string()).optional(),packageName:Q.string()});var dI=Q.object({toolName:Q.string(),args:Q.unknown(),progressToken:Q.union([Q.string(),Q.number()]).optional(),hasProgress:Q.boolean().optional(),...A5.shape}),cI=Q.object({resourceUri:Q.string()});var oI=Q.object({name:Q.string(),schema:Q.custom(($)=>$ instanceof Q.ZodType)});var b=Symbol.for("drizzle:entityKind");function y1($,X){if(!$||typeof $!=="object")return!1;if($ instanceof X)return!0;if(!Object.prototype.hasOwnProperty.call(X,b))throw Error(`Class "${X.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let G=Object.getPrototypeOf($).constructor;if(G)while(G){if(b in G&&G[b]===X[b])return!0;G=Object.getPrototypeOf(G)}return!1}class s0{constructor($,X){this.table=$,this.config=X,this.name=X.name,this.keyAsName=X.keyAsName,this.notNull=X.notNull,this.default=X.default,this.defaultFn=X.defaultFn,this.onUpdateFn=X.onUpdateFn,this.hasDefault=X.hasDefault,this.primary=X.primaryKey,this.isUnique=X.isUnique,this.uniqueName=X.uniqueName,this.uniqueType=X.uniqueType,this.dataType=X.dataType,this.columnType=X.columnType,this.generated=X.generated,this.generatedIdentity=X.generatedIdentity}static[b]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue($){return $}mapToDriverValue($){return $}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class I9{static[b]="ColumnBuilder";config;constructor($,X,G){this.config={name:$,keyAsName:$==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:X,columnType:G,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default($){return this.config.default=$,this.config.hasDefault=!0,this}$defaultFn($){return this.config.defaultFn=$,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn($){return this.config.onUpdateFn=$,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName($){if(this.config.name!=="")return;this.config.name=$}}var V0=Symbol.for("drizzle:Name");function cY($,...X){return $(...X)}function rY($,X){return`${$[V0]}_${X.join("_")}_unique`}class V6 extends s0{constructor($,X){if(!X.uniqueName)X.uniqueName=rY($,[X.name]);super($,X);this.table=$}static[b]="PgColumn"}class dR extends V6{static[b]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op($){return this.indexConfig.opClass=$,this}}class cR extends V6{static[b]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor($,X){super($,X);this.enum=X.enum}getSQLType(){return this.enum.enumName}}var iY=Symbol.for("drizzle:isPgEnum");function oY($){return!!$&&typeof $==="function"&&iY in $&&$[iY]===!0}class rR extends V6{static[b]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor($,X){super($,X);this.enum=X.enum}getSQLType(){return this.enum.enumName}}class B5{static[b]="Subquery";constructor($,X,G,Y=!1,q=[]){this._={brand:"Subquery",sql:$,selectedFields:X,alias:G,isWith:Y,usedTables:q}}}var nY="0.44.7";var b9,x9,sY={startActiveSpan($,X){if(!b9)return X();if(!x9)x9=b9.trace.getTracer("drizzle-orm",nY);return cY((G,Y)=>Y.startActiveSpan($,(q)=>{try{return X(q)}catch(J){throw q.setStatus({code:G.SpanStatusCode.ERROR,message:J instanceof Error?J.message:"Unknown error"}),J}finally{q.end()}}),b9,x9)}};var F4=Symbol.for("drizzle:ViewBaseConfig");var v9=Symbol.for("drizzle:Schema"),aY=Symbol.for("drizzle:Columns"),tY=Symbol.for("drizzle:ExtraConfigColumns"),k9=Symbol.for("drizzle:OriginalName"),h9=Symbol.for("drizzle:BaseName"),W6=Symbol.for("drizzle:IsAlias"),eY=Symbol.for("drizzle:ExtraConfigBuilder"),iR=Symbol.for("drizzle:IsDrizzleTable");class F1{static[b]="Table";static Symbol={Name:V0,Schema:v9,OriginalName:k9,Columns:aY,ExtraConfigColumns:tY,BaseName:h9,IsAlias:W6,ExtraConfigBuilder:eY};[V0];[k9];[v9];[aY];[tY];[h9];[W6]=!1;[iR]=!0;[eY]=void 0;constructor($,X,G){this[V0]=this[k9]=$,this[v9]=X,this[h9]=G}}function oR($){return $!==null&&$!==void 0&&typeof $.getSQL==="function"}function nR($){let X={sql:"",params:[]};for(let G of $)if(X.sql+=G.sql,X.params.push(...G.params),G.typings?.length){if(!X.typings)X.typings=[];X.typings.push(...G.typings)}return X}class e1{static[b]="StringChunk";value;constructor($){this.value=Array.isArray($)?$:[$]}getSQL(){return new O1([this])}}class O1{constructor($){this.queryChunks=$;for(let X of $)if(y1(X,F1)){let G=X[F1.Symbol.Schema];this.usedTables.push(G===void 0?X[F1.Symbol.Name]:G+"."+X[F1.Symbol.Name])}}static[b]="SQL";decoder=$q;shouldInlineParams=!1;usedTables=[];append($){return this.queryChunks.push(...$.queryChunks),this}toQuery($){return sY.startActiveSpan("drizzle.buildSQL",(X)=>{let G=this.buildQueryFromSourceParams(this.queryChunks,$);return X?.setAttributes({"drizzle.query.text":G.sql,"drizzle.query.params":JSON.stringify(G.params)}),G})}buildQueryFromSourceParams($,X){let G=Object.assign({},X,{inlineParams:X.inlineParams||this.shouldInlineParams,paramStartIndex:X.paramStartIndex||{value:0}}),{casing:Y,escapeName:q,escapeParam:J,prepareTyping:V,inlineParams:W,paramStartIndex:H}=G;return nR($.map((U)=>{if(y1(U,e1))return{sql:U.value.join(""),params:[]};if(y1(U,Z5))return{sql:q(U.value),params:[]};if(U===void 0)return{sql:"",params:[]};if(Array.isArray(U)){let D=[new e1("(")];for(let[K,O]of U.entries())if(D.push(O),K<U.length-1)D.push(new e1(", "));return D.push(new e1(")")),this.buildQueryFromSourceParams(D,G)}if(y1(U,O1))return this.buildQueryFromSourceParams(U.queryChunks,{...G,inlineParams:W||U.shouldInlineParams});if(y1(U,F1)){let D=U[F1.Symbol.Schema],K=U[F1.Symbol.Name];return{sql:D===void 0||U[W6]?q(K):q(D)+"."+q(K),params:[]}}if(y1(U,s0)){let D=Y.getColumnCasing(U);if(X.invokeSource==="indexes")return{sql:q(D),params:[]};let K=U.table[F1.Symbol.Schema];return{sql:U.table[W6]||K===void 0?q(U.table[F1.Symbol.Name])+"."+q(D):q(K)+"."+q(U.table[F1.Symbol.Name])+"."+q(D),params:[]}}if(y1(U,Gq)){let D=U[F4].schema,K=U[F4].name;return{sql:D===void 0||U[F4].isAlias?q(K):q(D)+"."+q(K),params:[]}}if(y1(U,y9)){if(y1(U.value,w5))return{sql:J(H.value++,U),params:[U],typings:["none"]};let D=U.value===null?null:U.encoder.mapToDriverValue(U.value);if(y1(D,O1))return this.buildQueryFromSourceParams([D],G);if(W)return{sql:this.mapInlineParam(D,G),params:[]};let K=["none"];if(V)K=[V(U.encoder)];return{sql:J(H.value++,D),params:[D],typings:K}}if(y1(U,w5))return{sql:J(H.value++,U),params:[U],typings:["none"]};if(y1(U,O1.Aliased)&&U.fieldAlias!==void 0)return{sql:q(U.fieldAlias),params:[]};if(y1(U,B5)){if(U._.isWith)return{sql:q(U._.alias),params:[]};return this.buildQueryFromSourceParams([new e1("("),U._.sql,new e1(") "),new Z5(U._.alias)],G)}if(oY(U)){if(U.schema)return{sql:q(U.schema)+"."+q(U.enumName),params:[]};return{sql:q(U.enumName),params:[]}}if(oR(U)){if(U.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([U.getSQL()],G);return this.buildQueryFromSourceParams([new e1("("),U.getSQL(),new e1(")")],G)}if(W)return{sql:this.mapInlineParam(U,G),params:[]};return{sql:J(H.value++,U),params:[U],typings:["none"]}}))}mapInlineParam($,{escapeString:X}){if($===null)return"null";if(typeof $==="number"||typeof $==="boolean")return $.toString();if(typeof $==="string")return X($);if(typeof $==="object"){let G=$.toString();if(G==="[object Object]")return X(JSON.stringify($));return X(G)}throw Error("Unexpected param value: "+$)}getSQL(){return this}as($){if($===void 0)return this;return new O1.Aliased(this,$)}mapWith($){return this.decoder=typeof $==="function"?{mapFromDriverValue:$}:$,this}inlineParams(){return this.shouldInlineParams=!0,this}if($){return $?this:void 0}}class Z5{constructor($){this.value=$}static[b]="Name";brand;getSQL(){return new O1([this])}}var $q={mapFromDriverValue:($)=>$},Xq={mapToDriverValue:($)=>$},Sb={...$q,...Xq};class y9{constructor($,X=Xq){this.value=$,this.encoder=X}static[b]="Param";brand;getSQL(){return new O1([this])}}function O4($,...X){let G=[];if(X.length>0||$.length>0&&$[0]!=="")G.push(new e1($[0]));for(let[Y,q]of X.entries())G.push(q,new e1($[Y+1]));return new O1(G)}(($)=>{function X(){return new O1([])}$.empty=X;function G(H){return new O1(H)}$.fromList=G;function Y(H){return new O1([new e1(H)])}$.raw=Y;function q(H,U){let D=[];for(let[K,O]of H.entries()){if(K>0&&U!==void 0)D.push(U);D.push(O)}return new O1(D)}$.join=q;function J(H){return new Z5(H)}$.identifier=J;function V(H){return new w5(H)}$.placeholder=V;function W(H,U){return new y9(H,U)}$.param=W})(O4||(O4={}));(($)=>{class X{constructor(G,Y){this.sql=G,this.fieldAlias=Y}static[b]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new X(this.sql,this.fieldAlias)}}$.Aliased=X})(O1||(O1={}));class w5{constructor($){this.name=$}static[b]="Placeholder";getSQL(){return new O1([this])}}var sR=Symbol.for("drizzle:IsDrizzleView");class Gq{static[b]="View";[F4];[sR]=!0;constructor({name:$,schema:X,selectedFields:G,query:Y}){this[F4]={name:$,originalName:$,schema:X,selectedFields:G,query:Y,isExisting:!Y,isAlias:!1}}getSQL(){return new O1([this])}}s0.prototype.getSQL=function(){return new O1([this])};F1.prototype.getSQL=function(){return new O1([this])};B5.prototype.getSQL=function(){return new O1([this])};function B0($,X){return{name:typeof $==="string"&&$.length>0?$:"",config:typeof $==="object"?$:X}}var g9=typeof TextDecoder>"u"?null:new TextDecoder;class f9{static[b]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor($,X){if(this.reference=()=>{let{name:G,columns:Y,foreignColumns:q}=$();return{name:G,columns:Y,foreignTable:q[0].table,foreignColumns:q}},X)this._onUpdate=X.onUpdate,this._onDelete=X.onDelete}onUpdate($){return this._onUpdate=$,this}onDelete($){return this._onDelete=$,this}build($){return new Yq($,this)}}class Yq{constructor($,X){this.table=$,this.reference=X.reference,this.onUpdate=X._onUpdate,this.onDelete=X._onDelete}static[b]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:$,columns:X,foreignColumns:G}=this.reference(),Y=X.map((V)=>V.name),q=G.map((V)=>V.name),J=[this.table[V0],...Y,G[0].table[V0],...q];return $??`${J.join("_")}_fk`}}function qq($,X){return`${$[V0]}_${X.join("_")}_unique`}class N1 extends I9{static[b]="SQLiteColumnBuilder";foreignKeyConfigs=[];references($,X={}){return this.foreignKeyConfigs.push({ref:$,actions:X}),this}unique($){return this.config.isUnique=!0,this.config.uniqueName=$,this}generatedAlwaysAs($,X){return this.config.generated={as:$,type:"always",mode:X?.mode??"virtual"},this}buildForeignKeys($,X){return this.foreignKeyConfigs.map(({ref:G,actions:Y})=>{return((q,J)=>{let V=new f9(()=>{let W=q();return{columns:[$],foreignColumns:[W]}});if(J.onUpdate)V.onUpdate(J.onUpdate);if(J.onDelete)V.onDelete(J.onDelete);return V.build(X)})(G,Y)})}}class z1 extends s0{constructor($,X){if(!X.uniqueName)X.uniqueName=qq($,[X.name]);super($,X);this.table=$}static[b]="SQLiteColumn"}class Jq extends N1{static[b]="SQLiteBigIntBuilder";constructor($){super($,"bigint","SQLiteBigInt")}build($){return new Vq($,this.config)}}class Vq extends z1{static[b]="SQLiteBigInt";getSQLType(){return"blob"}mapFromDriverValue($){if(typeof Buffer<"u"&&Buffer.from){let X=Buffer.isBuffer($)?$:$ instanceof ArrayBuffer?Buffer.from($):$.buffer?Buffer.from($.buffer,$.byteOffset,$.byteLength):Buffer.from($);return BigInt(X.toString("utf8"))}return BigInt(g9.decode($))}mapToDriverValue($){return Buffer.from($.toString())}}class Wq extends N1{static[b]="SQLiteBlobJsonBuilder";constructor($){super($,"json","SQLiteBlobJson")}build($){return new Hq($,this.config)}}class Hq extends z1{static[b]="SQLiteBlobJson";getSQLType(){return"blob"}mapFromDriverValue($){if(typeof Buffer<"u"&&Buffer.from){let X=Buffer.isBuffer($)?$:$ instanceof ArrayBuffer?Buffer.from($):$.buffer?Buffer.from($.buffer,$.byteOffset,$.byteLength):Buffer.from($);return JSON.parse(X.toString("utf8"))}return JSON.parse(g9.decode($))}mapToDriverValue($){return Buffer.from(JSON.stringify($))}}class Uq extends N1{static[b]="SQLiteBlobBufferBuilder";constructor($){super($,"buffer","SQLiteBlobBuffer")}build($){return new Dq($,this.config)}}class Dq extends z1{static[b]="SQLiteBlobBuffer";mapFromDriverValue($){if(Buffer.isBuffer($))return $;return Buffer.from($)}getSQLType(){return"blob"}}function Qq($,X){let{name:G,config:Y}=B0($,X);if(Y?.mode==="json")return new Wq(G);if(Y?.mode==="bigint")return new Jq(G);return new Uq(G)}class Kq extends N1{static[b]="SQLiteCustomColumnBuilder";constructor($,X,G){super($,"custom","SQLiteCustomColumn");this.config.fieldConfig=X,this.config.customTypeParams=G}build($){return new Mq($,this.config)}}class Mq extends z1{static[b]="SQLiteCustomColumn";sqlName;mapTo;mapFrom;constructor($,X){super($,X);this.sqlName=X.customTypeParams.dataType(X.fieldConfig),this.mapTo=X.customTypeParams.toDriver,this.mapFrom=X.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue($){return typeof this.mapFrom==="function"?this.mapFrom($):$}mapToDriverValue($){return typeof this.mapTo==="function"?this.mapTo($):$}}function N5($){return(X,G)=>{let{name:Y,config:q}=B0(X,G);return new Kq(Y,q,$)}}class z5 extends N1{static[b]="SQLiteBaseIntegerBuilder";constructor($,X,G){super($,X,G);this.config.autoIncrement=!1}primaryKey($){if($?.autoIncrement)this.config.autoIncrement=!0;return this.config.hasDefault=!0,super.primaryKey()}}class L5 extends z1{static[b]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}}class Fq extends z5{static[b]="SQLiteIntegerBuilder";constructor($){super($,"number","SQLiteInteger")}build($){return new Oq($,this.config)}}class Oq extends L5{static[b]="SQLiteInteger"}class Rq extends z5{static[b]="SQLiteTimestampBuilder";constructor($,X){super($,"date","SQLiteTimestamp");this.config.mode=X}defaultNow(){return this.default(O4`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build($){return new Aq($,this.config)}}class Aq extends L5{static[b]="SQLiteTimestamp";mode=this.config.mode;mapFromDriverValue($){if(this.config.mode==="timestamp")return new Date($*1000);return new Date($)}mapToDriverValue($){let X=$.getTime();if(this.config.mode==="timestamp")return Math.floor(X/1000);return X}}class Bq extends z5{static[b]="SQLiteBooleanBuilder";constructor($,X){super($,"boolean","SQLiteBoolean");this.config.mode=X}build($){return new Zq($,this.config)}}class Zq extends L5{static[b]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue($){return Number($)===1}mapToDriverValue($){return $?1:0}}function g1($,X){let{name:G,config:Y}=B0($,X);if(Y?.mode==="timestamp"||Y?.mode==="timestamp_ms")return new Rq(G,Y.mode);if(Y?.mode==="boolean")return new Bq(G,Y.mode);return new Fq(G)}class wq extends N1{static[b]="SQLiteNumericBuilder";constructor($){super($,"string","SQLiteNumeric")}build($){return new Nq($,this.config)}}class Nq extends z1{static[b]="SQLiteNumeric";mapFromDriverValue($){if(typeof $==="string")return $;return String($)}getSQLType(){return"numeric"}}class zq extends N1{static[b]="SQLiteNumericNumberBuilder";constructor($){super($,"number","SQLiteNumericNumber")}build($){return new Lq($,this.config)}}class Lq extends z1{static[b]="SQLiteNumericNumber";mapFromDriverValue($){if(typeof $==="number")return $;return Number($)}mapToDriverValue=String;getSQLType(){return"numeric"}}class _q extends N1{static[b]="SQLiteNumericBigIntBuilder";constructor($){super($,"bigint","SQLiteNumericBigInt")}build($){return new jq($,this.config)}}class jq extends z1{static[b]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}function Pq($,X){let{name:G,config:Y}=B0($,X),q=Y?.mode;return q==="number"?new zq(G):q==="bigint"?new _q(G):new wq(G)}class Eq extends N1{static[b]="SQLiteRealBuilder";constructor($){super($,"number","SQLiteReal")}build($){return new Cq($,this.config)}}class Cq extends z1{static[b]="SQLiteReal";getSQLType(){return"real"}}function Tq($){return new Eq($??"")}class Sq extends N1{static[b]="SQLiteTextBuilder";constructor($,X){super($,"string","SQLiteText");this.config.enumValues=X.enum,this.config.length=X.length}build($){return new Iq($,this.config)}}class Iq extends z1{static[b]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor($,X){super($,X)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}}class bq extends N1{static[b]="SQLiteTextJsonBuilder";constructor($){super($,"json","SQLiteTextJson")}build($){return new xq($,this.config)}}class xq extends z1{static[b]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue($){return JSON.parse($)}mapToDriverValue($){return JSON.stringify($)}}function i($,X={}){let{name:G,config:Y}=B0($,X);if(Y.mode==="json")return new bq(G);return new Sq(G,Y)}function vq(){return{blob:Qq,customType:N5,integer:g1,numeric:Pq,real:Tq,text:i}}var m9=Symbol.for("drizzle:SQLiteInlineForeignKeys");class H6 extends F1{static[b]="SQLiteTable";static Symbol=Object.assign({},F1.Symbol,{InlineForeignKeys:m9});[F1.Symbol.Columns];[m9]=[];[F1.Symbol.ExtraConfigBuilder]=void 0}function aR($,X,G,Y,q=$){let J=new H6($,Y,q),V=typeof X==="function"?X(vq()):X,W=Object.fromEntries(Object.entries(V).map(([U,D])=>{let K=D;K.setName(U);let O=K.build(J);return J[m9].push(...K.buildForeignKeys(O,J)),[U,O]})),H=Object.assign(J,W);if(H[F1.Symbol.Columns]=W,H[F1.Symbol.ExtraConfigColumns]=W,G)H[H6.Symbol.ExtraConfigBuilder]=G;return H}var Z0=($,X,G)=>{return aR($,X,G)};class kq{constructor($,X){this.name=$,this.unique=X}static[b]="SQLiteIndexBuilderOn";on(...$){return new hq(this.name,$,this.unique)}}class hq{static[b]="SQLiteIndexBuilder";config;constructor($,X,G){this.config={name:$,columns:X,unique:G,where:void 0}}where($){return this.config.where=$,this}build($){return new yq(this.config,$)}}class yq{static[b]="SQLiteIndex";config;constructor($,X){this.config={...$,table:X}}}function W0($){return new kq($,!1)}function _5(...$){if($[0].columns)return new u9($[0].columns,$[0].name);return new u9($)}class u9{static[b]="SQLitePrimaryKeyBuilder";columns;name;constructor($,X){this.columns=$,this.name=X}build($){return new gq($,this.columns,this.name)}}class gq{constructor($,X,G){this.table=$,this.columns=X,this.name=G}static[b]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[H6.Symbol.Name]}_${this.columns.map(($)=>$.name).join("_")}_pk`}}var p9=Z0("job_queue",{id:i("id").primaryKey().$defaultFn(()=>n0()),type:i("type").notNull(),data:i("data").notNull(),result:i("result",{mode:"json"}),source:i("source"),metadata:i("metadata",{mode:"json"}).$type().notNull(),status:i("status",{enum:["pending","processing","completed","failed"]}).notNull().default("pending"),priority:g1("priority").notNull().default(0),retryCount:g1("retryCount").notNull().default(0),maxRetries:g1("maxRetries").notNull().default(3),lastError:i("lastError"),createdAt:g1("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:g1("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:g1("startedAt"),completedAt:g1("completedAt")},($)=>({queueReadyIdx:W0("idx_job_queue_ready").on($.status,$.priority,$.scheduledFor),jobTypeIdx:W0("idx_job_queue_type").on($.type,$.status),jobSourceIdx:W0("idx_job_queue_source").on($.source)}));var fq=Q.enum(["file_operations","content_operations","data_processing","batch_processing"]),mq=Q.object({pluginId:Q.string().optional(),progressToken:Q.union([Q.string(),Q.number()]).optional(),operationType:fq,operationTarget:Q.string().optional(),interfaceType:Q.string().optional(),channelId:Q.string().optional()}),U6=mq.extend({rootJobId:Q.string()}),vx=Q.enum(["none","skip","replace","coalesce"]);var l9=Q.enum(["pending","processing","completed","failed"]),uq=Q.enum(["completed","failed"]);var tR=Q.object({id:Q.string(),type:Q.string(),status:l9,data:Q.unknown(),result:Q.unknown().optional(),lastError:Q.string().optional().nullable(),attempts:Q.number(),maxRetries:Q.number(),priority:Q.number(),createdAt:Q.date(),updatedAt:Q.date(),processedAt:Q.date().optional().nullable(),completedAt:Q.date().optional().nullable(),failedAt:Q.date().optional().nullable()}),eR=Q.object({jobId:Q.string(),type:Q.string(),status:uq,result:Q.unknown().optional(),error:Q.string().optional()}),j5=Q.object({id:Q.string(),type:Q.enum(["job","batch"]),status:l9,message:Q.string().optional(),progress:Q.object({current:Q.number(),total:Q.number(),percentage:Q.number()}).optional(),aggregationKey:Q.string().optional(),batchDetails:Q.object({totalOperations:Q.number(),completedOperations:Q.number(),failedOperations:Q.number(),currentOperation:Q.string().optional(),errors:Q.array(Q.string()).optional()}).optional(),jobDetails:Q.object({jobType:Q.string(),priority:Q.number(),retryCount:Q.number()}).optional(),metadata:U6});import{createClient as mx}from"@libsql/client";var Vv=Q.object({success:Q.literal(!1),error:Q.string().optional()});class R4{logger;schema;jobTypeName;constructor($,X){this.logger=$,this.schema=X.schema,this.jobTypeName=X.jobTypeName}validateAndParse($){if(!this.schema)throw Error(`${this.jobTypeName}: No schema provided. Override validateAndParse() or provide a schema.`);try{let X=this.schema.parse($);return this.logger.debug(`${this.jobTypeName} job data validation successful`,{data:this.summarizeDataForLog(X)}),X}catch(X){return this.logger.warn(`Invalid ${this.jobTypeName} job data`,{data:$,validationError:X instanceof Q.ZodError?X.issues:X}),null}}async onError($,X,G,Y){this.logger.error(`${this.jobTypeName} job error handler triggered`,{jobId:G,errorMessage:$.message,errorStack:$.stack,data:this.summarizeDataForLog(X)})}async reportProgress($,X){await $.report({progress:X.progress,total:X.total??100,message:X.message})}summarizeDataForLog($){return $}}var $A=Q.object({id:Q.string(),type:Q.string(),data:Q.string(),status:Q.enum(["pending","processing","completed","failed"]),source:Q.string().nullable(),priority:Q.number(),retryCount:Q.number(),maxRetries:Q.number(),lastError:Q.string().nullable(),createdAt:Q.number(),scheduledFor:Q.number(),startedAt:Q.number().nullable(),completedAt:Q.number().nullable(),metadata:U6,result:Q.unknown().nullable().optional()});import{createClient as pv}from"@libsql/client";var E5=Z0("entities",{id:i("id").notNull(),entityType:i("entityType").notNull(),content:i("content").notNull(),contentHash:i("contentHash").notNull(),metadata:i("metadata",{mode:"json"}).$type().notNull().default(O4`'{}'`),created:g1("created").notNull().$defaultFn(()=>Date.now()),updated:g1("updated").notNull().$defaultFn(()=>Date.now())},($)=>{return{pk:_5({columns:[$.id,$.entityType]})}});import{createClient as av}from"@libsql/client";var pq=N5({dataType(){return"F32_BLOB(1536)"},toDriver($){return Buffer.from($.buffer)},fromDriver($){return new Float32Array($.buffer,$.byteOffset,$.byteLength/4)}});var C5=Z0("embeddings",{entityId:i("entity_id").notNull(),entityType:i("entity_type").notNull(),embedding:pq("embedding").notNull(),contentHash:i("content_hash").notNull()},($)=>{return{pk:_5({columns:[$.entityId,$.entityType]})}});var Gk=Q.object({id:Q.string().min(1,"Entity ID is required"),entityType:Q.string().min(1,"Entity type is required"),contentHash:Q.string().min(1,"Content hash is required"),operation:Q.enum(["create","update"])});var Vk=Q.object({limit:Q.number().int().positive().optional().default(20),offset:Q.number().int().min(0).optional().default(0),types:Q.array(Q.string()).optional().default([]),excludeTypes:Q.array(Q.string()).optional().default([]),weight:Q.record(Q.string(),Q.number()).optional()});var qA=Q.object({field:Q.string(),direction:Q.enum(["asc","desc"]),nullsFirst:Q.boolean().optional()}),Mk=Q.object({limit:Q.number().int().positive().optional(),offset:Q.number().int().min(0).optional().default(0),sortFields:Q.array(qA).optional(),filter:Q.object({metadata:Q.record(Q.string(),Q.unknown()).optional()}).optional(),publishedOnly:Q.boolean().optional()});var T5=M6(H8(),1);function D6($,X){if(Object.keys(X).length===0)return $;let G=Object.fromEntries(Object.entries(X).filter(([,Y])=>Y!==void 0));return T5.default.stringify($,G)}function d9($){if($ instanceof Date)return $.toISOString();if(Array.isArray($))return $.map(d9);if($!==null&&typeof $==="object"){let X={};for(let[G,Y]of Object.entries($))X[G]=d9(Y);return X}return $}function H0($,X){let{content:G,data:Y}=T5.default($),q=d9(Y);return{content:G.trim(),metadata:X.parse(q)}}function c9($){if(Object.keys($).length===0)return"";let G=T5.default.stringify("",$).match(/^---\n[\s\S]*?\n---/);return G?G[0]:""}var MA={generateBodyTemplate:()=>""};class I0{entityType;schema;frontmatterSchema;isSingleton;hasBody;supportsCoverImage;fmSchema;bodyFormatter;constructor($){if(this.entityType=$.entityType,this.schema=$.schema,this.frontmatterSchema=$.frontmatterSchema,this.fmSchema=$.frontmatterSchema,this.bodyFormatter=$.bodyFormatter??MA,$.isSingleton!==void 0)this.isSingleton=$.isSingleton;if($.hasBody!==void 0)this.hasBody=$.hasBody;if($.supportsCoverImage!==void 0)this.supportsCoverImage=$.supportsCoverImage}toMarkdown($){let X=this.renderBody($),Y={...this.readExistingFrontmatter($.content)},q=Object.keys(this.frontmatterSchema.shape);for(let[J,V]of Object.entries($.metadata))if(q.includes(J))Y[J]=V;return this.buildMarkdown(X,Y)}renderBody($){return this.extractBody($.content)}readExistingFrontmatter($){try{return H0($,Q.record(Q.unknown())).metadata}catch{return{}}}extractMetadata($){return $.metadata}parseFrontMatter($,X){return H0($,X).metadata}getBodyTemplate(){return this.bodyFormatter.generateBodyTemplate()}generateFrontMatter($){let X=$.metadata;return c9(X)}extractBody($){try{return H0($,Q.record(Q.unknown())).content}catch{return $}}parseFrontmatter($){return H0($,this.fmSchema).metadata}buildMarkdown($,X){return D6($,X)}}var P2=Q.object({id:Q.string(),entityType:Q.string(),content:Q.string(),created:Q.string().datetime(),updated:Q.string().datetime(),metadata:Q.record(Q.string(),Q.unknown()),contentHash:Q.string()});class A4{cache=null;cacheParseError=null;logger;entityService;entityType;defaultBody;constructor($,X,G,Y){this.entityService=$,this.logger=X.child(this.constructor.name),this.entityType=G,this.defaultBody=Y}async initialize(){if(await this.load(),!this.cache){this.logger.info(`No ${this.entityType} found, creating default ${this.entityType}`);try{let $=this.createContent(this.defaultBody);await this.entityService.createEntity({id:this.entityType,entityType:this.entityType,content:$,metadata:{}}),await this.load(),this.logger.info(`Default ${this.entityType} created successfully`)}catch($){this.logger.error(`Failed to create default ${this.entityType}`,{error:$})}}}get(){if(this.cache&&!this.cacheParseError)return this.parseBody(this.cache.content);return this.defaultBody}getContent(){if(this.cache)return this.cache.content;return this.createContent(this.defaultBody)}async refreshCache(){await this.load()}async load(){try{let $=await this.entityService.getEntity(this.entityType,this.entityType);if(this.cache=$,this.cacheParseError=null,$)try{this.parseBody($.content),this.logger.debug(`${this.entityType} loaded`)}catch(X){this.cacheParseError=X instanceof Error?X:Error(String(X)),this.logger.error(`Failed to parse ${this.entityType} \u2014 using default. Fix the entity content to clear this error.`,{error:this.cacheParseError.message})}else this.logger.debug(`No ${this.entityType} found in database`)}catch($){this.logger.warn(`Failed to load ${this.entityType}`,{error:$}),this.cache=null,this.cacheParseError=null}}}var lq=Q.object({currentPage:Q.number(),totalPages:Q.number(),totalItems:Q.number(),pageSize:Q.number(),hasNextPage:Q.boolean(),hasPrevPage:Q.boolean()});function r9($,X,G){let Y=Math.max(1,Math.ceil($/G));return{currentPage:X,totalPages:Y,totalItems:$,pageSize:G,hasNextPage:X<Y,hasPrevPage:X>1}}var oh=Q.object({});var o9=Q.object({id:Q.string().optional(),limit:Q.number().optional(),page:Q.number().optional(),pageSize:Q.number().optional(),baseUrl:Q.string().optional()}).passthrough(),n9=Q.object({entityType:Q.string().optional(),query:o9.optional()}).passthrough();class s9{logger;constructor($){this.logger=$}buildDetailResult($,X){throw Error(`${this.id}: buildDetailResult() not implemented. Override this method or override fetch() to handle detail views.`)}parseQuery($){let X=n9.parse($);return{entityType:X.entityType??this.config.entityType,query:X.query??{}}}async fetch($,X,G){let Y=this.parseQuery($),q=G.entityService;if(Y.query.id){let V=await this.fetchDetail(Y.query.id,q);return X.parse(this.buildDetailResult(V.item,V.navigation))}let J=await this.fetchList(Y.query,q);return X.parse(this.buildListResult(J.items,J.pagination,Y.query))}async fetchDetail($,X){let G=await this.lookupEntity($,X),Y=this.transformEntity(G),q=null;if(this.config.enableNavigation)q=await this.resolveNavigation(G,X);return{item:Y,navigation:q}}async fetchList($,X,G){let Y=$.page??1,q=$.pageSize??$.limit??this.config.defaultLimit??100,J=(Y-1)*q,V=$.page!==void 0,[W,H]=await Promise.all([X.listEntities(this.config.entityType,{limit:q,offset:J,sortFields:this.config.defaultSort,...G}),V?X.countEntities(this.config.entityType,G?.filter?{filter:G.filter}:void 0):Promise.resolve(0)]),U=W.map((K)=>this.transformEntity(K)),D=V?r9(H,Y,q):null;return{items:U,pagination:D}}async resolveNavigation($,X,G){let Y=this.config.navigationLimit??1000,q=await X.listEntities(this.config.entityType,{limit:Y,sortFields:G??this.config.defaultSort}),J=q.findIndex((D)=>D.id===$.id),V=J>0?q[J-1]:void 0,W=J<q.length-1?q[J+1]:void 0,H=V?this.transformEntity(V):null,U=W?this.transformEntity(W):null;return{prev:H,next:U}}async lookupEntity($,X){if(this.config.lookupField==="id"){let q=await X.getEntity(this.config.entityType,$);if(!q)throw Error(`${this.config.entityType} not found: ${$}`);return q}let Y=(await X.listEntities(this.config.entityType,{filter:{metadata:{slug:$}},limit:1}))[0];if(!Y)throw Error(`${this.config.entityType} not found with slug: ${$}`);return Y}}class t9 extends R4{context;entityType;constructor($,X,G){super($,{schema:G.schema,jobTypeName:G.jobTypeName});this.context=X,this.entityType=G.entityType}async afterCreate($,X,G,Y){}async onGenerationFailure($,X){}async process($,X,G){try{await this.reportProgress(G,{progress:q6.START,message:`Starting ${this.jobTypeName}`});let Y=await this.generate($,G);await this.reportProgress(G,{progress:q6.SAVE,message:`Saving ${this.entityType} to database`});let q=await this.context.entityService.createEntity({id:Y.id,entityType:this.entityType,content:Y.content,metadata:Y.metadata},Y.createOptions);return await this.afterCreate($,q.entityId,G,Y),await this.reportProgress(G,{progress:q6.COMPLETE,message:`${Y.title??this.entityType} created successfully`}),{success:!0,entityId:q.entityId,...Y.resultExtras}}catch(Y){if(Y instanceof a9)return await this.onGenerationFailure($,Y.message),{success:!1,error:Y.message};let q=h1(Y);return this.logger.error(`${this.jobTypeName} job failed`,{error:Y,jobId:X,data:this.summarizeDataForLog($)}),await this.onGenerationFailure($,q),C9.failure(Y)}}failEarly($){throw new a9($)}}class a9 extends Error{constructor($){super($);this.name="GenerationFailure"}}import{createClient as Qy}from"@libsql/client";var S5=Z0("conversations",{id:i("id").primaryKey(),sessionId:i("session_id").notNull(),interfaceType:i("interface_type").notNull(),channelId:i("channel_id").notNull(),started:i("started").notNull(),lastActive:i("last_active").notNull(),metadata:i("metadata"),created:i("created").notNull(),updated:i("updated").notNull()},($)=>({sessionIdx:W0("idx_conversations_session").on($.sessionId),channelIdx:W0("idx_conversations_channel").on($.channelId),interfaceSessionIdx:W0("idx_conversations_interface_session").on($.interfaceType,$.sessionId),interfaceChannelIdx:W0("idx_conversations_interface_channel").on($.interfaceType,$.channelId)})),rq=Z0("messages",{id:i("id").primaryKey(),conversationId:i("conversation_id").notNull().references(()=>S5.id,{onDelete:"cascade"}),role:i("role").notNull(),content:i("content").notNull(),timestamp:i("timestamp").notNull(),metadata:i("metadata")},($)=>({conversationIdx:W0("idx_messages_conversation").on($.conversationId),timestampIdx:W0("idx_messages_timestamp").on($.timestamp)})),iq=Z0("summary_tracking",{conversationId:i("conversation_id").primaryKey().references(()=>S5.id,{onDelete:"cascade"}),lastSummarizedAt:i("last_summarized_at"),lastMessageId:i("last_message_id"),messagesSinceSummary:g1("messages_since_summary").default(0),updated:i("updated").notNull()});var BA=Q.object({id:Q.string(),conversationId:Q.string(),role:Q.string(),content:Q.string(),timestamp:Q.string(),metadata:Q.string().nullable()}),oq=Q.object({conversationId:Q.string(),messageCount:Q.number(),messages:Q.array(BA),windowStart:Q.number(),windowEnd:Q.number(),windowSize:Q.number(),timestamp:Q.string()});var nq=Q.object({captureUrls:Q.boolean().default(!1),blockedUrlDomains:Q.array(Q.string()).default(["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"])});async function sq($){let{entityType:X,title:G,deriveId:Y,regeneratePrompt:q,context:J}=$,V=Y(G);if(!await J.entityService.getEntity(X,V))return G;J.logger.debug(`Entity ID collision: ${X}/${V}, asking AI for a new title`);let H=Q.object({title:Q.string().max(80).describe("A short, unique title (2-6 words)")}),{object:U}=await J.ai.generateObject(`The title "${G}" is already taken. ${q}`,H),D=U.title;return J.logger.debug(`AI suggested new title: "${D}"`),D}var PA=Q.object({id:Q.string(),template:Q.string(),content:Q.unknown().optional(),dataQuery:Q.object({entityType:Q.string().optional(),template:Q.string().optional(),query:Q.object({id:Q.string().optional(),limit:Q.number().optional(),offset:Q.number().optional()}).passthrough().optional()}).passthrough().optional(),order:Q.number().optional()}),aq=["primary","secondary"],EA=Q.object({show:Q.boolean().default(!1),label:Q.string().optional(),slot:Q.enum(aq).default("primary"),priority:Q.number().min(0).max(100).default(50)}).optional(),tq=Q.object({id:Q.string(),path:Q.string(),title:Q.string().default(""),description:Q.string().default(""),sections:Q.array(PA).default([]),layout:Q.string().default("default"),fullscreen:Q.boolean().optional(),pluginId:Q.string().optional(),sourceEntityType:Q.string().optional(),external:Q.boolean().optional(),navigation:EA}),CA=Q.object({routes:Q.array(tq),pluginId:Q.string()}),TA=Q.object({paths:Q.array(Q.string()).optional(),pluginId:Q.string().optional()}),SA=Q.object({pluginId:Q.string().optional()}),IA=Q.object({path:Q.string()});var bA=Q.object({enabled:Q.boolean().describe("Whether the plugin is enabled"),debug:Q.boolean().describe("Enable debug logging for this plugin")});var e9=P2.extend({id:Q.literal("brain-character"),entityType:Q.literal("brain-character")}),I5=Q.object({name:Q.string().describe("The brain's friendly display name"),role:Q.string().describe("The brain's primary role"),purpose:Q.string().describe("The brain's purpose and goals"),values:Q.array(Q.string()).describe("Core values that guide behavior")});class b5 extends I0{constructor(){super({entityType:"brain-character",schema:e9,frontmatterSchema:I5,isSingleton:!0,hasBody:!1})}createCharacterContent($){return this.buildMarkdown("",$)}parseCharacterBody($){return this.parseFrontmatter($)}toMarkdown($){let X=this.parseFrontmatter($.content);return this.buildMarkdown("",X)}fromMarkdown($){return{content:$,entityType:"brain-character"}}extractMetadata($){let X=this.parseFrontmatter($.content);return{role:X.role,values:X.values}}generateFrontMatter($){let X=this.parseFrontmatter($.content);return this.buildMarkdown("",X)}}class a0 extends A4{static instance=null;adapter=new b5;static getDefaultCharacter(){return{name:"Brain",role:"Knowledge assistant",purpose:"Help organize, understand, and retrieve information from your knowledge base",values:["clarity","accuracy","helpfulness"]}}static getInstance($,X,G){return a0.instance??=new a0($,X,G),a0.instance}static resetInstance(){a0.instance=null}static createFresh($,X,G){return new a0($,X,G)}constructor($,X,G){super($,X,"brain-character",G??a0.getDefaultCharacter())}parseBody($){return this.adapter.parseCharacterBody($)}createContent($){return this.adapter.createCharacterContent($)}getCharacter(){return this.get()}getCharacterContent(){return this.getContent()}}var eq=Q.object({tagline:Q.string().optional().describe("Short, punchy one-liner for homepage"),intro:Q.string().optional().describe("Optional longer introduction for homepage"),story:Q.string().optional().describe("Extended bio/narrative (multi-paragraph markdown)")});var $7=P2.extend({id:Q.literal("anchor-profile"),entityType:Q.literal("anchor-profile")}),B4=Q.object({name:Q.string().describe("Name (person or organization)"),kind:Q.enum(["professional","team","collective"]).describe("Type of anchor: professional (individual), team, or collective"),organization:Q.string().optional().describe("Organization the anchor belongs to"),description:Q.string().optional().describe("Short description or biography"),avatar:Q.string().optional().describe("URL or asset path to avatar/logo"),website:Q.string().optional().describe("Primary website URL"),email:Q.string().optional().describe("Contact email"),socialLinks:Q.array(Q.object({platform:Q.enum(["github","instagram","linkedin","email","website"]).describe("Social media platform"),url:Q.string().describe("Profile or contact URL"),label:Q.string().optional().describe("Optional display label")})).optional().describe("Social media and contact links")});class x5 extends I0{constructor(){super({entityType:"anchor-profile",schema:$7,frontmatterSchema:B4,isSingleton:!0,hasBody:!0})}createProfileContent($){let X=B4.parse($);return this.buildMarkdown("",X)}parseProfileBody($,X){if(X){let{metadata:G,content:Y}=H0($,X);return Y?{...G,story:Y}:G}return this.parseFrontmatter($)}fromMarkdown($){return{content:$,entityType:"anchor-profile"}}extractMetadata($){let X=this.parseFrontmatter($.content);return{name:X.name,email:X.email,website:X.website}}generateFrontMatter($){let X=this.parseFrontmatter($.content);return this.buildMarkdown("",X)}}class b0 extends A4{static instance=null;adapter=new x5;static getDefaultProfile(){return{name:"Unknown",kind:"professional"}}static getInstance($,X,G){return b0.instance??=new b0($,X,G),b0.instance}static resetInstance(){b0.instance=null}static createFresh($,X,G){return new b0($,X,G)}constructor($,X,G){super($,X,"anchor-profile",G??b0.getDefaultProfile())}parseBody($){return this.adapter.parseProfileBody($)}createContent($){return this.adapter.createProfileContent($)}getProfile(){return this.get()}getProfileContent(){return this.getContent()}}var $J=Q.object({id:Q.string(),description:Q.string(),name:Q.string().optional(),tags:Q.array(Q.string()).optional().default([])}).passthrough();var vA=Q.object({uri:Q.string(),params:Q.record(Q.unknown()).optional()}).passthrough(),kA=Q.object({name:Q.string(),url:Q.string(),description:Q.string().optional(),skills:Q.array($J).optional().default([]),capabilities:Q.object({extensions:Q.array(vA).optional().default([])}).passthrough().optional()}).passthrough();var hA=Q.object({name:Q.string(),description:Q.string(),tags:Q.array(Q.string()),examples:Q.array(Q.string())});import{EventEmitter as XJ}from"events";class U0 extends Error{pluginId;constructor($,X){super(`Plugin ${$}: ${X}`);this.name="PluginError",this.pluginId=$}}class X7{plugins;events;daemonRegistry;logger;constructor($,X,G,Y){this.plugins=$;this.events=X;this.daemonRegistry=G;this.logger=Y.child("PluginLifecycle")}async initializePlugin($,X,G){let Y=this.plugins.get($);if(!Y)throw new U0($,"Registration failed: Plugin is not registered");let q=Y.plugin;this.logger.debug(`Initializing plugin: ${$}`),this.events.emit("plugin:before_initialize",$,q);try{let J=await q.register(X,G);return Y.status="initialized",this.logger.debug(`Initialized plugin: ${$}`),this.events.emit("plugin:initialized",$,q),J}catch(J){let V=h1(J);throw this.logger.error(`Error initializing plugin ${$}: ${V}`),Y.status="error",Y.error=J6(J),this.events.emit("plugin:error",$,J),J}}async readyPlugin($){let X=this.plugins.get($);if(!X)throw new U0($,"Ready failed: Plugin is not registered");if(X.status!=="initialized"){this.logger.debug(`Skipping ready hook for non-initialized plugin: ${$}`);return}try{await X.plugin.ready?.(),this.logger.debug(`Ready hook completed for plugin: ${$}`)}catch(G){let Y=J6(G);throw X.status="error",X.error=Y,this.events.emit("plugin:error",$,Y),Y}}async startPluginDaemons($){let X=this.plugins.get($);if(X?.status!=="initialized")return;try{await this.daemonRegistry.startPlugin($),this.logger.debug(`Started daemons for plugin: ${$}`)}catch(G){if(X.plugin.requiresDaemonStartup?.())throw G;this.logger.warn(`Daemon ${$} failed to start: ${h1(G)}`)}}async disablePlugin($){let X=this.plugins.get($);if(!X){this.logger.warn(`Cannot disable plugin ${$}: not registered`);return}this.logger.debug(`Disabling plugin: ${$}`);try{await this.daemonRegistry.stopPlugin($),this.logger.debug(`Stopped daemons for plugin: ${$}`)}catch(G){this.logger.error(`Failed to stop daemons for plugin: ${$}`,G)}if(X.plugin.shutdown)try{await X.plugin.shutdown(),this.logger.debug(`Shutdown completed for plugin: ${$}`)}catch(G){this.logger.error(`Plugin shutdown failed for ${$}:`,G)}X.status="disabled",this.events.emit("plugin:disabled",$,X.plugin),this.logger.debug(`Disabled plugin: ${$}`)}async enablePlugin($){let X=this.plugins.get($);if(!X){this.logger.warn(`Cannot enable plugin ${$}: not registered`);return}if(X.status!=="disabled"){this.logger.warn(`Cannot enable plugin ${$}: not disabled`);return}this.logger.debug(`Enabling plugin: ${$}`),X.status="initialized";try{await this.daemonRegistry.startPlugin($),this.logger.debug(`Started daemons for plugin: ${$}`)}catch(G){this.logger.error(`Failed to start daemons for plugin: ${$}`,G)}this.events.emit("plugin:enabled",$,X.plugin),this.logger.debug(`Enabled plugin: ${$}`)}}class G7{plugins;events;logger;constructor($,X,G){this.plugins=$;this.events=X;this.logger=G.child("DependencyResolver")}async resolveInitializationOrder($){this.logger.debug("Resolving plugin initialization order...");let X=Array.from(this.plugins.keys()),G=new Set,Y=!0;while(Y&&G.size<X.length){Y=!1;for(let V of X){if(G.has(V))continue;if(!this.plugins.get(V))continue;if(this.getUnmetDependencies(V).length===0)try{await $(V),G.add(V),Y=!0}catch(U){let D=h1(U);this.logger.error(`Failed to initialize plugin ${V}: ${D}`),G.add(V),Y=!0}}}let q=X.filter((V)=>!G.has(V));if(q.length>0){let V=q.join(", ");this.logger.error(`Failed to initialize plugins due to dependency issues: ${V}`);for(let W of q){let H=this.getUnmetDependencies(W);this.logger.error(`Plugin ${W} has unmet dependencies: ${H.join(", ")}`);let U=this.plugins.get(W);if(U)U.status="error",U.error=new U0(W,`Unmet dependencies: ${H.join(", ")}`);this.events.emit("plugin:error",W,U?.error)}}let J=new Set;for(let[V,W]of this.plugins)if(W.status==="initialized")J.add(V);return this.logger.debug(`Resolved ${J.size} of ${X.length} plugins`),{initialized:J,failed:q}}getUnmetDependencies($){let X=this.plugins.get($);if(!X)return[];let{dependencies:G}=X,Y=[];for(let q of G){let J=this.plugins.get(q);if(!J){Y.push(q);continue}if(J.status!=="initialized")Y.push(q)}return Y}}class Y7{logger;constructor($){this.logger=$.child("CapabilityRegistrar")}async registerCapabilities($,X,G){if(G.tools.length>0)$.registerTools(X,G.tools),this.logger.debug(`Registered ${G.tools.length} tools from ${X}`);if(G.resources.length>0)$.registerResources(X,G.resources),this.logger.debug(`Registered ${G.resources.length} resources from ${X}`);if(G.instructions)$.registerInstructions(X,G.instructions),this.logger.debug(`Registered instructions from ${X}`)}}class t0{static instance=null;plugins=new Map;logger;events=new XJ;daemonRegistry;shell=null;initializedPluginIds=[];pluginLifecycle;dependencyResolver;capabilityRegistrar;static getInstance($,X){return t0.instance??=new t0($,X),t0.instance}static resetInstance(){t0.instance=null}static createFresh($,X){return new t0($,X)}setShell($){this.shell=$}constructor($,X){this.logger=$.child("PluginManager"),this.events=new XJ,this.daemonRegistry=X,this.pluginLifecycle=new X7(this.plugins,this.events,this.daemonRegistry,$),this.dependencyResolver=new G7(this.plugins,this.events,$),this.capabilityRegistrar=new Y7($)}registerPlugin($){if(!$.id)throw new U0("unknown","Registration failed: Plugin must have an id");if(this.logger.debug(`Registering plugin: ${$.id} (${$.version})`),this.plugins.has($.id)){let q=this.plugins.get($.id)?.plugin.version;throw new U0($.id,`Registration failed: Plugin is already registered with version ${q}`)}let X=$.dependencies??[],G={plugin:$,status:"registered",dependencies:X};this.plugins.set($.id,G),this.logger.debug(`Registered plugin: ${$.id} (${$.version})`),this.events.emit("plugin:registered",$.id,$)}async initializePlugins($){this.logger.debug("Initializing plugins..."),this.initializedPluginIds=[];let X=await this.dependencyResolver.resolveInitializationOrder(async(G)=>{await this.initializePlugin(G,$)});this.logger.debug(`Initialized ${X.initialized.size} of ${this.plugins.size} plugins`)}async initializePlugin($,X){if(!this.shell)throw new U0($,"Cannot initialize plugin: Shell not set. Call setShell() first.");let G=this.shell,Y=await this.pluginLifecycle.initializePlugin($,G,X);await this.capabilityRegistrar.registerCapabilities(G,$,Y),this.initializedPluginIds.push($)}async readyPlugins(){this.logger.debug("Dispatching plugin ready hooks..."),await Promise.all(this.initializedPluginIds.map(($)=>this.pluginLifecycle.readyPlugin($)))}async startPluginDaemons(){this.logger.debug("Starting plugin daemons..."),await Promise.all(this.initializedPluginIds.map(($)=>this.pluginLifecycle.startPluginDaemons($)))}getPlugin($){return this.plugins.get($)?.plugin}getPluginStatus($){return this.plugins.get($)?.status}hasPlugin($){return this.plugins.has($)}isPluginInitialized($){return this.plugins.get($)?.status==="initialized"}getAllPluginIds(){return Array.from(this.plugins.keys())}getAllPlugins(){return new Map(this.plugins)}getFailedPlugins(){return Array.from(this.plugins.entries()).filter(($)=>$[1].status==="error"&&$[1].error!==void 0).map(([$,X])=>({id:$,error:X.error}))}getPluginPackageName($){return this.plugins.get($)?.plugin.packageName}async disablePlugin($){await this.pluginLifecycle.disablePlugin($)}async enablePlugin($){await this.pluginLifecycle.enablePlugin($)}on($,X){this.events.on($,X)}once($,X){this.events.once($,X)}off($,X){this.events.off($,X)}getEventEmitter(){return this.events}}export{sq as ensureUniqueTitle,o9 as baseQuerySchema,n9 as baseInputSchema,j5 as JobProgressEventSchema,R4 as BaseJobHandler,t9 as BaseGenerationJobHandler,s9 as BaseEntityDataSource};
169
+ `)}}var hC=Q.object({slug:Q.string(),title:Q.string(),type:Q.string(),entityId:Q.string(),contentHash:Q.string()});import{webcrypto as vY}from"crypto";var xY="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var jR=128,j2,M4;function PR($){if(!j2||j2.length<$)j2=Buffer.allocUnsafe($*jR),vY.getRandomValues(j2),M4=0;else if(M4+$>j2.length)vY.getRandomValues(j2),M4=0;M4+=$}function kY($=21){PR($|=0);let X="";for(let G=M4-$;G<M4;G++)X+=xY[j2[G]&63];return X}function n0($=12){return kY($)}var q6={START:0,INIT:10,FETCH:20,PROCESS:40,GENERATE:50,EXTRACT:60,SAVE:80,COMPLETE:100};function h1($){return $ instanceof Error?$.message:String($)}function J6($){return $ instanceof Error?$:Error(String($))}var C9={success($){return{success:!0,...$}},failure($){return{success:!1,error:h1($)}}};var CR=Q.object({success:Q.boolean(),entityId:Q.string().optional(),error:Q.string().optional()});var IR=Q.object({status:Q.enum(["healthy","warning","error","unknown"]),message:Q.string().optional(),lastCheck:Q.date().optional(),details:Q.record(Q.string(),Q.unknown()).optional()}),yY=Q.object({name:Q.string(),pluginId:Q.string(),status:Q.string(),health:IR.optional()});import{McpServer as MI}from"@modelcontextprotocol/sdk/server/mcp.js";var T9=Q.enum(["anchor","trusted","public"]);var bR=Q.object({name:Q.string(),description:Q.string(),schema:Q.any(),basePrompt:Q.string().optional(),useKnowledgeContext:Q.boolean().optional(),requiredPermission:T9,formatter:Q.any().optional(),layout:Q.object({component:Q.any(),fullscreen:Q.boolean().optional()}).optional(),dataSourceId:Q.string().optional()});var xR=Q.enum(["site-content-preview","site-content-production"]),vR=Q.object({name:Q.string(),schema:Q.any(),description:Q.string().optional(),pluginId:Q.string(),renderers:Q.object({web:Q.union([Q.function(),Q.string()]).optional()})}),kR=Q.object({enableContentGeneration:Q.boolean().default(!1),outputDir:Q.string(),workingDir:Q.string().optional(),environment:Q.enum(["preview","production"]).default("preview"),siteConfig:Q.object({title:Q.string(),description:Q.string(),url:Q.string().optional()}).optional()}),hR=Q.object({success:Q.boolean(),routesBuilt:Q.number(),errors:Q.array(Q.string()).optional(),warnings:Q.array(Q.string()).optional()});import{ResourceTemplate as RI}from"@modelcontextprotocol/sdk/server/mcp.js";var A5=Q.object({interfaceType:Q.string(),userId:Q.string(),channelId:Q.string().optional(),channelName:Q.string().optional()}),mY=Q.object({success:Q.literal(!0),data:Q.unknown(),message:Q.string().optional()}),uY=Q.object({success:Q.literal(!1),error:Q.string(),code:Q.string().optional()}),pY=Q.object({needsConfirmation:Q.literal(!0),toolName:Q.string(),description:Q.string(),args:Q.unknown()}),S9=Q.union([mY,uY,pY]);var lY=Q.union([Q.object({success:Q.literal(!0),data:Q.unknown(),message:Q.string().optional()}),Q.object({success:Q.literal(!1),error:Q.string(),code:Q.string().optional()})]);var kI=Q.object({id:Q.string(),type:Q.string(),version:Q.string(),status:Q.string()}),hI=Q.object({name:Q.string(),description:Q.string()}),dY=Q.object({label:Q.string(),url:Q.string(),pluginId:Q.string(),priority:Q.number().default(100)}),pR=Q.object({model:Q.string(),version:Q.string(),uptime:Q.number(),entities:Q.number(),embeddings:Q.number(),ai:Q.object({model:Q.string(),embeddingModel:Q.string()}),daemons:Q.array(yY),endpoints:Q.array(dY)}),yI=Q.object({pluginId:Q.string(),tool:Q.object({name:Q.string(),description:Q.string(),inputSchema:Q.record(Q.string(),Q.unknown()),handler:Q.function(),visibility:Q.enum(["public","trusted","anchor"]).optional()}),timestamp:Q.number()}),gI=Q.object({pluginId:Q.string(),resource:Q.object({uri:Q.string(),name:Q.string(),description:Q.string().optional(),mimeType:Q.string().optional(),handler:Q.function()}),timestamp:Q.number()});var lR=Q.object({id:Q.string(),version:Q.string(),type:Q.enum(["core","entity","service","interface"]),description:Q.string().optional(),dependencies:Q.array(Q.string()).optional(),packageName:Q.string()});var dI=Q.object({toolName:Q.string(),args:Q.unknown(),progressToken:Q.union([Q.string(),Q.number()]).optional(),hasProgress:Q.boolean().optional(),...A5.shape}),cI=Q.object({resourceUri:Q.string()});var oI=Q.object({name:Q.string(),schema:Q.custom(($)=>$ instanceof Q.ZodType)});var b=Symbol.for("drizzle:entityKind");function y1($,X){if(!$||typeof $!=="object")return!1;if($ instanceof X)return!0;if(!Object.prototype.hasOwnProperty.call(X,b))throw Error(`Class "${X.name??"<unknown>"}" doesn't look like a Drizzle entity. If this is incorrect and the class is provided by Drizzle, please report this as a bug.`);let G=Object.getPrototypeOf($).constructor;if(G)while(G){if(b in G&&G[b]===X[b])return!0;G=Object.getPrototypeOf(G)}return!1}class s0{constructor($,X){this.table=$,this.config=X,this.name=X.name,this.keyAsName=X.keyAsName,this.notNull=X.notNull,this.default=X.default,this.defaultFn=X.defaultFn,this.onUpdateFn=X.onUpdateFn,this.hasDefault=X.hasDefault,this.primary=X.primaryKey,this.isUnique=X.isUnique,this.uniqueName=X.uniqueName,this.uniqueType=X.uniqueType,this.dataType=X.dataType,this.columnType=X.columnType,this.generated=X.generated,this.generatedIdentity=X.generatedIdentity}static[b]="Column";name;keyAsName;primary;notNull;default;defaultFn;onUpdateFn;hasDefault;isUnique;uniqueName;uniqueType;dataType;columnType;enumValues=void 0;generated=void 0;generatedIdentity=void 0;config;mapFromDriverValue($){return $}mapToDriverValue($){return $}shouldDisableInsert(){return this.config.generated!==void 0&&this.config.generated.type!=="byDefault"}}class I9{static[b]="ColumnBuilder";config;constructor($,X,G){this.config={name:$,keyAsName:$==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:X,columnType:G,generated:void 0}}$type(){return this}notNull(){return this.config.notNull=!0,this}default($){return this.config.default=$,this.config.hasDefault=!0,this}$defaultFn($){return this.config.defaultFn=$,this.config.hasDefault=!0,this}$default=this.$defaultFn;$onUpdateFn($){return this.config.onUpdateFn=$,this.config.hasDefault=!0,this}$onUpdate=this.$onUpdateFn;primaryKey(){return this.config.primaryKey=!0,this.config.notNull=!0,this}setName($){if(this.config.name!=="")return;this.config.name=$}}var V0=Symbol.for("drizzle:Name");function cY($,...X){return $(...X)}function rY($,X){return`${$[V0]}_${X.join("_")}_unique`}class V6 extends s0{constructor($,X){if(!X.uniqueName)X.uniqueName=rY($,[X.name]);super($,X);this.table=$}static[b]="PgColumn"}class dR extends V6{static[b]="ExtraConfigColumn";getSQLType(){return this.getSQLType()}indexConfig={order:this.config.order??"asc",nulls:this.config.nulls??"last",opClass:this.config.opClass};defaultConfig={order:"asc",nulls:"last",opClass:void 0};asc(){return this.indexConfig.order="asc",this}desc(){return this.indexConfig.order="desc",this}nullsFirst(){return this.indexConfig.nulls="first",this}nullsLast(){return this.indexConfig.nulls="last",this}op($){return this.indexConfig.opClass=$,this}}class cR extends V6{static[b]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor($,X){super($,X);this.enum=X.enum}getSQLType(){return this.enum.enumName}}var iY=Symbol.for("drizzle:isPgEnum");function oY($){return!!$&&typeof $==="function"&&iY in $&&$[iY]===!0}class rR extends V6{static[b]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor($,X){super($,X);this.enum=X.enum}getSQLType(){return this.enum.enumName}}class B5{static[b]="Subquery";constructor($,X,G,Y=!1,q=[]){this._={brand:"Subquery",sql:$,selectedFields:X,alias:G,isWith:Y,usedTables:q}}}var nY="0.44.7";var b9,x9,sY={startActiveSpan($,X){if(!b9)return X();if(!x9)x9=b9.trace.getTracer("drizzle-orm",nY);return cY((G,Y)=>Y.startActiveSpan($,(q)=>{try{return X(q)}catch(J){throw q.setStatus({code:G.SpanStatusCode.ERROR,message:J instanceof Error?J.message:"Unknown error"}),J}finally{q.end()}}),b9,x9)}};var F4=Symbol.for("drizzle:ViewBaseConfig");var v9=Symbol.for("drizzle:Schema"),aY=Symbol.for("drizzle:Columns"),tY=Symbol.for("drizzle:ExtraConfigColumns"),k9=Symbol.for("drizzle:OriginalName"),h9=Symbol.for("drizzle:BaseName"),W6=Symbol.for("drizzle:IsAlias"),eY=Symbol.for("drizzle:ExtraConfigBuilder"),iR=Symbol.for("drizzle:IsDrizzleTable");class F1{static[b]="Table";static Symbol={Name:V0,Schema:v9,OriginalName:k9,Columns:aY,ExtraConfigColumns:tY,BaseName:h9,IsAlias:W6,ExtraConfigBuilder:eY};[V0];[k9];[v9];[aY];[tY];[h9];[W6]=!1;[iR]=!0;[eY]=void 0;constructor($,X,G){this[V0]=this[k9]=$,this[v9]=X,this[h9]=G}}function oR($){return $!==null&&$!==void 0&&typeof $.getSQL==="function"}function nR($){let X={sql:"",params:[]};for(let G of $)if(X.sql+=G.sql,X.params.push(...G.params),G.typings?.length){if(!X.typings)X.typings=[];X.typings.push(...G.typings)}return X}class e1{static[b]="StringChunk";value;constructor($){this.value=Array.isArray($)?$:[$]}getSQL(){return new O1([this])}}class O1{constructor($){this.queryChunks=$;for(let X of $)if(y1(X,F1)){let G=X[F1.Symbol.Schema];this.usedTables.push(G===void 0?X[F1.Symbol.Name]:G+"."+X[F1.Symbol.Name])}}static[b]="SQL";decoder=$q;shouldInlineParams=!1;usedTables=[];append($){return this.queryChunks.push(...$.queryChunks),this}toQuery($){return sY.startActiveSpan("drizzle.buildSQL",(X)=>{let G=this.buildQueryFromSourceParams(this.queryChunks,$);return X?.setAttributes({"drizzle.query.text":G.sql,"drizzle.query.params":JSON.stringify(G.params)}),G})}buildQueryFromSourceParams($,X){let G=Object.assign({},X,{inlineParams:X.inlineParams||this.shouldInlineParams,paramStartIndex:X.paramStartIndex||{value:0}}),{casing:Y,escapeName:q,escapeParam:J,prepareTyping:V,inlineParams:W,paramStartIndex:H}=G;return nR($.map((U)=>{if(y1(U,e1))return{sql:U.value.join(""),params:[]};if(y1(U,Z5))return{sql:q(U.value),params:[]};if(U===void 0)return{sql:"",params:[]};if(Array.isArray(U)){let D=[new e1("(")];for(let[K,O]of U.entries())if(D.push(O),K<U.length-1)D.push(new e1(", "));return D.push(new e1(")")),this.buildQueryFromSourceParams(D,G)}if(y1(U,O1))return this.buildQueryFromSourceParams(U.queryChunks,{...G,inlineParams:W||U.shouldInlineParams});if(y1(U,F1)){let D=U[F1.Symbol.Schema],K=U[F1.Symbol.Name];return{sql:D===void 0||U[W6]?q(K):q(D)+"."+q(K),params:[]}}if(y1(U,s0)){let D=Y.getColumnCasing(U);if(X.invokeSource==="indexes")return{sql:q(D),params:[]};let K=U.table[F1.Symbol.Schema];return{sql:U.table[W6]||K===void 0?q(U.table[F1.Symbol.Name])+"."+q(D):q(K)+"."+q(U.table[F1.Symbol.Name])+"."+q(D),params:[]}}if(y1(U,Gq)){let D=U[F4].schema,K=U[F4].name;return{sql:D===void 0||U[F4].isAlias?q(K):q(D)+"."+q(K),params:[]}}if(y1(U,y9)){if(y1(U.value,w5))return{sql:J(H.value++,U),params:[U],typings:["none"]};let D=U.value===null?null:U.encoder.mapToDriverValue(U.value);if(y1(D,O1))return this.buildQueryFromSourceParams([D],G);if(W)return{sql:this.mapInlineParam(D,G),params:[]};let K=["none"];if(V)K=[V(U.encoder)];return{sql:J(H.value++,D),params:[D],typings:K}}if(y1(U,w5))return{sql:J(H.value++,U),params:[U],typings:["none"]};if(y1(U,O1.Aliased)&&U.fieldAlias!==void 0)return{sql:q(U.fieldAlias),params:[]};if(y1(U,B5)){if(U._.isWith)return{sql:q(U._.alias),params:[]};return this.buildQueryFromSourceParams([new e1("("),U._.sql,new e1(") "),new Z5(U._.alias)],G)}if(oY(U)){if(U.schema)return{sql:q(U.schema)+"."+q(U.enumName),params:[]};return{sql:q(U.enumName),params:[]}}if(oR(U)){if(U.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([U.getSQL()],G);return this.buildQueryFromSourceParams([new e1("("),U.getSQL(),new e1(")")],G)}if(W)return{sql:this.mapInlineParam(U,G),params:[]};return{sql:J(H.value++,U),params:[U],typings:["none"]}}))}mapInlineParam($,{escapeString:X}){if($===null)return"null";if(typeof $==="number"||typeof $==="boolean")return $.toString();if(typeof $==="string")return X($);if(typeof $==="object"){let G=$.toString();if(G==="[object Object]")return X(JSON.stringify($));return X(G)}throw Error("Unexpected param value: "+$)}getSQL(){return this}as($){if($===void 0)return this;return new O1.Aliased(this,$)}mapWith($){return this.decoder=typeof $==="function"?{mapFromDriverValue:$}:$,this}inlineParams(){return this.shouldInlineParams=!0,this}if($){return $?this:void 0}}class Z5{constructor($){this.value=$}static[b]="Name";brand;getSQL(){return new O1([this])}}var $q={mapFromDriverValue:($)=>$},Xq={mapToDriverValue:($)=>$},Sb={...$q,...Xq};class y9{constructor($,X=Xq){this.value=$,this.encoder=X}static[b]="Param";brand;getSQL(){return new O1([this])}}function O4($,...X){let G=[];if(X.length>0||$.length>0&&$[0]!=="")G.push(new e1($[0]));for(let[Y,q]of X.entries())G.push(q,new e1($[Y+1]));return new O1(G)}(($)=>{function X(){return new O1([])}$.empty=X;function G(H){return new O1(H)}$.fromList=G;function Y(H){return new O1([new e1(H)])}$.raw=Y;function q(H,U){let D=[];for(let[K,O]of H.entries()){if(K>0&&U!==void 0)D.push(U);D.push(O)}return new O1(D)}$.join=q;function J(H){return new Z5(H)}$.identifier=J;function V(H){return new w5(H)}$.placeholder=V;function W(H,U){return new y9(H,U)}$.param=W})(O4||(O4={}));(($)=>{class X{constructor(G,Y){this.sql=G,this.fieldAlias=Y}static[b]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new X(this.sql,this.fieldAlias)}}$.Aliased=X})(O1||(O1={}));class w5{constructor($){this.name=$}static[b]="Placeholder";getSQL(){return new O1([this])}}var sR=Symbol.for("drizzle:IsDrizzleView");class Gq{static[b]="View";[F4];[sR]=!0;constructor({name:$,schema:X,selectedFields:G,query:Y}){this[F4]={name:$,originalName:$,schema:X,selectedFields:G,query:Y,isExisting:!Y,isAlias:!1}}getSQL(){return new O1([this])}}s0.prototype.getSQL=function(){return new O1([this])};F1.prototype.getSQL=function(){return new O1([this])};B5.prototype.getSQL=function(){return new O1([this])};function B0($,X){return{name:typeof $==="string"&&$.length>0?$:"",config:typeof $==="object"?$:X}}var g9=typeof TextDecoder>"u"?null:new TextDecoder;class f9{static[b]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor($,X){if(this.reference=()=>{let{name:G,columns:Y,foreignColumns:q}=$();return{name:G,columns:Y,foreignTable:q[0].table,foreignColumns:q}},X)this._onUpdate=X.onUpdate,this._onDelete=X.onDelete}onUpdate($){return this._onUpdate=$,this}onDelete($){return this._onDelete=$,this}build($){return new Yq($,this)}}class Yq{constructor($,X){this.table=$,this.reference=X.reference,this.onUpdate=X._onUpdate,this.onDelete=X._onDelete}static[b]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:$,columns:X,foreignColumns:G}=this.reference(),Y=X.map((V)=>V.name),q=G.map((V)=>V.name),J=[this.table[V0],...Y,G[0].table[V0],...q];return $??`${J.join("_")}_fk`}}function qq($,X){return`${$[V0]}_${X.join("_")}_unique`}class N1 extends I9{static[b]="SQLiteColumnBuilder";foreignKeyConfigs=[];references($,X={}){return this.foreignKeyConfigs.push({ref:$,actions:X}),this}unique($){return this.config.isUnique=!0,this.config.uniqueName=$,this}generatedAlwaysAs($,X){return this.config.generated={as:$,type:"always",mode:X?.mode??"virtual"},this}buildForeignKeys($,X){return this.foreignKeyConfigs.map(({ref:G,actions:Y})=>{return((q,J)=>{let V=new f9(()=>{let W=q();return{columns:[$],foreignColumns:[W]}});if(J.onUpdate)V.onUpdate(J.onUpdate);if(J.onDelete)V.onDelete(J.onDelete);return V.build(X)})(G,Y)})}}class z1 extends s0{constructor($,X){if(!X.uniqueName)X.uniqueName=qq($,[X.name]);super($,X);this.table=$}static[b]="SQLiteColumn"}class Jq extends N1{static[b]="SQLiteBigIntBuilder";constructor($){super($,"bigint","SQLiteBigInt")}build($){return new Vq($,this.config)}}class Vq extends z1{static[b]="SQLiteBigInt";getSQLType(){return"blob"}mapFromDriverValue($){if(typeof Buffer<"u"&&Buffer.from){let X=Buffer.isBuffer($)?$:$ instanceof ArrayBuffer?Buffer.from($):$.buffer?Buffer.from($.buffer,$.byteOffset,$.byteLength):Buffer.from($);return BigInt(X.toString("utf8"))}return BigInt(g9.decode($))}mapToDriverValue($){return Buffer.from($.toString())}}class Wq extends N1{static[b]="SQLiteBlobJsonBuilder";constructor($){super($,"json","SQLiteBlobJson")}build($){return new Hq($,this.config)}}class Hq extends z1{static[b]="SQLiteBlobJson";getSQLType(){return"blob"}mapFromDriverValue($){if(typeof Buffer<"u"&&Buffer.from){let X=Buffer.isBuffer($)?$:$ instanceof ArrayBuffer?Buffer.from($):$.buffer?Buffer.from($.buffer,$.byteOffset,$.byteLength):Buffer.from($);return JSON.parse(X.toString("utf8"))}return JSON.parse(g9.decode($))}mapToDriverValue($){return Buffer.from(JSON.stringify($))}}class Uq extends N1{static[b]="SQLiteBlobBufferBuilder";constructor($){super($,"buffer","SQLiteBlobBuffer")}build($){return new Dq($,this.config)}}class Dq extends z1{static[b]="SQLiteBlobBuffer";mapFromDriverValue($){if(Buffer.isBuffer($))return $;return Buffer.from($)}getSQLType(){return"blob"}}function Qq($,X){let{name:G,config:Y}=B0($,X);if(Y?.mode==="json")return new Wq(G);if(Y?.mode==="bigint")return new Jq(G);return new Uq(G)}class Kq extends N1{static[b]="SQLiteCustomColumnBuilder";constructor($,X,G){super($,"custom","SQLiteCustomColumn");this.config.fieldConfig=X,this.config.customTypeParams=G}build($){return new Mq($,this.config)}}class Mq extends z1{static[b]="SQLiteCustomColumn";sqlName;mapTo;mapFrom;constructor($,X){super($,X);this.sqlName=X.customTypeParams.dataType(X.fieldConfig),this.mapTo=X.customTypeParams.toDriver,this.mapFrom=X.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue($){return typeof this.mapFrom==="function"?this.mapFrom($):$}mapToDriverValue($){return typeof this.mapTo==="function"?this.mapTo($):$}}function N5($){return(X,G)=>{let{name:Y,config:q}=B0(X,G);return new Kq(Y,q,$)}}class z5 extends N1{static[b]="SQLiteBaseIntegerBuilder";constructor($,X,G){super($,X,G);this.config.autoIncrement=!1}primaryKey($){if($?.autoIncrement)this.config.autoIncrement=!0;return this.config.hasDefault=!0,super.primaryKey()}}class L5 extends z1{static[b]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}}class Fq extends z5{static[b]="SQLiteIntegerBuilder";constructor($){super($,"number","SQLiteInteger")}build($){return new Oq($,this.config)}}class Oq extends L5{static[b]="SQLiteInteger"}class Rq extends z5{static[b]="SQLiteTimestampBuilder";constructor($,X){super($,"date","SQLiteTimestamp");this.config.mode=X}defaultNow(){return this.default(O4`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build($){return new Aq($,this.config)}}class Aq extends L5{static[b]="SQLiteTimestamp";mode=this.config.mode;mapFromDriverValue($){if(this.config.mode==="timestamp")return new Date($*1000);return new Date($)}mapToDriverValue($){let X=$.getTime();if(this.config.mode==="timestamp")return Math.floor(X/1000);return X}}class Bq extends z5{static[b]="SQLiteBooleanBuilder";constructor($,X){super($,"boolean","SQLiteBoolean");this.config.mode=X}build($){return new Zq($,this.config)}}class Zq extends L5{static[b]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue($){return Number($)===1}mapToDriverValue($){return $?1:0}}function g1($,X){let{name:G,config:Y}=B0($,X);if(Y?.mode==="timestamp"||Y?.mode==="timestamp_ms")return new Rq(G,Y.mode);if(Y?.mode==="boolean")return new Bq(G,Y.mode);return new Fq(G)}class wq extends N1{static[b]="SQLiteNumericBuilder";constructor($){super($,"string","SQLiteNumeric")}build($){return new Nq($,this.config)}}class Nq extends z1{static[b]="SQLiteNumeric";mapFromDriverValue($){if(typeof $==="string")return $;return String($)}getSQLType(){return"numeric"}}class zq extends N1{static[b]="SQLiteNumericNumberBuilder";constructor($){super($,"number","SQLiteNumericNumber")}build($){return new Lq($,this.config)}}class Lq extends z1{static[b]="SQLiteNumericNumber";mapFromDriverValue($){if(typeof $==="number")return $;return Number($)}mapToDriverValue=String;getSQLType(){return"numeric"}}class _q extends N1{static[b]="SQLiteNumericBigIntBuilder";constructor($){super($,"bigint","SQLiteNumericBigInt")}build($){return new jq($,this.config)}}class jq extends z1{static[b]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}function Pq($,X){let{name:G,config:Y}=B0($,X),q=Y?.mode;return q==="number"?new zq(G):q==="bigint"?new _q(G):new wq(G)}class Eq extends N1{static[b]="SQLiteRealBuilder";constructor($){super($,"number","SQLiteReal")}build($){return new Cq($,this.config)}}class Cq extends z1{static[b]="SQLiteReal";getSQLType(){return"real"}}function Tq($){return new Eq($??"")}class Sq extends N1{static[b]="SQLiteTextBuilder";constructor($,X){super($,"string","SQLiteText");this.config.enumValues=X.enum,this.config.length=X.length}build($){return new Iq($,this.config)}}class Iq extends z1{static[b]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor($,X){super($,X)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}}class bq extends N1{static[b]="SQLiteTextJsonBuilder";constructor($){super($,"json","SQLiteTextJson")}build($){return new xq($,this.config)}}class xq extends z1{static[b]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue($){return JSON.parse($)}mapToDriverValue($){return JSON.stringify($)}}function i($,X={}){let{name:G,config:Y}=B0($,X);if(Y.mode==="json")return new bq(G);return new Sq(G,Y)}function vq(){return{blob:Qq,customType:N5,integer:g1,numeric:Pq,real:Tq,text:i}}var m9=Symbol.for("drizzle:SQLiteInlineForeignKeys");class H6 extends F1{static[b]="SQLiteTable";static Symbol=Object.assign({},F1.Symbol,{InlineForeignKeys:m9});[F1.Symbol.Columns];[m9]=[];[F1.Symbol.ExtraConfigBuilder]=void 0}function aR($,X,G,Y,q=$){let J=new H6($,Y,q),V=typeof X==="function"?X(vq()):X,W=Object.fromEntries(Object.entries(V).map(([U,D])=>{let K=D;K.setName(U);let O=K.build(J);return J[m9].push(...K.buildForeignKeys(O,J)),[U,O]})),H=Object.assign(J,W);if(H[F1.Symbol.Columns]=W,H[F1.Symbol.ExtraConfigColumns]=W,G)H[H6.Symbol.ExtraConfigBuilder]=G;return H}var Z0=($,X,G)=>{return aR($,X,G)};class kq{constructor($,X){this.name=$,this.unique=X}static[b]="SQLiteIndexBuilderOn";on(...$){return new hq(this.name,$,this.unique)}}class hq{static[b]="SQLiteIndexBuilder";config;constructor($,X,G){this.config={name:$,columns:X,unique:G,where:void 0}}where($){return this.config.where=$,this}build($){return new yq(this.config,$)}}class yq{static[b]="SQLiteIndex";config;constructor($,X){this.config={...$,table:X}}}function W0($){return new kq($,!1)}function _5(...$){if($[0].columns)return new u9($[0].columns,$[0].name);return new u9($)}class u9{static[b]="SQLitePrimaryKeyBuilder";columns;name;constructor($,X){this.columns=$,this.name=X}build($){return new gq($,this.columns,this.name)}}class gq{constructor($,X,G){this.table=$,this.columns=X,this.name=G}static[b]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[H6.Symbol.Name]}_${this.columns.map(($)=>$.name).join("_")}_pk`}}var p9=Z0("job_queue",{id:i("id").primaryKey().$defaultFn(()=>n0()),type:i("type").notNull(),data:i("data").notNull(),result:i("result",{mode:"json"}),source:i("source"),metadata:i("metadata",{mode:"json"}).$type().notNull(),status:i("status",{enum:["pending","processing","completed","failed"]}).notNull().default("pending"),priority:g1("priority").notNull().default(0),retryCount:g1("retryCount").notNull().default(0),maxRetries:g1("maxRetries").notNull().default(3),lastError:i("lastError"),createdAt:g1("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:g1("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:g1("startedAt"),completedAt:g1("completedAt")},($)=>({queueReadyIdx:W0("idx_job_queue_ready").on($.status,$.priority,$.scheduledFor),jobTypeIdx:W0("idx_job_queue_type").on($.type,$.status),jobSourceIdx:W0("idx_job_queue_source").on($.source)}));var fq=Q.enum(["file_operations","content_operations","data_processing","batch_processing"]),mq=Q.object({pluginId:Q.string().optional(),progressToken:Q.union([Q.string(),Q.number()]).optional(),operationType:fq,operationTarget:Q.string().optional(),interfaceType:Q.string().optional(),channelId:Q.string().optional()}),U6=mq.extend({rootJobId:Q.string()}),vx=Q.enum(["none","skip","replace","coalesce"]);var l9=Q.enum(["pending","processing","completed","failed"]),uq=Q.enum(["completed","failed"]);var tR=Q.object({id:Q.string(),type:Q.string(),status:l9,data:Q.unknown(),result:Q.unknown().optional(),lastError:Q.string().optional().nullable(),attempts:Q.number(),maxRetries:Q.number(),priority:Q.number(),createdAt:Q.date(),updatedAt:Q.date(),processedAt:Q.date().optional().nullable(),completedAt:Q.date().optional().nullable(),failedAt:Q.date().optional().nullable()}),eR=Q.object({jobId:Q.string(),type:Q.string(),status:uq,result:Q.unknown().optional(),error:Q.string().optional()}),j5=Q.object({id:Q.string(),type:Q.enum(["job","batch"]),status:l9,message:Q.string().optional(),progress:Q.object({current:Q.number(),total:Q.number(),percentage:Q.number()}).optional(),aggregationKey:Q.string().optional(),batchDetails:Q.object({totalOperations:Q.number(),completedOperations:Q.number(),failedOperations:Q.number(),currentOperation:Q.string().optional(),errors:Q.array(Q.string()).optional()}).optional(),jobDetails:Q.object({jobType:Q.string(),priority:Q.number(),retryCount:Q.number()}).optional(),metadata:U6});import{createClient as mx}from"@libsql/client";var Vv=Q.object({success:Q.literal(!1),error:Q.string().optional()});class R4{logger;schema;jobTypeName;constructor($,X){this.logger=$,this.schema=X.schema,this.jobTypeName=X.jobTypeName}validateAndParse($){if(!this.schema)throw Error(`${this.jobTypeName}: No schema provided. Override validateAndParse() or provide a schema.`);try{let X=this.schema.parse($);return this.logger.debug(`${this.jobTypeName} job data validation successful`,{data:this.summarizeDataForLog(X)}),X}catch(X){return this.logger.warn(`Invalid ${this.jobTypeName} job data`,{data:$,validationError:X instanceof Q.ZodError?X.issues:X}),null}}async onError($,X,G,Y){this.logger.error(`${this.jobTypeName} job error handler triggered`,{jobId:G,errorMessage:$.message,errorStack:$.stack,data:this.summarizeDataForLog(X)})}async reportProgress($,X){await $.report({progress:X.progress,total:X.total??100,message:X.message})}summarizeDataForLog($){return $}}var $A=Q.object({id:Q.string(),type:Q.string(),data:Q.string(),status:Q.enum(["pending","processing","completed","failed"]),source:Q.string().nullable(),priority:Q.number(),retryCount:Q.number(),maxRetries:Q.number(),lastError:Q.string().nullable(),createdAt:Q.number(),scheduledFor:Q.number(),startedAt:Q.number().nullable(),completedAt:Q.number().nullable(),metadata:U6,result:Q.unknown().nullable().optional()});import{createClient as pv}from"@libsql/client";var E5=Z0("entities",{id:i("id").notNull(),entityType:i("entityType").notNull(),content:i("content").notNull(),contentHash:i("contentHash").notNull(),metadata:i("metadata",{mode:"json"}).$type().notNull().default(O4`'{}'`),created:g1("created").notNull().$defaultFn(()=>Date.now()),updated:g1("updated").notNull().$defaultFn(()=>Date.now())},($)=>{return{pk:_5({columns:[$.id,$.entityType]})}});import{createClient as av}from"@libsql/client";var pq=N5({dataType(){return"F32_BLOB(1536)"},toDriver($){return Buffer.from($.buffer)},fromDriver($){return new Float32Array($.buffer,$.byteOffset,$.byteLength/4)}});var C5=Z0("embeddings",{entityId:i("entity_id").notNull(),entityType:i("entity_type").notNull(),embedding:pq("embedding").notNull(),contentHash:i("content_hash").notNull()},($)=>{return{pk:_5({columns:[$.entityId,$.entityType]})}});var Gk=Q.object({id:Q.string().min(1,"Entity ID is required"),entityType:Q.string().min(1,"Entity type is required"),contentHash:Q.string().min(1,"Content hash is required"),operation:Q.enum(["create","update"])});var Vk=Q.object({limit:Q.number().int().positive().optional().default(20),offset:Q.number().int().min(0).optional().default(0),types:Q.array(Q.string()).optional().default([]),excludeTypes:Q.array(Q.string()).optional().default([]),weight:Q.record(Q.string(),Q.number()).optional()});var qA=Q.object({field:Q.string(),direction:Q.enum(["asc","desc"]),nullsFirst:Q.boolean().optional()}),Mk=Q.object({limit:Q.number().int().positive().optional(),offset:Q.number().int().min(0).optional().default(0),sortFields:Q.array(qA).optional(),filter:Q.object({metadata:Q.record(Q.string(),Q.unknown()).optional()}).optional(),publishedOnly:Q.boolean().optional()});var T5=M6(H8(),1);function D6($,X){if(Object.keys(X).length===0)return $;let G=Object.fromEntries(Object.entries(X).filter(([,Y])=>Y!==void 0));return T5.default.stringify($,G)}function d9($){if($ instanceof Date)return $.toISOString();if(Array.isArray($))return $.map(d9);if($!==null&&typeof $==="object"){let X={};for(let[G,Y]of Object.entries($))X[G]=d9(Y);return X}return $}function H0($,X){let{content:G,data:Y}=T5.default($),q=d9(Y);return{content:G.trim(),metadata:X.parse(q)}}function c9($){if(Object.keys($).length===0)return"";let G=T5.default.stringify("",$).match(/^---\n[\s\S]*?\n---/);return G?G[0]:""}var MA={generateBodyTemplate:()=>""};class I0{entityType;schema;frontmatterSchema;isSingleton;hasBody;supportsCoverImage;fmSchema;bodyFormatter;constructor($){if(this.entityType=$.entityType,this.schema=$.schema,this.frontmatterSchema=$.frontmatterSchema,this.fmSchema=$.frontmatterSchema,this.bodyFormatter=$.bodyFormatter??MA,$.isSingleton!==void 0)this.isSingleton=$.isSingleton;if($.hasBody!==void 0)this.hasBody=$.hasBody;if($.supportsCoverImage!==void 0)this.supportsCoverImage=$.supportsCoverImage}toMarkdown($){let X=this.renderBody($),Y={...this.readExistingFrontmatter($.content)},q=Object.keys(this.frontmatterSchema.shape);for(let[J,V]of Object.entries($.metadata))if(q.includes(J))Y[J]=V;return this.buildMarkdown(X,Y)}renderBody($){return this.extractBody($.content)}readExistingFrontmatter($){try{return H0($,Q.record(Q.unknown())).metadata}catch{return{}}}extractMetadata($){return $.metadata}parseFrontMatter($,X){return H0($,X).metadata}getBodyTemplate(){return this.bodyFormatter.generateBodyTemplate()}generateFrontMatter($){let X=$.metadata;return c9(X)}extractBody($){try{return H0($,Q.record(Q.unknown())).content}catch{return $}}parseFrontmatter($){return H0($,this.fmSchema).metadata}buildMarkdown($,X){return D6($,X)}}var P2=Q.object({id:Q.string(),entityType:Q.string(),content:Q.string(),created:Q.string().datetime(),updated:Q.string().datetime(),metadata:Q.record(Q.string(),Q.unknown()),contentHash:Q.string()});class A4{cache=null;cacheParseError=null;logger;entityService;entityType;defaultBody;constructor($,X,G,Y){this.entityService=$,this.logger=X.child(this.constructor.name),this.entityType=G,this.defaultBody=Y}async initialize(){if(await this.load(),!this.cache){if(await this.load(),this.cache)return;this.logger.info(`No ${this.entityType} found, creating default ${this.entityType}`);try{let $=this.createContent(this.defaultBody);await this.entityService.createEntity({id:this.entityType,entityType:this.entityType,content:$,metadata:{}}),await this.load(),this.logger.info(`Default ${this.entityType} created successfully`)}catch($){this.logger.error(`Failed to create default ${this.entityType}`,{error:$})}}}get(){if(this.cache&&!this.cacheParseError)return this.parseBody(this.cache.content);return this.defaultBody}getContent(){if(this.cache)return this.cache.content;return this.createContent(this.defaultBody)}async refreshCache(){await this.load()}async load(){try{let $=await this.entityService.getEntity(this.entityType,this.entityType);if(this.cache=$,this.cacheParseError=null,$)try{this.parseBody($.content),this.logger.debug(`${this.entityType} loaded`)}catch(X){this.cacheParseError=X instanceof Error?X:Error(String(X)),this.logger.error(`Failed to parse ${this.entityType} \u2014 using default. Fix the entity content to clear this error.`,{error:this.cacheParseError.message})}else this.logger.debug(`No ${this.entityType} found in database`)}catch($){this.logger.warn(`Failed to load ${this.entityType}`,{error:$}),this.cache=null,this.cacheParseError=null}}}var lq=Q.object({currentPage:Q.number(),totalPages:Q.number(),totalItems:Q.number(),pageSize:Q.number(),hasNextPage:Q.boolean(),hasPrevPage:Q.boolean()});function r9($,X,G){let Y=Math.max(1,Math.ceil($/G));return{currentPage:X,totalPages:Y,totalItems:$,pageSize:G,hasNextPage:X<Y,hasPrevPage:X>1}}var oh=Q.object({});var o9=Q.object({id:Q.string().optional(),limit:Q.number().optional(),page:Q.number().optional(),pageSize:Q.number().optional(),baseUrl:Q.string().optional()}).passthrough(),n9=Q.object({entityType:Q.string().optional(),query:o9.optional()}).passthrough();class s9{logger;constructor($){this.logger=$}buildDetailResult($,X){throw Error(`${this.id}: buildDetailResult() not implemented. Override this method or override fetch() to handle detail views.`)}parseQuery($){let X=n9.parse($);return{entityType:X.entityType??this.config.entityType,query:X.query??{}}}async fetch($,X,G){let Y=this.parseQuery($),q=G.entityService;if(Y.query.id){let V=await this.fetchDetail(Y.query.id,q);return X.parse(this.buildDetailResult(V.item,V.navigation))}let J=await this.fetchList(Y.query,q);return X.parse(this.buildListResult(J.items,J.pagination,Y.query))}async fetchDetail($,X){let G=await this.lookupEntity($,X),Y=this.transformEntity(G),q=null;if(this.config.enableNavigation)q=await this.resolveNavigation(G,X);return{item:Y,navigation:q}}async fetchList($,X,G){let Y=$.page??1,q=$.pageSize??$.limit??this.config.defaultLimit??100,J=(Y-1)*q,V=$.page!==void 0,[W,H]=await Promise.all([X.listEntities(this.config.entityType,{limit:q,offset:J,sortFields:this.config.defaultSort,...G}),V?X.countEntities(this.config.entityType,G?.filter?{filter:G.filter}:void 0):Promise.resolve(0)]),U=W.map((K)=>this.transformEntity(K)),D=V?r9(H,Y,q):null;return{items:U,pagination:D}}async resolveNavigation($,X,G){let Y=this.config.navigationLimit??1000,q=await X.listEntities(this.config.entityType,{limit:Y,sortFields:G??this.config.defaultSort}),J=q.findIndex((D)=>D.id===$.id),V=J>0?q[J-1]:void 0,W=J<q.length-1?q[J+1]:void 0,H=V?this.transformEntity(V):null,U=W?this.transformEntity(W):null;return{prev:H,next:U}}async lookupEntity($,X){if(this.config.lookupField==="id"){let q=await X.getEntity(this.config.entityType,$);if(!q)throw Error(`${this.config.entityType} not found: ${$}`);return q}let Y=(await X.listEntities(this.config.entityType,{filter:{metadata:{slug:$}},limit:1}))[0];if(!Y)throw Error(`${this.config.entityType} not found with slug: ${$}`);return Y}}class t9 extends R4{context;entityType;constructor($,X,G){super($,{schema:G.schema,jobTypeName:G.jobTypeName});this.context=X,this.entityType=G.entityType}async afterCreate($,X,G,Y){}async onGenerationFailure($,X){}async process($,X,G){try{await this.reportProgress(G,{progress:q6.START,message:`Starting ${this.jobTypeName}`});let Y=await this.generate($,G);await this.reportProgress(G,{progress:q6.SAVE,message:`Saving ${this.entityType} to database`});let q=await this.context.entityService.createEntity({id:Y.id,entityType:this.entityType,content:Y.content,metadata:Y.metadata},Y.createOptions);return await this.afterCreate($,q.entityId,G,Y),await this.reportProgress(G,{progress:q6.COMPLETE,message:`${Y.title??this.entityType} created successfully`}),{success:!0,entityId:q.entityId,...Y.resultExtras}}catch(Y){if(Y instanceof a9)return await this.onGenerationFailure($,Y.message),{success:!1,error:Y.message};let q=h1(Y);return this.logger.error(`${this.jobTypeName} job failed`,{error:Y,jobId:X,data:this.summarizeDataForLog($)}),await this.onGenerationFailure($,q),C9.failure(Y)}}failEarly($){throw new a9($)}}class a9 extends Error{constructor($){super($);this.name="GenerationFailure"}}import{createClient as Qy}from"@libsql/client";var S5=Z0("conversations",{id:i("id").primaryKey(),sessionId:i("session_id").notNull(),interfaceType:i("interface_type").notNull(),channelId:i("channel_id").notNull(),started:i("started").notNull(),lastActive:i("last_active").notNull(),metadata:i("metadata"),created:i("created").notNull(),updated:i("updated").notNull()},($)=>({sessionIdx:W0("idx_conversations_session").on($.sessionId),channelIdx:W0("idx_conversations_channel").on($.channelId),interfaceSessionIdx:W0("idx_conversations_interface_session").on($.interfaceType,$.sessionId),interfaceChannelIdx:W0("idx_conversations_interface_channel").on($.interfaceType,$.channelId)})),rq=Z0("messages",{id:i("id").primaryKey(),conversationId:i("conversation_id").notNull().references(()=>S5.id,{onDelete:"cascade"}),role:i("role").notNull(),content:i("content").notNull(),timestamp:i("timestamp").notNull(),metadata:i("metadata")},($)=>({conversationIdx:W0("idx_messages_conversation").on($.conversationId),timestampIdx:W0("idx_messages_timestamp").on($.timestamp)})),iq=Z0("summary_tracking",{conversationId:i("conversation_id").primaryKey().references(()=>S5.id,{onDelete:"cascade"}),lastSummarizedAt:i("last_summarized_at"),lastMessageId:i("last_message_id"),messagesSinceSummary:g1("messages_since_summary").default(0),updated:i("updated").notNull()});var BA=Q.object({id:Q.string(),conversationId:Q.string(),role:Q.string(),content:Q.string(),timestamp:Q.string(),metadata:Q.string().nullable()}),oq=Q.object({conversationId:Q.string(),messageCount:Q.number(),messages:Q.array(BA),windowStart:Q.number(),windowEnd:Q.number(),windowSize:Q.number(),timestamp:Q.string()});var nq=Q.object({captureUrls:Q.boolean().default(!1),blockedUrlDomains:Q.array(Q.string()).default(["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"])});async function sq($){let{entityType:X,title:G,deriveId:Y,regeneratePrompt:q,context:J}=$,V=Y(G);if(!await J.entityService.getEntity(X,V))return G;J.logger.debug(`Entity ID collision: ${X}/${V}, asking AI for a new title`);let H=Q.object({title:Q.string().max(80).describe("A short, unique title (2-6 words)")}),{object:U}=await J.ai.generateObject(`The title "${G}" is already taken. ${q}`,H),D=U.title;return J.logger.debug(`AI suggested new title: "${D}"`),D}var PA=Q.object({id:Q.string(),template:Q.string(),content:Q.unknown().optional(),dataQuery:Q.object({entityType:Q.string().optional(),template:Q.string().optional(),query:Q.object({id:Q.string().optional(),limit:Q.number().optional(),offset:Q.number().optional()}).passthrough().optional()}).passthrough().optional(),order:Q.number().optional()}),aq=["primary","secondary"],EA=Q.object({show:Q.boolean().default(!1),label:Q.string().optional(),slot:Q.enum(aq).default("primary"),priority:Q.number().min(0).max(100).default(50)}).optional(),tq=Q.object({id:Q.string(),path:Q.string(),title:Q.string().default(""),description:Q.string().default(""),sections:Q.array(PA).default([]),layout:Q.string().default("default"),fullscreen:Q.boolean().optional(),pluginId:Q.string().optional(),sourceEntityType:Q.string().optional(),external:Q.boolean().optional(),navigation:EA}),CA=Q.object({routes:Q.array(tq),pluginId:Q.string()}),TA=Q.object({paths:Q.array(Q.string()).optional(),pluginId:Q.string().optional()}),SA=Q.object({pluginId:Q.string().optional()}),IA=Q.object({path:Q.string()});var bA=Q.object({enabled:Q.boolean().describe("Whether the plugin is enabled"),debug:Q.boolean().describe("Enable debug logging for this plugin")});var e9=P2.extend({id:Q.literal("brain-character"),entityType:Q.literal("brain-character")}),I5=Q.object({name:Q.string().describe("The brain's friendly display name"),role:Q.string().describe("The brain's primary role"),purpose:Q.string().describe("The brain's purpose and goals"),values:Q.array(Q.string()).describe("Core values that guide behavior")});class b5 extends I0{constructor(){super({entityType:"brain-character",schema:e9,frontmatterSchema:I5,isSingleton:!0,hasBody:!1})}createCharacterContent($){return this.buildMarkdown("",$)}parseCharacterBody($){return this.parseFrontmatter($)}toMarkdown($){let X=this.parseFrontmatter($.content);return this.buildMarkdown("",X)}fromMarkdown($){return{content:$,entityType:"brain-character"}}extractMetadata($){let X=this.parseFrontmatter($.content);return{role:X.role,values:X.values}}generateFrontMatter($){let X=this.parseFrontmatter($.content);return this.buildMarkdown("",X)}}class a0 extends A4{static instance=null;adapter=new b5;static getDefaultCharacter(){return{name:"Brain",role:"Knowledge assistant",purpose:"Help organize, understand, and retrieve information from your knowledge base",values:["clarity","accuracy","helpfulness"]}}static getInstance($,X,G){return a0.instance??=new a0($,X,G),a0.instance}static resetInstance(){a0.instance=null}static createFresh($,X,G){return new a0($,X,G)}constructor($,X,G){super($,X,"brain-character",G??a0.getDefaultCharacter())}parseBody($){return this.adapter.parseCharacterBody($)}createContent($){return this.adapter.createCharacterContent($)}getCharacter(){return this.get()}getCharacterContent(){return this.getContent()}}var eq=Q.object({tagline:Q.string().optional().describe("Short, punchy one-liner for homepage"),intro:Q.string().optional().describe("Optional longer introduction for homepage"),story:Q.string().optional().describe("Extended bio/narrative (multi-paragraph markdown)")});var $7=P2.extend({id:Q.literal("anchor-profile"),entityType:Q.literal("anchor-profile")}),B4=Q.object({name:Q.string().describe("Name (person or organization)"),kind:Q.enum(["professional","team","collective"]).describe("Type of anchor: professional (individual), team, or collective"),organization:Q.string().optional().describe("Organization the anchor belongs to"),description:Q.string().optional().describe("Short description or biography"),avatar:Q.string().optional().describe("URL or asset path to avatar/logo"),website:Q.string().optional().describe("Primary website URL"),email:Q.string().optional().describe("Contact email"),socialLinks:Q.array(Q.object({platform:Q.enum(["github","instagram","linkedin","email","website"]).describe("Social media platform"),url:Q.string().describe("Profile or contact URL"),label:Q.string().optional().describe("Optional display label")})).optional().describe("Social media and contact links")});class x5 extends I0{constructor(){super({entityType:"anchor-profile",schema:$7,frontmatterSchema:B4,isSingleton:!0,hasBody:!0})}createProfileContent($){let X=B4.parse($);return this.buildMarkdown("",X)}parseProfileBody($,X){if(X){let{metadata:G,content:Y}=H0($,X);return Y?{...G,story:Y}:G}return this.parseFrontmatter($)}fromMarkdown($){return{content:$,entityType:"anchor-profile"}}extractMetadata($){let X=this.parseFrontmatter($.content);return{name:X.name,email:X.email,website:X.website}}generateFrontMatter($){let X=this.parseFrontmatter($.content);return this.buildMarkdown("",X)}}class b0 extends A4{static instance=null;adapter=new x5;static getDefaultProfile(){return{name:"Unknown",kind:"professional"}}static getInstance($,X,G){return b0.instance??=new b0($,X,G),b0.instance}static resetInstance(){b0.instance=null}static createFresh($,X,G){return new b0($,X,G)}constructor($,X,G){super($,X,"anchor-profile",G??b0.getDefaultProfile())}parseBody($){return this.adapter.parseProfileBody($)}createContent($){return this.adapter.createProfileContent($)}getProfile(){return this.get()}getProfileContent(){return this.getContent()}}var $J=Q.object({id:Q.string(),description:Q.string(),name:Q.string().optional(),tags:Q.array(Q.string()).optional().default([])}).passthrough();var vA=Q.object({uri:Q.string(),params:Q.record(Q.unknown()).optional()}).passthrough(),kA=Q.object({name:Q.string(),url:Q.string(),description:Q.string().optional(),skills:Q.array($J).optional().default([]),capabilities:Q.object({extensions:Q.array(vA).optional().default([])}).passthrough().optional()}).passthrough();var hA=Q.object({name:Q.string(),description:Q.string(),tags:Q.array(Q.string()),examples:Q.array(Q.string())});import{EventEmitter as XJ}from"events";class U0 extends Error{pluginId;constructor($,X){super(`Plugin ${$}: ${X}`);this.name="PluginError",this.pluginId=$}}class X7{plugins;events;daemonRegistry;logger;constructor($,X,G,Y){this.plugins=$;this.events=X;this.daemonRegistry=G;this.logger=Y.child("PluginLifecycle")}async initializePlugin($,X,G){let Y=this.plugins.get($);if(!Y)throw new U0($,"Registration failed: Plugin is not registered");let q=Y.plugin;this.logger.debug(`Initializing plugin: ${$}`),this.events.emit("plugin:before_initialize",$,q);try{let J=await q.register(X,G);return Y.status="initialized",this.logger.debug(`Initialized plugin: ${$}`),this.events.emit("plugin:initialized",$,q),J}catch(J){let V=h1(J);throw this.logger.error(`Error initializing plugin ${$}: ${V}`),Y.status="error",Y.error=J6(J),this.events.emit("plugin:error",$,J),J}}async readyPlugin($){let X=this.plugins.get($);if(!X)throw new U0($,"Ready failed: Plugin is not registered");if(X.status!=="initialized"){this.logger.debug(`Skipping ready hook for non-initialized plugin: ${$}`);return}try{await X.plugin.ready?.(),this.logger.debug(`Ready hook completed for plugin: ${$}`)}catch(G){let Y=J6(G);throw X.status="error",X.error=Y,this.events.emit("plugin:error",$,Y),Y}}async startPluginDaemons($){let X=this.plugins.get($);if(X?.status!=="initialized")return;try{await this.daemonRegistry.startPlugin($),this.logger.debug(`Started daemons for plugin: ${$}`)}catch(G){if(X.plugin.requiresDaemonStartup?.())throw G;this.logger.warn(`Daemon ${$} failed to start: ${h1(G)}`)}}async disablePlugin($){let X=this.plugins.get($);if(!X){this.logger.warn(`Cannot disable plugin ${$}: not registered`);return}this.logger.debug(`Disabling plugin: ${$}`);try{await this.daemonRegistry.stopPlugin($),this.logger.debug(`Stopped daemons for plugin: ${$}`)}catch(G){this.logger.error(`Failed to stop daemons for plugin: ${$}`,G)}if(X.plugin.shutdown)try{await X.plugin.shutdown(),this.logger.debug(`Shutdown completed for plugin: ${$}`)}catch(G){this.logger.error(`Plugin shutdown failed for ${$}:`,G)}X.status="disabled",this.events.emit("plugin:disabled",$,X.plugin),this.logger.debug(`Disabled plugin: ${$}`)}async enablePlugin($){let X=this.plugins.get($);if(!X){this.logger.warn(`Cannot enable plugin ${$}: not registered`);return}if(X.status!=="disabled"){this.logger.warn(`Cannot enable plugin ${$}: not disabled`);return}this.logger.debug(`Enabling plugin: ${$}`),X.status="initialized";try{await this.daemonRegistry.startPlugin($),this.logger.debug(`Started daemons for plugin: ${$}`)}catch(G){this.logger.error(`Failed to start daemons for plugin: ${$}`,G)}this.events.emit("plugin:enabled",$,X.plugin),this.logger.debug(`Enabled plugin: ${$}`)}}class G7{plugins;events;logger;constructor($,X,G){this.plugins=$;this.events=X;this.logger=G.child("DependencyResolver")}async resolveInitializationOrder($){this.logger.debug("Resolving plugin initialization order...");let X=Array.from(this.plugins.keys()),G=new Set,Y=!0;while(Y&&G.size<X.length){Y=!1;for(let V of X){if(G.has(V))continue;if(!this.plugins.get(V))continue;if(this.getUnmetDependencies(V).length===0)try{await $(V),G.add(V),Y=!0}catch(U){let D=h1(U);this.logger.error(`Failed to initialize plugin ${V}: ${D}`),G.add(V),Y=!0}}}let q=X.filter((V)=>!G.has(V));if(q.length>0){let V=q.join(", ");this.logger.error(`Failed to initialize plugins due to dependency issues: ${V}`);for(let W of q){let H=this.getUnmetDependencies(W);this.logger.error(`Plugin ${W} has unmet dependencies: ${H.join(", ")}`);let U=this.plugins.get(W);if(U)U.status="error",U.error=new U0(W,`Unmet dependencies: ${H.join(", ")}`);this.events.emit("plugin:error",W,U?.error)}}let J=new Set;for(let[V,W]of this.plugins)if(W.status==="initialized")J.add(V);return this.logger.debug(`Resolved ${J.size} of ${X.length} plugins`),{initialized:J,failed:q}}getUnmetDependencies($){let X=this.plugins.get($);if(!X)return[];let{dependencies:G}=X,Y=[];for(let q of G){let J=this.plugins.get(q);if(!J){Y.push(q);continue}if(J.status!=="initialized")Y.push(q)}return Y}}class Y7{logger;constructor($){this.logger=$.child("CapabilityRegistrar")}async registerCapabilities($,X,G){if(G.tools.length>0)$.registerTools(X,G.tools),this.logger.debug(`Registered ${G.tools.length} tools from ${X}`);if(G.resources.length>0)$.registerResources(X,G.resources),this.logger.debug(`Registered ${G.resources.length} resources from ${X}`);if(G.instructions)$.registerInstructions(X,G.instructions),this.logger.debug(`Registered instructions from ${X}`)}}class t0{static instance=null;plugins=new Map;logger;events=new XJ;daemonRegistry;shell=null;initializedPluginIds=[];pluginLifecycle;dependencyResolver;capabilityRegistrar;static getInstance($,X){return t0.instance??=new t0($,X),t0.instance}static resetInstance(){t0.instance=null}static createFresh($,X){return new t0($,X)}setShell($){this.shell=$}constructor($,X){this.logger=$.child("PluginManager"),this.events=new XJ,this.daemonRegistry=X,this.pluginLifecycle=new X7(this.plugins,this.events,this.daemonRegistry,$),this.dependencyResolver=new G7(this.plugins,this.events,$),this.capabilityRegistrar=new Y7($)}registerPlugin($){if(!$.id)throw new U0("unknown","Registration failed: Plugin must have an id");if(this.logger.debug(`Registering plugin: ${$.id} (${$.version})`),this.plugins.has($.id)){let q=this.plugins.get($.id)?.plugin.version;throw new U0($.id,`Registration failed: Plugin is already registered with version ${q}`)}let X=$.dependencies??[],G={plugin:$,status:"registered",dependencies:X};this.plugins.set($.id,G),this.logger.debug(`Registered plugin: ${$.id} (${$.version})`),this.events.emit("plugin:registered",$.id,$)}async initializePlugins($){this.logger.debug("Initializing plugins..."),this.initializedPluginIds=[];let X=await this.dependencyResolver.resolveInitializationOrder(async(G)=>{await this.initializePlugin(G,$)});this.logger.debug(`Initialized ${X.initialized.size} of ${this.plugins.size} plugins`)}async initializePlugin($,X){if(!this.shell)throw new U0($,"Cannot initialize plugin: Shell not set. Call setShell() first.");let G=this.shell,Y=await this.pluginLifecycle.initializePlugin($,G,X);await this.capabilityRegistrar.registerCapabilities(G,$,Y),this.initializedPluginIds.push($)}async readyPlugins(){this.logger.debug("Dispatching plugin ready hooks..."),await Promise.all(this.initializedPluginIds.map(($)=>this.pluginLifecycle.readyPlugin($)))}async startPluginDaemons(){this.logger.debug("Starting plugin daemons..."),await Promise.all(this.initializedPluginIds.map(($)=>this.pluginLifecycle.startPluginDaemons($)))}getPlugin($){return this.plugins.get($)?.plugin}getPluginStatus($){return this.plugins.get($)?.status}hasPlugin($){return this.plugins.has($)}isPluginInitialized($){return this.plugins.get($)?.status==="initialized"}getAllPluginIds(){return Array.from(this.plugins.keys())}getAllPlugins(){return new Map(this.plugins)}getFailedPlugins(){return Array.from(this.plugins.entries()).filter(($)=>$[1].status==="error"&&$[1].error!==void 0).map(([$,X])=>({id:$,error:X.error}))}getPluginPackageName($){return this.plugins.get($)?.plugin.packageName}async disablePlugin($){await this.pluginLifecycle.disablePlugin($)}async enablePlugin($){await this.pluginLifecycle.enablePlugin($)}on($,X){this.events.on($,X)}once($,X){this.events.once($,X)}off($,X){this.events.off($,X)}getEventEmitter(){return this.events}}export{sq as ensureUniqueTitle,o9 as baseQuerySchema,n9 as baseInputSchema,j5 as JobProgressEventSchema,R4 as BaseJobHandler,t9 as BaseGenerationJobHandler,s9 as BaseEntityDataSource};
170
170
 
171
- //# debugId=5F6DE4FDBE70339B64756E2164756E21
171
+ //# debugId=FAF3307BAA02555264756E2164756E21
172
172
  //# sourceMappingURL=services.js.map