@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
 
3
3
  export const UserPermissionLevelSchema: z.ZodSchema<UserPermissionLevel>;
4
4
  export type UserPermissionLevel = "public" | "trusted" | "anchor";
@@ -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 bC=Q.object({slug:Q.string(),title:Q.string(),type:Q.string(),entityId:Q.string(),contentHash:Q.string()});import{webcrypto as EY}from"crypto";var PY="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var NO=128,j2,K4;function zO($){if(!j2||j2.length<$)j2=Buffer.allocUnsafe($*NO),EY.getRandomValues(j2),K4=0;else if(K4+$>j2.length)EY.getRandomValues(j2),K4=0;K4+=$}function CY($=21){zO($|=0);let X="";for(let G=K4-$;G<K4;G++)X+=PY[j2[G]&63];return X}function n0($=12){return CY($)}function o1($){return $ instanceof Error?$.message:String($)}function Y6($){return $ instanceof Error?$:Error(String($))}var _O=Q.object({success:Q.boolean(),entityId:Q.string().optional(),error:Q.string().optional()});var R5=Q.enum(["anchor","trusted","public"]);var TO=Q.object({name:Q.string(),description:Q.string(),schema:Q.any(),basePrompt:Q.string().optional(),useKnowledgeContext:Q.boolean().optional(),requiredPermission:R5,formatter:Q.any().optional(),layout:Q.object({component:Q.any(),fullscreen:Q.boolean().optional()}).optional(),dataSourceId:Q.string().optional()});var SO=Q.enum(["site-content-preview","site-content-production"]),IO=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()})}),bO=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()}),xO=Q.object({success:Q.boolean(),routesBuilt:Q.number(),errors:Q.array(Q.string()).optional(),warnings:Q.array(Q.string()).optional()});var kO=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()}),bY=Q.object({name:Q.string(),pluginId:Q.string(),status:Q.string(),health:kO.optional()});import{McpServer as UI}from"@modelcontextprotocol/sdk/server/mcp.js";import{ResourceTemplate as MI}from"@modelcontextprotocol/sdk/server/mcp.js";var O5=Q.object({interfaceType:Q.string(),userId:Q.string(),channelId:Q.string().optional(),channelName:Q.string().optional()}),xY=Q.object({success:Q.literal(!0),data:Q.unknown(),message:Q.string().optional()}),vY=Q.object({success:Q.literal(!1),error:Q.string(),code:Q.string().optional()}),kY=Q.object({needsConfirmation:Q.literal(!0),toolName:Q.string(),description:Q.string(),args:Q.unknown()}),P9=Q.union([xY,vY,kY]);var hY=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 II=Q.object({id:Q.string(),type:Q.string(),version:Q.string(),status:Q.string()}),bI=Q.object({name:Q.string(),description:Q.string()}),yY=Q.object({label:Q.string(),url:Q.string(),pluginId:Q.string(),priority:Q.number().default(100)}),mO=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(bY),endpoints:Q.array(yY)}),xI=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()}),vI=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 uO=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 mI=Q.object({toolName:Q.string(),args:Q.unknown(),progressToken:Q.union([Q.string(),Q.number()]).optional(),hasProgress:Q.boolean().optional(),...O5.shape}),uI=Q.object({resourceUri:Q.string()});var dI=Q.object({name:Q.string(),schema:Q.custom(($)=>$ instanceof Q.ZodType)});var b=Symbol.for("drizzle:entityKind");function h1($,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 E9{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 gY($,...X){return $(...X)}function fY($,X){return`${$[V0]}_${X.join("_")}_unique`}class q6 extends s0{constructor($,X){if(!X.uniqueName)X.uniqueName=fY($,[X.name]);super($,X);this.table=$}static[b]="PgColumn"}class pO extends q6{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 lO extends q6{static[b]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor($,X){super($,X);this.enum=X.enum}getSQLType(){return this.enum.enumName}}var mY=Symbol.for("drizzle:isPgEnum");function uY($){return!!$&&typeof $==="function"&&mY in $&&$[mY]===!0}class dO extends q6{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 A5{static[b]="Subquery";constructor($,X,G,Y=!1,q=[]){this._={brand:"Subquery",sql:$,selectedFields:X,alias:G,isWith:Y,usedTables:q}}}var pY="0.44.7";var C9,T9,lY={startActiveSpan($,X){if(!C9)return X();if(!T9)T9=C9.trace.getTracer("drizzle-orm",pY);return gY((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()}}),C9,T9)}};var F4=Symbol.for("drizzle:ViewBaseConfig");var S9=Symbol.for("drizzle:Schema"),dY=Symbol.for("drizzle:Columns"),cY=Symbol.for("drizzle:ExtraConfigColumns"),I9=Symbol.for("drizzle:OriginalName"),b9=Symbol.for("drizzle:BaseName"),J6=Symbol.for("drizzle:IsAlias"),rY=Symbol.for("drizzle:ExtraConfigBuilder"),cO=Symbol.for("drizzle:IsDrizzleTable");class F1{static[b]="Table";static Symbol={Name:V0,Schema:S9,OriginalName:I9,Columns:dY,ExtraConfigColumns:cY,BaseName:b9,IsAlias:J6,ExtraConfigBuilder:rY};[V0];[I9];[S9];[dY];[cY];[b9];[J6]=!1;[cO]=!0;[rY]=void 0;constructor($,X,G){this[V0]=this[I9]=$,this[S9]=X,this[b9]=G}}function rO($){return $!==null&&$!==void 0&&typeof $.getSQL==="function"}function iO($){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 R1([this])}}class R1{constructor($){this.queryChunks=$;for(let X of $)if(h1(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=iY;shouldInlineParams=!1;usedTables=[];append($){return this.queryChunks.push(...$.queryChunks),this}toQuery($){return lY.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 iO($.map((U)=>{if(h1(U,e1))return{sql:U.value.join(""),params:[]};if(h1(U,B5))return{sql:q(U.value),params:[]};if(U===void 0)return{sql:"",params:[]};if(Array.isArray(U)){let D=[new e1("(")];for(let[M,R]of U.entries())if(D.push(R),M<U.length-1)D.push(new e1(", "));return D.push(new e1(")")),this.buildQueryFromSourceParams(D,G)}if(h1(U,R1))return this.buildQueryFromSourceParams(U.queryChunks,{...G,inlineParams:W||U.shouldInlineParams});if(h1(U,F1)){let D=U[F1.Symbol.Schema],M=U[F1.Symbol.Name];return{sql:D===void 0||U[J6]?q(M):q(D)+"."+q(M),params:[]}}if(h1(U,s0)){let D=Y.getColumnCasing(U);if(X.invokeSource==="indexes")return{sql:q(D),params:[]};let M=U.table[F1.Symbol.Schema];return{sql:U.table[J6]||M===void 0?q(U.table[F1.Symbol.Name])+"."+q(D):q(M)+"."+q(U.table[F1.Symbol.Name])+"."+q(D),params:[]}}if(h1(U,nY)){let D=U[F4].schema,M=U[F4].name;return{sql:D===void 0||U[F4].isAlias?q(M):q(D)+"."+q(M),params:[]}}if(h1(U,x9)){if(h1(U.value,Z5))return{sql:J(H.value++,U),params:[U],typings:["none"]};let D=U.value===null?null:U.encoder.mapToDriverValue(U.value);if(h1(D,R1))return this.buildQueryFromSourceParams([D],G);if(W)return{sql:this.mapInlineParam(D,G),params:[]};let M=["none"];if(V)M=[V(U.encoder)];return{sql:J(H.value++,D),params:[D],typings:M}}if(h1(U,Z5))return{sql:J(H.value++,U),params:[U],typings:["none"]};if(h1(U,R1.Aliased)&&U.fieldAlias!==void 0)return{sql:q(U.fieldAlias),params:[]};if(h1(U,A5)){if(U._.isWith)return{sql:q(U._.alias),params:[]};return this.buildQueryFromSourceParams([new e1("("),U._.sql,new e1(") "),new B5(U._.alias)],G)}if(uY(U)){if(U.schema)return{sql:q(U.schema)+"."+q(U.enumName),params:[]};return{sql:q(U.enumName),params:[]}}if(rO(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 R1.Aliased(this,$)}mapWith($){return this.decoder=typeof $==="function"?{mapFromDriverValue:$}:$,this}inlineParams(){return this.shouldInlineParams=!0,this}if($){return $?this:void 0}}class B5{constructor($){this.value=$}static[b]="Name";brand;getSQL(){return new R1([this])}}var iY={mapFromDriverValue:($)=>$},oY={mapToDriverValue:($)=>$},Pb={...iY,...oY};class x9{constructor($,X=oY){this.value=$,this.encoder=X}static[b]="Param";brand;getSQL(){return new R1([this])}}function R4($,...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 R1(G)}(($)=>{function X(){return new R1([])}$.empty=X;function G(H){return new R1(H)}$.fromList=G;function Y(H){return new R1([new e1(H)])}$.raw=Y;function q(H,U){let D=[];for(let[M,R]of H.entries()){if(M>0&&U!==void 0)D.push(U);D.push(R)}return new R1(D)}$.join=q;function J(H){return new B5(H)}$.identifier=J;function V(H){return new Z5(H)}$.placeholder=V;function W(H,U){return new x9(H,U)}$.param=W})(R4||(R4={}));(($)=>{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})(R1||(R1={}));class Z5{constructor($){this.name=$}static[b]="Placeholder";getSQL(){return new R1([this])}}var oO=Symbol.for("drizzle:IsDrizzleView");class nY{static[b]="View";[F4];[oO]=!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 R1([this])}}s0.prototype.getSQL=function(){return new R1([this])};F1.prototype.getSQL=function(){return new R1([this])};A5.prototype.getSQL=function(){return new R1([this])};function B0($,X){return{name:typeof $==="string"&&$.length>0?$:"",config:typeof $==="object"?$:X}}var v9=typeof TextDecoder>"u"?null:new TextDecoder;class k9{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 sY($,this)}}class sY{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 aY($,X){return`${$[V0]}_${X.join("_")}_unique`}class N1 extends E9{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 k9(()=>{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=aY($,[X.name]);super($,X);this.table=$}static[b]="SQLiteColumn"}class tY extends N1{static[b]="SQLiteBigIntBuilder";constructor($){super($,"bigint","SQLiteBigInt")}build($){return new eY($,this.config)}}class eY 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(v9.decode($))}mapToDriverValue($){return Buffer.from($.toString())}}class $q extends N1{static[b]="SQLiteBlobJsonBuilder";constructor($){super($,"json","SQLiteBlobJson")}build($){return new Xq($,this.config)}}class Xq 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(v9.decode($))}mapToDriverValue($){return Buffer.from(JSON.stringify($))}}class Gq extends N1{static[b]="SQLiteBlobBufferBuilder";constructor($){super($,"buffer","SQLiteBlobBuffer")}build($){return new Yq($,this.config)}}class Yq 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 $q(G);if(Y?.mode==="bigint")return new tY(G);return new Gq(G)}class Jq extends N1{static[b]="SQLiteCustomColumnBuilder";constructor($,X,G){super($,"custom","SQLiteCustomColumn");this.config.fieldConfig=X,this.config.customTypeParams=G}build($){return new Vq($,this.config)}}class Vq 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 w5($){return(X,G)=>{let{name:Y,config:q}=B0(X,G);return new Jq(Y,q,$)}}class N5 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 z5 extends z1{static[b]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}}class Wq extends N5{static[b]="SQLiteIntegerBuilder";constructor($){super($,"number","SQLiteInteger")}build($){return new Hq($,this.config)}}class Hq extends z5{static[b]="SQLiteInteger"}class Uq extends N5{static[b]="SQLiteTimestampBuilder";constructor($,X){super($,"date","SQLiteTimestamp");this.config.mode=X}defaultNow(){return this.default(R4`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build($){return new Dq($,this.config)}}class Dq extends z5{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 Qq extends N5{static[b]="SQLiteBooleanBuilder";constructor($,X){super($,"boolean","SQLiteBoolean");this.config.mode=X}build($){return new Mq($,this.config)}}class Mq extends z5{static[b]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue($){return Number($)===1}mapToDriverValue($){return $?1:0}}function y1($,X){let{name:G,config:Y}=B0($,X);if(Y?.mode==="timestamp"||Y?.mode==="timestamp_ms")return new Uq(G,Y.mode);if(Y?.mode==="boolean")return new Qq(G,Y.mode);return new Wq(G)}class Kq extends N1{static[b]="SQLiteNumericBuilder";constructor($){super($,"string","SQLiteNumeric")}build($){return new Fq($,this.config)}}class Fq extends z1{static[b]="SQLiteNumeric";mapFromDriverValue($){if(typeof $==="string")return $;return String($)}getSQLType(){return"numeric"}}class Rq extends N1{static[b]="SQLiteNumericNumberBuilder";constructor($){super($,"number","SQLiteNumericNumber")}build($){return new Oq($,this.config)}}class Oq extends z1{static[b]="SQLiteNumericNumber";mapFromDriverValue($){if(typeof $==="number")return $;return Number($)}mapToDriverValue=String;getSQLType(){return"numeric"}}class Aq extends N1{static[b]="SQLiteNumericBigIntBuilder";constructor($){super($,"bigint","SQLiteNumericBigInt")}build($){return new Bq($,this.config)}}class Bq extends z1{static[b]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}function Zq($,X){let{name:G,config:Y}=B0($,X),q=Y?.mode;return q==="number"?new Rq(G):q==="bigint"?new Aq(G):new Kq(G)}class wq extends N1{static[b]="SQLiteRealBuilder";constructor($){super($,"number","SQLiteReal")}build($){return new Nq($,this.config)}}class Nq extends z1{static[b]="SQLiteReal";getSQLType(){return"real"}}function zq($){return new wq($??"")}class Lq extends N1{static[b]="SQLiteTextBuilder";constructor($,X){super($,"string","SQLiteText");this.config.enumValues=X.enum,this.config.length=X.length}build($){return new _q($,this.config)}}class _q 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 jq extends N1{static[b]="SQLiteTextJsonBuilder";constructor($){super($,"json","SQLiteTextJson")}build($){return new Pq($,this.config)}}class Pq 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 jq(G);return new Lq(G,Y)}function Eq(){return{blob:qq,customType:w5,integer:y1,numeric:Zq,real:zq,text:i}}var h9=Symbol.for("drizzle:SQLiteInlineForeignKeys");class V6 extends F1{static[b]="SQLiteTable";static Symbol=Object.assign({},F1.Symbol,{InlineForeignKeys:h9});[F1.Symbol.Columns];[h9]=[];[F1.Symbol.ExtraConfigBuilder]=void 0}function nO($,X,G,Y,q=$){let J=new V6($,Y,q),V=typeof X==="function"?X(Eq()):X,W=Object.fromEntries(Object.entries(V).map(([U,D])=>{let M=D;M.setName(U);let R=M.build(J);return J[h9].push(...M.buildForeignKeys(R,J)),[U,R]})),H=Object.assign(J,W);if(H[F1.Symbol.Columns]=W,H[F1.Symbol.ExtraConfigColumns]=W,G)H[V6.Symbol.ExtraConfigBuilder]=G;return H}var Z0=($,X,G)=>{return nO($,X,G)};class Cq{constructor($,X){this.name=$,this.unique=X}static[b]="SQLiteIndexBuilderOn";on(...$){return new Tq(this.name,$,this.unique)}}class Tq{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 Sq(this.config,$)}}class Sq{static[b]="SQLiteIndex";config;constructor($,X){this.config={...$,table:X}}}function W0($){return new Cq($,!1)}function L5(...$){if($[0].columns)return new y9($[0].columns,$[0].name);return new y9($)}class y9{static[b]="SQLitePrimaryKeyBuilder";columns;name;constructor($,X){this.columns=$,this.name=X}build($){return new Iq($,this.columns,this.name)}}class Iq{constructor($,X,G){this.table=$,this.columns=X,this.name=G}static[b]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[V6.Symbol.Name]}_${this.columns.map(($)=>$.name).join("_")}_pk`}}var g9=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:y1("priority").notNull().default(0),retryCount:y1("retryCount").notNull().default(0),maxRetries:y1("maxRetries").notNull().default(3),lastError:i("lastError"),createdAt:y1("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:y1("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:y1("startedAt"),completedAt:y1("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 bq=Q.enum(["file_operations","content_operations","data_processing","batch_processing"]),xq=Q.object({pluginId:Q.string().optional(),progressToken:Q.union([Q.string(),Q.number()]).optional(),operationType:bq,operationTarget:Q.string().optional(),interfaceType:Q.string().optional(),channelId:Q.string().optional()}),W6=xq.extend({rootJobId:Q.string()}),Sx=Q.enum(["none","skip","replace","coalesce"]);var f9=Q.enum(["pending","processing","completed","failed"]),vq=Q.enum(["completed","failed"]);var sO=Q.object({id:Q.string(),type:Q.string(),status:f9,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()}),aO=Q.object({jobId:Q.string(),type:Q.string(),status:vq,result:Q.unknown().optional(),error:Q.string().optional()}),m9=Q.object({id:Q.string(),type:Q.enum(["job","batch"]),status:f9,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:W6});import{createClient as hx}from"@libsql/client";var Gv=Q.object({success:Q.literal(!1),error:Q.string().optional()});var tO=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:W6,result:Q.unknown().nullable().optional()});import{createClient as gv}from"@libsql/client";var j5=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(R4`'{}'`),created:y1("created").notNull().$defaultFn(()=>Date.now()),updated:y1("updated").notNull().$defaultFn(()=>Date.now())},($)=>{return{pk:L5({columns:[$.id,$.entityType]})}});import{createClient as iv}from"@libsql/client";var hq=w5({dataType(){return"F32_BLOB(1536)"},toDriver($){return Buffer.from($.buffer)},fromDriver($){return new Float32Array($.buffer,$.byteOffset,$.byteLength/4)}});var P5=Z0("embeddings",{entityId:i("entity_id").notNull(),entityType:i("entity_type").notNull(),embedding:hq("embedding").notNull(),contentHash:i("content_hash").notNull()},($)=>{return{pk:L5({columns:[$.entityId,$.entityType]})}});var tv=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 Gk=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 GA=Q.object({field:Q.string(),direction:Q.enum(["asc","desc"]),nullsFirst:Q.boolean().optional()}),Uk=Q.object({limit:Q.number().int().positive().optional(),offset:Q.number().int().min(0).optional().default(0),sortFields:Q.array(GA).optional(),filter:Q.object({metadata:Q.record(Q.string(),Q.unknown()).optional()}).optional(),publishedOnly:Q.boolean().optional()});var E5=Q6(V8(),1);function H6($,X){if(Object.keys(X).length===0)return $;let G=Object.fromEntries(Object.entries(X).filter(([,Y])=>Y!==void 0));return E5.default.stringify($,G)}function u9($){if($ instanceof Date)return $.toISOString();if(Array.isArray($))return $.map(u9);if($!==null&&typeof $==="object"){let X={};for(let[G,Y]of Object.entries($))X[G]=u9(Y);return X}return $}function H0($,X){let{content:G,data:Y}=E5.default($),q=u9(Y);return{content:G.trim(),metadata:X.parse(q)}}function p9($){if(Object.keys($).length===0)return"";let G=E5.default.stringify("",$).match(/^---\n[\s\S]*?\n---/);return G?G[0]:""}var QA={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??QA,$.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 p9(X)}extractBody($){try{return H0($,Q.record(Q.unknown())).content}catch{return $}}parseFrontmatter($){return H0($,this.fmSchema).metadata}buildMarkdown($,X){return H6($,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 O4{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 yq=Q.object({currentPage:Q.number(),totalPages:Q.number(),totalItems:Q.number(),pageSize:Q.number(),hasNextPage:Q.boolean(),hasPrevPage:Q.boolean()});var dh=Q.object({});var mq=Q.object({id:Q.string().optional(),limit:Q.number().optional(),page:Q.number().optional(),pageSize:Q.number().optional(),baseUrl:Q.string().optional()}).passthrough(),AA=Q.object({entityType:Q.string().optional(),query:mq.optional()}).passthrough();import{createClient as Wy}from"@libsql/client";var C5=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)})),uq=Z0("messages",{id:i("id").primaryKey(),conversationId:i("conversation_id").notNull().references(()=>C5.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)})),pq=Z0("summary_tracking",{conversationId:i("conversation_id").primaryKey().references(()=>C5.id,{onDelete:"cascade"}),lastSummarizedAt:i("last_summarized_at"),lastMessageId:i("last_message_id"),messagesSinceSummary:y1("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()}),lq=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 dq=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"])});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()}),d9=["primary","secondary"],EA=Q.object({show:Q.boolean().default(!1),label:Q.string().optional(),slot:Q.enum(d9).default("primary"),priority:Q.number().min(0).max(100).default(50)}).optional(),c9=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}),cq=Q.object({routes:Q.array(c9),pluginId:Q.string()}),rq=Q.object({paths:Q.array(Q.string()).optional(),pluginId:Q.string().optional()}),iq=Q.object({pluginId:Q.string().optional()}),oq=Q.object({path:Q.string()});var CA=Q.object({enabled:Q.boolean().describe("Whether the plugin is enabled"),debug:Q.boolean().describe("Enable debug logging for this plugin")});var r9=P2.extend({id:Q.literal("brain-character"),entityType:Q.literal("brain-character")}),T5=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 S5 extends I0{constructor(){super({entityType:"brain-character",schema:r9,frontmatterSchema:T5,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 O4{static instance=null;adapter=new S5;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 nq=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 i9=P2.extend({id:Q.literal("anchor-profile"),entityType:Q.literal("anchor-profile")}),A4=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 I5 extends I0{constructor(){super({entityType:"anchor-profile",schema:i9,frontmatterSchema:A4,isSingleton:!0,hasBody:!0})}createProfileContent($){let X=A4.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 O4{static instance=null;adapter=new I5;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 sq=Q.object({id:Q.string(),description:Q.string(),name:Q.string().optional(),tags:Q.array(Q.string()).optional().default([])}).passthrough();var SA=Q.object({uri:Q.string(),params:Q.record(Q.unknown()).optional()}).passthrough(),IA=Q.object({name:Q.string(),url:Q.string(),description:Q.string().optional(),skills:Q.array(sq).optional().default([]),capabilities:Q.object({extensions:Q.array(SA).optional().default([])}).passthrough().optional()}).passthrough();var bA=Q.object({name:Q.string(),description:Q.string(),tags:Q.array(Q.string()),examples:Q.array(Q.string())});import{EventEmitter as aq}from"events";class U0 extends Error{pluginId;constructor($,X){super(`Plugin ${$}: ${X}`);this.name="PluginError",this.pluginId=$}}class o9{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=o1(J);throw this.logger.error(`Error initializing plugin ${$}: ${V}`),Y.status="error",Y.error=Y6(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=Y6(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: ${o1(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 n9{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=o1(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 s9{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 aq;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 aq,this.daemonRegistry=X,this.pluginLifecycle=new o9(this.plugins,this.events,this.daemonRegistry,$),this.dependencyResolver=new n9(this.plugins,this.events,$),this.capabilityRegistrar=new s9($)}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{R5 as UserPermissionLevelSchema,rq as UnregisterRoutesPayloadSchema,c9 as RouteDefinitionSchema,cq as RegisterRoutesPayloadSchema,d9 as NavigationSlots,iq as ListRoutesPayloadSchema,oq as GetRoutePayloadSchema};
169
+ `)}}var bC=Q.object({slug:Q.string(),title:Q.string(),type:Q.string(),entityId:Q.string(),contentHash:Q.string()});import{webcrypto as EY}from"crypto";var PY="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var NO=128,j2,K4;function zO($){if(!j2||j2.length<$)j2=Buffer.allocUnsafe($*NO),EY.getRandomValues(j2),K4=0;else if(K4+$>j2.length)EY.getRandomValues(j2),K4=0;K4+=$}function CY($=21){zO($|=0);let X="";for(let G=K4-$;G<K4;G++)X+=PY[j2[G]&63];return X}function n0($=12){return CY($)}function o1($){return $ instanceof Error?$.message:String($)}function Y6($){return $ instanceof Error?$:Error(String($))}var _O=Q.object({success:Q.boolean(),entityId:Q.string().optional(),error:Q.string().optional()});var R5=Q.enum(["anchor","trusted","public"]);var TO=Q.object({name:Q.string(),description:Q.string(),schema:Q.any(),basePrompt:Q.string().optional(),useKnowledgeContext:Q.boolean().optional(),requiredPermission:R5,formatter:Q.any().optional(),layout:Q.object({component:Q.any(),fullscreen:Q.boolean().optional()}).optional(),dataSourceId:Q.string().optional()});var SO=Q.enum(["site-content-preview","site-content-production"]),IO=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()})}),bO=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()}),xO=Q.object({success:Q.boolean(),routesBuilt:Q.number(),errors:Q.array(Q.string()).optional(),warnings:Q.array(Q.string()).optional()});var kO=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()}),bY=Q.object({name:Q.string(),pluginId:Q.string(),status:Q.string(),health:kO.optional()});import{McpServer as UI}from"@modelcontextprotocol/sdk/server/mcp.js";import{ResourceTemplate as MI}from"@modelcontextprotocol/sdk/server/mcp.js";var O5=Q.object({interfaceType:Q.string(),userId:Q.string(),channelId:Q.string().optional(),channelName:Q.string().optional()}),xY=Q.object({success:Q.literal(!0),data:Q.unknown(),message:Q.string().optional()}),vY=Q.object({success:Q.literal(!1),error:Q.string(),code:Q.string().optional()}),kY=Q.object({needsConfirmation:Q.literal(!0),toolName:Q.string(),description:Q.string(),args:Q.unknown()}),P9=Q.union([xY,vY,kY]);var hY=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 II=Q.object({id:Q.string(),type:Q.string(),version:Q.string(),status:Q.string()}),bI=Q.object({name:Q.string(),description:Q.string()}),yY=Q.object({label:Q.string(),url:Q.string(),pluginId:Q.string(),priority:Q.number().default(100)}),mO=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(bY),endpoints:Q.array(yY)}),xI=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()}),vI=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 uO=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 mI=Q.object({toolName:Q.string(),args:Q.unknown(),progressToken:Q.union([Q.string(),Q.number()]).optional(),hasProgress:Q.boolean().optional(),...O5.shape}),uI=Q.object({resourceUri:Q.string()});var dI=Q.object({name:Q.string(),schema:Q.custom(($)=>$ instanceof Q.ZodType)});var b=Symbol.for("drizzle:entityKind");function h1($,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 E9{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 gY($,...X){return $(...X)}function fY($,X){return`${$[V0]}_${X.join("_")}_unique`}class q6 extends s0{constructor($,X){if(!X.uniqueName)X.uniqueName=fY($,[X.name]);super($,X);this.table=$}static[b]="PgColumn"}class pO extends q6{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 lO extends q6{static[b]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor($,X){super($,X);this.enum=X.enum}getSQLType(){return this.enum.enumName}}var mY=Symbol.for("drizzle:isPgEnum");function uY($){return!!$&&typeof $==="function"&&mY in $&&$[mY]===!0}class dO extends q6{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 A5{static[b]="Subquery";constructor($,X,G,Y=!1,q=[]){this._={brand:"Subquery",sql:$,selectedFields:X,alias:G,isWith:Y,usedTables:q}}}var pY="0.44.7";var C9,T9,lY={startActiveSpan($,X){if(!C9)return X();if(!T9)T9=C9.trace.getTracer("drizzle-orm",pY);return gY((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()}}),C9,T9)}};var F4=Symbol.for("drizzle:ViewBaseConfig");var S9=Symbol.for("drizzle:Schema"),dY=Symbol.for("drizzle:Columns"),cY=Symbol.for("drizzle:ExtraConfigColumns"),I9=Symbol.for("drizzle:OriginalName"),b9=Symbol.for("drizzle:BaseName"),J6=Symbol.for("drizzle:IsAlias"),rY=Symbol.for("drizzle:ExtraConfigBuilder"),cO=Symbol.for("drizzle:IsDrizzleTable");class F1{static[b]="Table";static Symbol={Name:V0,Schema:S9,OriginalName:I9,Columns:dY,ExtraConfigColumns:cY,BaseName:b9,IsAlias:J6,ExtraConfigBuilder:rY};[V0];[I9];[S9];[dY];[cY];[b9];[J6]=!1;[cO]=!0;[rY]=void 0;constructor($,X,G){this[V0]=this[I9]=$,this[S9]=X,this[b9]=G}}function rO($){return $!==null&&$!==void 0&&typeof $.getSQL==="function"}function iO($){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 R1([this])}}class R1{constructor($){this.queryChunks=$;for(let X of $)if(h1(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=iY;shouldInlineParams=!1;usedTables=[];append($){return this.queryChunks.push(...$.queryChunks),this}toQuery($){return lY.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 iO($.map((U)=>{if(h1(U,e1))return{sql:U.value.join(""),params:[]};if(h1(U,B5))return{sql:q(U.value),params:[]};if(U===void 0)return{sql:"",params:[]};if(Array.isArray(U)){let D=[new e1("(")];for(let[M,R]of U.entries())if(D.push(R),M<U.length-1)D.push(new e1(", "));return D.push(new e1(")")),this.buildQueryFromSourceParams(D,G)}if(h1(U,R1))return this.buildQueryFromSourceParams(U.queryChunks,{...G,inlineParams:W||U.shouldInlineParams});if(h1(U,F1)){let D=U[F1.Symbol.Schema],M=U[F1.Symbol.Name];return{sql:D===void 0||U[J6]?q(M):q(D)+"."+q(M),params:[]}}if(h1(U,s0)){let D=Y.getColumnCasing(U);if(X.invokeSource==="indexes")return{sql:q(D),params:[]};let M=U.table[F1.Symbol.Schema];return{sql:U.table[J6]||M===void 0?q(U.table[F1.Symbol.Name])+"."+q(D):q(M)+"."+q(U.table[F1.Symbol.Name])+"."+q(D),params:[]}}if(h1(U,nY)){let D=U[F4].schema,M=U[F4].name;return{sql:D===void 0||U[F4].isAlias?q(M):q(D)+"."+q(M),params:[]}}if(h1(U,x9)){if(h1(U.value,Z5))return{sql:J(H.value++,U),params:[U],typings:["none"]};let D=U.value===null?null:U.encoder.mapToDriverValue(U.value);if(h1(D,R1))return this.buildQueryFromSourceParams([D],G);if(W)return{sql:this.mapInlineParam(D,G),params:[]};let M=["none"];if(V)M=[V(U.encoder)];return{sql:J(H.value++,D),params:[D],typings:M}}if(h1(U,Z5))return{sql:J(H.value++,U),params:[U],typings:["none"]};if(h1(U,R1.Aliased)&&U.fieldAlias!==void 0)return{sql:q(U.fieldAlias),params:[]};if(h1(U,A5)){if(U._.isWith)return{sql:q(U._.alias),params:[]};return this.buildQueryFromSourceParams([new e1("("),U._.sql,new e1(") "),new B5(U._.alias)],G)}if(uY(U)){if(U.schema)return{sql:q(U.schema)+"."+q(U.enumName),params:[]};return{sql:q(U.enumName),params:[]}}if(rO(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 R1.Aliased(this,$)}mapWith($){return this.decoder=typeof $==="function"?{mapFromDriverValue:$}:$,this}inlineParams(){return this.shouldInlineParams=!0,this}if($){return $?this:void 0}}class B5{constructor($){this.value=$}static[b]="Name";brand;getSQL(){return new R1([this])}}var iY={mapFromDriverValue:($)=>$},oY={mapToDriverValue:($)=>$},Pb={...iY,...oY};class x9{constructor($,X=oY){this.value=$,this.encoder=X}static[b]="Param";brand;getSQL(){return new R1([this])}}function R4($,...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 R1(G)}(($)=>{function X(){return new R1([])}$.empty=X;function G(H){return new R1(H)}$.fromList=G;function Y(H){return new R1([new e1(H)])}$.raw=Y;function q(H,U){let D=[];for(let[M,R]of H.entries()){if(M>0&&U!==void 0)D.push(U);D.push(R)}return new R1(D)}$.join=q;function J(H){return new B5(H)}$.identifier=J;function V(H){return new Z5(H)}$.placeholder=V;function W(H,U){return new x9(H,U)}$.param=W})(R4||(R4={}));(($)=>{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})(R1||(R1={}));class Z5{constructor($){this.name=$}static[b]="Placeholder";getSQL(){return new R1([this])}}var oO=Symbol.for("drizzle:IsDrizzleView");class nY{static[b]="View";[F4];[oO]=!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 R1([this])}}s0.prototype.getSQL=function(){return new R1([this])};F1.prototype.getSQL=function(){return new R1([this])};A5.prototype.getSQL=function(){return new R1([this])};function B0($,X){return{name:typeof $==="string"&&$.length>0?$:"",config:typeof $==="object"?$:X}}var v9=typeof TextDecoder>"u"?null:new TextDecoder;class k9{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 sY($,this)}}class sY{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 aY($,X){return`${$[V0]}_${X.join("_")}_unique`}class N1 extends E9{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 k9(()=>{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=aY($,[X.name]);super($,X);this.table=$}static[b]="SQLiteColumn"}class tY extends N1{static[b]="SQLiteBigIntBuilder";constructor($){super($,"bigint","SQLiteBigInt")}build($){return new eY($,this.config)}}class eY 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(v9.decode($))}mapToDriverValue($){return Buffer.from($.toString())}}class $q extends N1{static[b]="SQLiteBlobJsonBuilder";constructor($){super($,"json","SQLiteBlobJson")}build($){return new Xq($,this.config)}}class Xq 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(v9.decode($))}mapToDriverValue($){return Buffer.from(JSON.stringify($))}}class Gq extends N1{static[b]="SQLiteBlobBufferBuilder";constructor($){super($,"buffer","SQLiteBlobBuffer")}build($){return new Yq($,this.config)}}class Yq 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 $q(G);if(Y?.mode==="bigint")return new tY(G);return new Gq(G)}class Jq extends N1{static[b]="SQLiteCustomColumnBuilder";constructor($,X,G){super($,"custom","SQLiteCustomColumn");this.config.fieldConfig=X,this.config.customTypeParams=G}build($){return new Vq($,this.config)}}class Vq 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 w5($){return(X,G)=>{let{name:Y,config:q}=B0(X,G);return new Jq(Y,q,$)}}class N5 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 z5 extends z1{static[b]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}}class Wq extends N5{static[b]="SQLiteIntegerBuilder";constructor($){super($,"number","SQLiteInteger")}build($){return new Hq($,this.config)}}class Hq extends z5{static[b]="SQLiteInteger"}class Uq extends N5{static[b]="SQLiteTimestampBuilder";constructor($,X){super($,"date","SQLiteTimestamp");this.config.mode=X}defaultNow(){return this.default(R4`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build($){return new Dq($,this.config)}}class Dq extends z5{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 Qq extends N5{static[b]="SQLiteBooleanBuilder";constructor($,X){super($,"boolean","SQLiteBoolean");this.config.mode=X}build($){return new Mq($,this.config)}}class Mq extends z5{static[b]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue($){return Number($)===1}mapToDriverValue($){return $?1:0}}function y1($,X){let{name:G,config:Y}=B0($,X);if(Y?.mode==="timestamp"||Y?.mode==="timestamp_ms")return new Uq(G,Y.mode);if(Y?.mode==="boolean")return new Qq(G,Y.mode);return new Wq(G)}class Kq extends N1{static[b]="SQLiteNumericBuilder";constructor($){super($,"string","SQLiteNumeric")}build($){return new Fq($,this.config)}}class Fq extends z1{static[b]="SQLiteNumeric";mapFromDriverValue($){if(typeof $==="string")return $;return String($)}getSQLType(){return"numeric"}}class Rq extends N1{static[b]="SQLiteNumericNumberBuilder";constructor($){super($,"number","SQLiteNumericNumber")}build($){return new Oq($,this.config)}}class Oq extends z1{static[b]="SQLiteNumericNumber";mapFromDriverValue($){if(typeof $==="number")return $;return Number($)}mapToDriverValue=String;getSQLType(){return"numeric"}}class Aq extends N1{static[b]="SQLiteNumericBigIntBuilder";constructor($){super($,"bigint","SQLiteNumericBigInt")}build($){return new Bq($,this.config)}}class Bq extends z1{static[b]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}function Zq($,X){let{name:G,config:Y}=B0($,X),q=Y?.mode;return q==="number"?new Rq(G):q==="bigint"?new Aq(G):new Kq(G)}class wq extends N1{static[b]="SQLiteRealBuilder";constructor($){super($,"number","SQLiteReal")}build($){return new Nq($,this.config)}}class Nq extends z1{static[b]="SQLiteReal";getSQLType(){return"real"}}function zq($){return new wq($??"")}class Lq extends N1{static[b]="SQLiteTextBuilder";constructor($,X){super($,"string","SQLiteText");this.config.enumValues=X.enum,this.config.length=X.length}build($){return new _q($,this.config)}}class _q 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 jq extends N1{static[b]="SQLiteTextJsonBuilder";constructor($){super($,"json","SQLiteTextJson")}build($){return new Pq($,this.config)}}class Pq 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 jq(G);return new Lq(G,Y)}function Eq(){return{blob:qq,customType:w5,integer:y1,numeric:Zq,real:zq,text:i}}var h9=Symbol.for("drizzle:SQLiteInlineForeignKeys");class V6 extends F1{static[b]="SQLiteTable";static Symbol=Object.assign({},F1.Symbol,{InlineForeignKeys:h9});[F1.Symbol.Columns];[h9]=[];[F1.Symbol.ExtraConfigBuilder]=void 0}function nO($,X,G,Y,q=$){let J=new V6($,Y,q),V=typeof X==="function"?X(Eq()):X,W=Object.fromEntries(Object.entries(V).map(([U,D])=>{let M=D;M.setName(U);let R=M.build(J);return J[h9].push(...M.buildForeignKeys(R,J)),[U,R]})),H=Object.assign(J,W);if(H[F1.Symbol.Columns]=W,H[F1.Symbol.ExtraConfigColumns]=W,G)H[V6.Symbol.ExtraConfigBuilder]=G;return H}var Z0=($,X,G)=>{return nO($,X,G)};class Cq{constructor($,X){this.name=$,this.unique=X}static[b]="SQLiteIndexBuilderOn";on(...$){return new Tq(this.name,$,this.unique)}}class Tq{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 Sq(this.config,$)}}class Sq{static[b]="SQLiteIndex";config;constructor($,X){this.config={...$,table:X}}}function W0($){return new Cq($,!1)}function L5(...$){if($[0].columns)return new y9($[0].columns,$[0].name);return new y9($)}class y9{static[b]="SQLitePrimaryKeyBuilder";columns;name;constructor($,X){this.columns=$,this.name=X}build($){return new Iq($,this.columns,this.name)}}class Iq{constructor($,X,G){this.table=$,this.columns=X,this.name=G}static[b]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[V6.Symbol.Name]}_${this.columns.map(($)=>$.name).join("_")}_pk`}}var g9=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:y1("priority").notNull().default(0),retryCount:y1("retryCount").notNull().default(0),maxRetries:y1("maxRetries").notNull().default(3),lastError:i("lastError"),createdAt:y1("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:y1("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:y1("startedAt"),completedAt:y1("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 bq=Q.enum(["file_operations","content_operations","data_processing","batch_processing"]),xq=Q.object({pluginId:Q.string().optional(),progressToken:Q.union([Q.string(),Q.number()]).optional(),operationType:bq,operationTarget:Q.string().optional(),interfaceType:Q.string().optional(),channelId:Q.string().optional()}),W6=xq.extend({rootJobId:Q.string()}),Sx=Q.enum(["none","skip","replace","coalesce"]);var f9=Q.enum(["pending","processing","completed","failed"]),vq=Q.enum(["completed","failed"]);var sO=Q.object({id:Q.string(),type:Q.string(),status:f9,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()}),aO=Q.object({jobId:Q.string(),type:Q.string(),status:vq,result:Q.unknown().optional(),error:Q.string().optional()}),m9=Q.object({id:Q.string(),type:Q.enum(["job","batch"]),status:f9,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:W6});import{createClient as hx}from"@libsql/client";var Gv=Q.object({success:Q.literal(!1),error:Q.string().optional()});var tO=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:W6,result:Q.unknown().nullable().optional()});import{createClient as gv}from"@libsql/client";var j5=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(R4`'{}'`),created:y1("created").notNull().$defaultFn(()=>Date.now()),updated:y1("updated").notNull().$defaultFn(()=>Date.now())},($)=>{return{pk:L5({columns:[$.id,$.entityType]})}});import{createClient as iv}from"@libsql/client";var hq=w5({dataType(){return"F32_BLOB(1536)"},toDriver($){return Buffer.from($.buffer)},fromDriver($){return new Float32Array($.buffer,$.byteOffset,$.byteLength/4)}});var P5=Z0("embeddings",{entityId:i("entity_id").notNull(),entityType:i("entity_type").notNull(),embedding:hq("embedding").notNull(),contentHash:i("content_hash").notNull()},($)=>{return{pk:L5({columns:[$.entityId,$.entityType]})}});var tv=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 Gk=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 GA=Q.object({field:Q.string(),direction:Q.enum(["asc","desc"]),nullsFirst:Q.boolean().optional()}),Uk=Q.object({limit:Q.number().int().positive().optional(),offset:Q.number().int().min(0).optional().default(0),sortFields:Q.array(GA).optional(),filter:Q.object({metadata:Q.record(Q.string(),Q.unknown()).optional()}).optional(),publishedOnly:Q.boolean().optional()});var E5=Q6(V8(),1);function H6($,X){if(Object.keys(X).length===0)return $;let G=Object.fromEntries(Object.entries(X).filter(([,Y])=>Y!==void 0));return E5.default.stringify($,G)}function u9($){if($ instanceof Date)return $.toISOString();if(Array.isArray($))return $.map(u9);if($!==null&&typeof $==="object"){let X={};for(let[G,Y]of Object.entries($))X[G]=u9(Y);return X}return $}function H0($,X){let{content:G,data:Y}=E5.default($),q=u9(Y);return{content:G.trim(),metadata:X.parse(q)}}function p9($){if(Object.keys($).length===0)return"";let G=E5.default.stringify("",$).match(/^---\n[\s\S]*?\n---/);return G?G[0]:""}var QA={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??QA,$.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 p9(X)}extractBody($){try{return H0($,Q.record(Q.unknown())).content}catch{return $}}parseFrontmatter($){return H0($,this.fmSchema).metadata}buildMarkdown($,X){return H6($,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 O4{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 yq=Q.object({currentPage:Q.number(),totalPages:Q.number(),totalItems:Q.number(),pageSize:Q.number(),hasNextPage:Q.boolean(),hasPrevPage:Q.boolean()});var dh=Q.object({});var mq=Q.object({id:Q.string().optional(),limit:Q.number().optional(),page:Q.number().optional(),pageSize:Q.number().optional(),baseUrl:Q.string().optional()}).passthrough(),AA=Q.object({entityType:Q.string().optional(),query:mq.optional()}).passthrough();import{createClient as Wy}from"@libsql/client";var C5=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)})),uq=Z0("messages",{id:i("id").primaryKey(),conversationId:i("conversation_id").notNull().references(()=>C5.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)})),pq=Z0("summary_tracking",{conversationId:i("conversation_id").primaryKey().references(()=>C5.id,{onDelete:"cascade"}),lastSummarizedAt:i("last_summarized_at"),lastMessageId:i("last_message_id"),messagesSinceSummary:y1("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()}),lq=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 dq=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"])});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()}),d9=["primary","secondary"],EA=Q.object({show:Q.boolean().default(!1),label:Q.string().optional(),slot:Q.enum(d9).default("primary"),priority:Q.number().min(0).max(100).default(50)}).optional(),c9=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}),cq=Q.object({routes:Q.array(c9),pluginId:Q.string()}),rq=Q.object({paths:Q.array(Q.string()).optional(),pluginId:Q.string().optional()}),iq=Q.object({pluginId:Q.string().optional()}),oq=Q.object({path:Q.string()});var CA=Q.object({enabled:Q.boolean().describe("Whether the plugin is enabled"),debug:Q.boolean().describe("Enable debug logging for this plugin")});var r9=P2.extend({id:Q.literal("brain-character"),entityType:Q.literal("brain-character")}),T5=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 S5 extends I0{constructor(){super({entityType:"brain-character",schema:r9,frontmatterSchema:T5,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 O4{static instance=null;adapter=new S5;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 nq=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 i9=P2.extend({id:Q.literal("anchor-profile"),entityType:Q.literal("anchor-profile")}),A4=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 I5 extends I0{constructor(){super({entityType:"anchor-profile",schema:i9,frontmatterSchema:A4,isSingleton:!0,hasBody:!0})}createProfileContent($){let X=A4.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 O4{static instance=null;adapter=new I5;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 sq=Q.object({id:Q.string(),description:Q.string(),name:Q.string().optional(),tags:Q.array(Q.string()).optional().default([])}).passthrough();var SA=Q.object({uri:Q.string(),params:Q.record(Q.unknown()).optional()}).passthrough(),IA=Q.object({name:Q.string(),url:Q.string(),description:Q.string().optional(),skills:Q.array(sq).optional().default([]),capabilities:Q.object({extensions:Q.array(SA).optional().default([])}).passthrough().optional()}).passthrough();var bA=Q.object({name:Q.string(),description:Q.string(),tags:Q.array(Q.string()),examples:Q.array(Q.string())});import{EventEmitter as aq}from"events";class U0 extends Error{pluginId;constructor($,X){super(`Plugin ${$}: ${X}`);this.name="PluginError",this.pluginId=$}}class o9{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=o1(J);throw this.logger.error(`Error initializing plugin ${$}: ${V}`),Y.status="error",Y.error=Y6(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=Y6(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: ${o1(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 n9{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=o1(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 s9{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 aq;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 aq,this.daemonRegistry=X,this.pluginLifecycle=new o9(this.plugins,this.events,this.daemonRegistry,$),this.dependencyResolver=new n9(this.plugins,this.events,$),this.capabilityRegistrar=new s9($)}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{R5 as UserPermissionLevelSchema,rq as UnregisterRoutesPayloadSchema,c9 as RouteDefinitionSchema,cq as RegisterRoutesPayloadSchema,d9 as NavigationSlots,iq as ListRoutesPayloadSchema,oq as GetRoutePayloadSchema};
170
170
 
171
- //# debugId=136581DBE1F4652D64756E2164756E21
171
+ //# debugId=6FA3FE9A150231BB64756E2164756E21
172
172
  //# sourceMappingURL=interfaces.js.map