@rizom/brain 0.2.0-alpha.56 → 0.2.0-alpha.58

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- function t(i){return i}var e={name:"@rizom/brain",version:"0.2.0-alpha.56",description:"Brain runtime + CLI \u2014 scaffold, run, and manage AI brain instances",type:"module",bin:{brain:"./dist/brain.js"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./cli":"./dist/brain.js","./plugins":{types:"./dist/plugins.d.ts",import:"./dist/plugins.js"},"./entities":{types:"./dist/entities.d.ts",import:"./dist/entities.js"},"./services":{types:"./dist/services.d.ts",import:"./dist/services.js"},"./interfaces":{types:"./dist/interfaces.d.ts",import:"./dist/interfaces.js"},"./templates":{types:"./dist/templates.d.ts",import:"./dist/templates.js"},"./site":{types:"./dist/site.d.ts",import:"./dist/site.js"},"./themes":{types:"./dist/themes.d.ts",import:"./dist/themes.js"},"./deploy":{types:"./dist/deploy.d.ts",import:"./dist/deploy.js"},"./tsconfig.instance.json":"./tsconfig.instance.json"},files:["dist","templates","tsconfig.instance.json"],scripts:{build:"bun scripts/build.ts",prepublishOnly:"bun scripts/build.ts","dev:start":"bun dist/brain.js start",typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts"},dependencies:{"@clack/prompts":"^0.11.0","@modelcontextprotocol/sdk":"^1.24.0","@tailwindcss/postcss":"^4.1.13","@tailwindcss/typography":"^0.5.19",postcss:"^8.5.6",preact:"^10.27.2","preact-render-to-string":"^6.3.1",tailwindcss:"^4.1.11"},optionalDependencies:{"@bitwarden/sdk-napi":"^1.0.0","@libsql/client":"^0.15.7","@tailwindcss/oxide":"^4.1.4","better-sqlite3":"^11.8.1",lightningcss:"^1.29.2","react-devtools-core":"^6.1.1",sharp:"^0.34.5"},devDependencies:{"@brains/app":"workspace:*","@brains/deploy-templates":"workspace:*","@brains/eslint-config":"workspace:*","@brains/mcp-service":"workspace:*","@brains/plugins":"workspace:*","@brains/ranger":"workspace:*","@brains/relay":"workspace:*","@brains/rover":"workspace:*","@brains/site-composition":"workspace:*","@brains/site-default":"workspace:*","@brains/site-personal":"workspace:*","@brains/site-professional":"workspace:*","@brains/theme-default":"workspace:*","@brains/theme-rizom":"workspace:*","@brains/typescript-config":"workspace:*","@brains/utils":"workspace:*","@types/bun":"latest",rollup:"^4.60.2","rollup-plugin-dts":"^6.4.1",typescript:"^5.3.3"},publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/rizom-ai/brains.git",directory:"packages/brain-cli"},license:"Apache-2.0",author:"Yeehaa <yeehaa@rizom.ai> (https://rizom.ai)",homepage:"https://github.com/rizom-ai/brains/tree/main/packages/brain-cli#readme",bugs:"https://github.com/rizom-ai/brains/issues",engines:{bun:">=1.3.3"},keywords:["brain","ai","cli","mcp","agent","personal-ai","knowledge-management"]};var n=e.version;export{t as defineBrain,n as PLUGIN_API_VERSION};
2
+ function t(i){return i}var e={name:"@rizom/brain",version:"0.2.0-alpha.58",description:"Brain runtime + CLI \u2014 scaffold, run, and manage AI brain instances",type:"module",bin:{brain:"./dist/brain.js"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./cli":"./dist/brain.js","./plugins":{types:"./dist/plugins.d.ts",import:"./dist/plugins.js"},"./entities":{types:"./dist/entities.d.ts",import:"./dist/entities.js"},"./services":{types:"./dist/services.d.ts",import:"./dist/services.js"},"./interfaces":{types:"./dist/interfaces.d.ts",import:"./dist/interfaces.js"},"./templates":{types:"./dist/templates.d.ts",import:"./dist/templates.js"},"./site":{types:"./dist/site.d.ts",import:"./dist/site.js"},"./themes":{types:"./dist/themes.d.ts",import:"./dist/themes.js"},"./deploy":{types:"./dist/deploy.d.ts",import:"./dist/deploy.js"},"./tsconfig.instance.json":"./tsconfig.instance.json"},files:["dist","templates","tsconfig.instance.json"],scripts:{build:"bun scripts/build.ts",prepublishOnly:"bun scripts/build.ts","dev:start":"bun dist/brain.js start",typecheck:"tsc --noEmit",test:"bun test",lint:"eslint . --ext .ts"},dependencies:{"@clack/prompts":"^0.11.0","@modelcontextprotocol/sdk":"^1.24.0","@tailwindcss/postcss":"^4.1.13","@tailwindcss/typography":"^0.5.19",postcss:"^8.5.6",preact:"^10.27.2","preact-render-to-string":"^6.3.1",tailwindcss:"^4.1.11"},optionalDependencies:{"@bitwarden/sdk-napi":"^1.0.0","@libsql/client":"^0.15.7","@tailwindcss/oxide":"^4.1.4","better-sqlite3":"^11.8.1",lightningcss:"^1.29.2","react-devtools-core":"^6.1.1",sharp:"^0.34.5"},devDependencies:{"@brains/app":"workspace:*","@brains/deploy-templates":"workspace:*","@brains/eslint-config":"workspace:*","@brains/mcp-service":"workspace:*","@brains/plugins":"workspace:*","@brains/ranger":"workspace:*","@brains/relay":"workspace:*","@brains/rover":"workspace:*","@brains/site-composition":"workspace:*","@brains/site-default":"workspace:*","@brains/site-personal":"workspace:*","@brains/site-professional":"workspace:*","@brains/theme-default":"workspace:*","@brains/theme-rizom":"workspace:*","@brains/typescript-config":"workspace:*","@brains/utils":"workspace:*","@types/bun":"latest",rollup:"^4.60.2","rollup-plugin-dts":"^6.4.1",typescript:"^5.3.3"},publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/rizom-ai/brains.git",directory:"packages/brain-cli"},license:"Apache-2.0",author:"Yeehaa <yeehaa@rizom.ai> (https://rizom.ai)",homepage:"https://github.com/rizom-ai/brains/tree/main/packages/brain-cli#readme",bugs:"https://github.com/rizom-ai/brains/issues",engines:{bun:">=1.3.3"},keywords:["brain","ai","cli","mcp","agent","personal-ai","knowledge-management"]};var n=e.version;export{t as defineBrain,n as PLUGIN_API_VERSION};
3
3
 
4
- //# debugId=DEB211E3DD98F4CC64756E2164756E21
4
+ //# debugId=A56EEB13D5C0DF3264756E2164756E21
5
5
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -6,6 +6,6 @@
6
6
  "import packageJson from \"../package.json\" with { type: \"json\" };\n\n/**\n * Pre-v1 external plugin API marker.\n *\n * During alpha, the external plugin API compatibility marker tracks the\n * published @rizom/brain package version. Once the plugin API is declared\n * stable, this can move to an independent semver contract such as 1.0.0.\n */\nexport const PLUGIN_API_VERSION = packageJson.version;\n"
7
7
  ],
8
8
  "mappings": ";AAkEO,SAAS,CAAW,CAAC,EAA8C,CACxE,OAAO,moFC1DF,IAAM,EAAqB,EAAY",
9
- "debugId": "DEB211E3DD98F4CC64756E2164756E21",
9
+ "debugId": "A56EEB13D5C0DF3264756E2164756E21",
10
10
  "names": []
11
11
  }
package/dist/plugins.js CHANGED
@@ -166,7 +166,7 @@ Please report this to https://github.com/markedjs/marked.`,$){let Y="<p>An error
166
166
  `}format($){try{let G=[`# ${this.config.title}`,""];for(let X of this.config.mappings)this.formatField($,X,G,2);return G.join(`
167
167
  `)}catch{throw Error("Failed to format structured content")}}parse($){try{let G=this.processor.parse($),X=this.extractSections(G,2),Y=this.buildDataFromSections(X,this.config.mappings);return this.schema.parse(Y)}catch{throw Error("Failed to parse structured content")}}formatField($,G,X,Y){let q="#".repeat(Y)+" "+G.label,V=this.getValueByPath($,G.key);if(G.type==="custom"&&G.formatter){if(V!==void 0&&V!==null){X.push(q,"");let W=G.formatter(V);if(W)X.push(W,"")}return}switch(G.type){case"string":case"number":X.push(q,String(V??""),"");break;case"object":if(X.push(q),G.children&&V)for(let W of G.children)this.formatField(V,W,X,Y+1);break;case"array":if(X.push(q,""),Array.isArray(V))if(G.itemType==="object"&&G.itemMappings)V.forEach((W,J)=>{if(X.push(`${"#".repeat(Y+1)} ${G.label.slice(0,-1)} ${J+1}`),X.push(""),G.itemMappings)for(let H of G.itemMappings)this.formatField(W,H,X,Y+2)});else{for(let W of V){let J=this.defaultArrayItemFormat(W);X.push(`- ${J}`)}X.push("")}break}}getValueByPath($,G){let X=G.split("."),Y=$;for(let q of X)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($,G){let X=new Map,Y=null,q=[];for(let V of $.children)if(V.type==="heading"&&V.depth===G){if(Y)X.set(Y.toLowerCase(),q);Y=this.getHeadingText(V),q=[]}else if(Y)q.push(V);if(Y)X.set(Y.toLowerCase(),q);return X}extractSubsections($,G){let X=new Map,Y=null,q=[];for(let V of $)if(V.type==="heading"&&V.depth===G){if(Y)X.set(Y.toLowerCase(),q);Y=this.getHeadingText(V),q=[]}else if(Y)q.push(V);if(Y)X.set(Y.toLowerCase(),q);return X}textNodeSchema=R.object({type:R.literal("text"),value:R.string()});extractTextValue($){let G=this.textNodeSchema.safeParse($);return G.success?G.data.value:""}getHeadingText($){return $.children.filter((X)=>X.type==="text").map((X)=>this.extractTextValue(X)).join("")}buildDataFromSections($,G,X=2){let Y={};for(let q of G){let V=$.get(q.label.toLowerCase());if(q.type==="custom"&&q.parser&&V){let W=this.getTextFromSection(V),J=q.parser(W);this.setValueByPath(Y,q.key,J)}else if(q.type==="object"&&q.children&&V){let W=this.extractSubsections(V,X+1),J=this.buildDataFromSections(W,q.children,X+1);this.setValueByPath(Y,q.key,J)}else if(q.type==="array"&&V)if(q.itemType==="object"&&q.itemMappings){let W=this.extractObjectArrayItems(V,X+1,q.itemMappings);this.setValueByPath(Y,q.key,W)}else{let W=this.extractSimpleArrayItems(V);this.setValueByPath(Y,q.key,W)}else if(V){let W=this.getTextFromSection(V),J=q.type==="number"?Number(W):W;this.setValueByPath(Y,q.key,J)}}return Y}setValueByPath($,G,X){let Y=G.split("."),q=$;for(let W=0;W<Y.length-1;W++){let J=Y[W];if(!J)continue;if(!(J in q))q[J]={};q=q[J]}let V=Y[Y.length-1];if(V)q[V]=X}getTextFromSection($){let G=[];for(let X of $)if(X.type==="paragraph"){let Y=this.extractTextFromParagraph(X);if(Y)G.push(Y)}else if(X.type==="list"){let Y=X;for(let q of Y.children){let V=this.extractTextFromListItem(q);if(V)G.push(`- ${V}`)}}return G.join(`
168
168
  `)}extractTextFromParagraph($){return this.extractInlineText($.children).trim()}extractInlineText($){let G=[];for(let X of $)if(X.type==="text")G.push(this.extractTextValue(X));else if(X.type==="emphasis"){let Y=this.extractInlineText(X.children);if(Y)G.push(`*${Y}*`)}else if(X.type==="strong"){let Y=this.extractInlineText(X.children);if(Y)G.push(`**${Y}**`)}return G.join("")}extractSimpleArrayItems($){let G=[];for(let X of $)if(X.type==="list"){let Y=X;for(let q of Y.children){let V=this.extractTextFromListItem(q);if(V)G.push(V)}}return G}extractObjectArrayItems($,G,X){let Y=[],q=[],V=!1;for(let W of $)if(W.type==="heading"&&W.depth===G){if(V&&q.length>0){let J=this.extractSubsections(q,G+1),H=this.buildDataFromSections(J,X,G+1);Y.push(H)}q=[],V=!0}else if(V)q.push(W);if(V&&q.length>0){let W=this.extractSubsections(q,G+1),J=this.buildDataFromSections(W,X,G+1);Y.push(J)}return Y}extractTextFromListItem($){let G=[];for(let X of $.children)if(X.type==="paragraph"){let Y=this.extractTextFromParagraph(X);if(Y)G.push(Y)}return G.join(`
169
- `)}}var XS=R.object({slug:R.string(),title:R.string(),type:R.string(),entityId:R.string(),contentHash:R.string()});import{webcrypto as EY}from"crypto";var _Y="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var fA=128,B2,W4;function mA($){if(!B2||B2.length<$)B2=Buffer.allocUnsafe($*fA),EY.getRandomValues(B2),W4=0;else if(W4+$>B2.length)EY.getRandomValues(B2),W4=0;W4+=$}function jY($=21){mA($|=0);let G="";for(let X=W4-$;X<W4;X++)G+=_Y[B2[X]&63];return G}function z2($=12){return jY($)}function w9($){let G=$.trim().replace(/^https?:\/\//,""),X=G.split(".").filter(Boolean);if(X.length>=3){let[Y,...q]=X;if(!Y||q.length===0)return`preview.${G}`;return`${Y}-preview.${q.join(".")}`}return`preview.${G}`}function V0($){return $ instanceof Error?$.message:String($)}var pA=R.object({success:R.boolean(),entityId:R.string().optional(),error:R.string().optional()});function dA($){return $}function iA($){return $}function cA($){return $===void 0?{success:!0}:{success:!0,data:$}}function nA($){return{success:!1,error:$}}var oA=R.object({captureUrls:R.boolean().default(!1),blockedUrlDomains:R.array(R.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"])});function sA($,G){return{name:$,schema:G}}var aA=R.object({status:R.enum(["healthy","warning","error","unknown"]),message:R.string().optional(),lastCheck:R.date().optional(),details:R.record(R.string(),R.unknown()).optional()}),CY=R.object({name:R.string(),pluginId:R.string(),status:R.string(),health:aA.optional()});var O9=R.enum(["anchor","trusted","public"]);var tA=R.object({name:R.string(),description:R.string(),schema:R.any(),basePrompt:R.string().optional(),useKnowledgeContext:R.boolean().optional(),requiredPermission:O9,formatter:R.any().optional(),layout:R.object({component:R.any(),fullscreen:R.boolean().optional()}).optional(),dataSourceId:R.string().optional()});class a4{static canGenerate($){return!!$.basePrompt&&!!$.dataSourceId&&$.dataSourceId.includes("ai-content")}static canFetch($){return!!$.dataSourceId&&!this.canGenerate($)}static canRender($){return!!$.layout?.component}static isStaticOnly($){return!this.canGenerate($)&&!this.canFetch($)}static getCapabilities($){return{canGenerate:this.canGenerate($),canFetch:this.canFetch($),canRender:this.canRender($),isStaticOnly:this.isStaticOnly($)}}static validate($){let G=[];if($.dataSourceId?.includes("ai-content")&&!$.basePrompt)G.push(`Template "${$.name}" has AI-content dataSourceId but no basePrompt. AI generation requires a basePrompt.`);if($.basePrompt&&(!$.dataSourceId||!$.dataSourceId.includes("ai-content")))G.push(`Template "${$.name}" has basePrompt but no AI-content dataSourceId. The basePrompt won't be used.`);return G}static logCapabilities($,G){let X=this.getCapabilities($),Y=this.validate($);if(G)G.debug(`Template capabilities for "${$.name}":`,{...X,errors:Y.length>0?Y:void 0})}}var eA=R.enum(["site-content-preview","site-content-production"]),$B=R.object({name:R.string(),schema:R.any(),description:R.string().optional(),pluginId:R.string(),renderers:R.object({web:R.union([R.function(),R.string()]).optional()})}),GB=R.object({enableContentGeneration:R.boolean().default(!1),outputDir:R.string(),workingDir:R.string().optional(),environment:R.enum(["preview","production"]).default("preview"),siteConfig:R.object({title:R.string(),description:R.string(),url:R.string().optional()}).optional()}),XB=R.object({success:R.boolean(),routesBuilt:R.number(),errors:R.array(R.string()).optional(),warnings:R.array(R.string()).optional()});import{McpServer as uI,ResourceTemplate as pI}from"@modelcontextprotocol/sdk/server/mcp.js";var M6=R.object({interfaceType:R.string(),userId:R.string(),channelId:R.string().optional(),channelName:R.string().optional()}),SY=R.object({success:R.literal(!0),data:R.unknown(),message:R.string().optional()}),TY=R.object({success:R.literal(!1),error:R.string(),code:R.string().optional()}),IY=R.object({needsConfirmation:R.literal(!0),toolName:R.string(),description:R.string(),args:R.unknown()}),vY=R.union([SY,TY,IY]);var qB=R.union([R.object({success:R.literal(!0),data:R.unknown(),message:R.string().optional()}),R.object({success:R.literal(!1),error:R.string(),code:R.string().optional()})]);var Ov=R.object({id:R.string(),type:R.string(),version:R.string(),status:R.string()}),Nv=R.object({name:R.string(),description:R.string()}),VB=R.object({label:R.string(),url:R.string(),pluginId:R.string(),priority:R.number().default(100)}),Pv=R.object({model:R.string(),version:R.string(),uptime:R.number(),entities:R.number(),embeddings:R.number(),ai:R.object({model:R.string(),embeddingModel:R.string()}),daemons:R.array(CY),endpoints:R.array(VB)});var Zv=R.object({id:R.string(),version:R.string(),type:R.enum(["core","entity","service","interface"]),description:R.string().optional(),dependencies:R.array(R.string()).optional(),packageName:R.string()});var WB=R.object({toolName:R.string(),args:R.unknown(),progressToken:R.union([R.string(),R.number()]).optional(),hasProgress:R.boolean().optional(),...M6.shape}),JB=R.object({resourceUri:R.string()});class w2{id;version;description;packageName;config;context;get logger(){return this.context?.logger??L1.createFresh({context:this.id})}constructor($,G,X,Y){this.id=$,this.packageName=G.name,this.version=G.version,this.description=G.description??`${G.name} plugin`,this.config=Y.parse(X)}setupMessageHandlers($){$.messaging.subscribe(`plugin:${this.id}:tool:execute`,async(G)=>{try{let{toolName:X,args:Y,progressToken:q,hasProgress:V,interfaceType:W,userId:J,channelId:H}=WB.parse(G.payload),D=(await this.getTools()).find((F)=>F.name===X);if(!D)return{success:!1,error:`Tool not found: ${X}`};let M={interfaceType:W,userId:J,...H&&{channelId:H},...V&&q!==void 0&&{progressToken:q,sendProgress:async(F)=>{await $.messaging.send({type:`plugin:${this.id}:progress`,payload:{progressToken:q,notification:F}})}}};return{success:!0,data:await D.handler(Y,M)}}catch(X){if(X instanceof R.ZodError)return{success:!1,error:"Invalid tool execution request format"};return this.logger.error("Tool execution error",X),{success:!1,error:V0(X)}}}),$.messaging.subscribe(`plugin:${this.id}:resource:get`,async(G)=>{try{let{resourceUri:X}=JB.parse(G.payload),q=(await this.getResources()).find((W)=>W.uri===X);if(!q)return{success:!1,error:`Resource not found: ${X}`};return{success:!0,data:await q.handler()}}catch(X){if(X instanceof R.ZodError)return{success:!1,error:"Invalid resource get request format"};return this.logger.error("Resource fetch error",X),{success:!1,error:V0(X)}}})}async onRegister($){}async onReady($){}async ready(){await this.onReady(this.getContext())}async getCapabilities(){let $=await this.getInstructions();return{tools:await this.getTools(),resources:await this.getResources(),...$&&{instructions:$}}}async getTools(){return[]}async getResources(){return[]}async getInstructions(){return}async shutdown(){await this.onShutdown()}async onShutdown(){}getContext(){if(!this.context)throw Error(`Plugin ${this.id}: Plugin not registered yet`);return this.context}determineUserPermissionLevel($){return"public"}createProgressBridge($){if(!$)return;let G=this.context;if(!G)return;let X=this.id;return m0.from(async(Y)=>{await G.messaging.send({type:`plugin:${X}:progress`,payload:{progressToken:$,notification:{progress:Y.progress,total:Y.total,message:Y.message}}})})}}var bY=R.enum(["file_operations","content_operations","data_processing","batch_processing"]),xY=R.object({pluginId:R.string().optional(),progressToken:R.union([R.string(),R.number()]).optional(),operationType:bY,operationTarget:R.string().optional(),interfaceType:R.string().optional(),channelId:R.string().optional()}),t4=xY.extend({rootJobId:R.string()}),Iv=R.enum(["none","skip","replace","coalesce"]);var N9=R.enum(["pending","processing","completed","failed"]),gY=R.enum(["completed","failed"]);var HB=R.object({id:R.string(),type:R.string(),status:N9,data:R.unknown(),result:R.unknown().optional(),lastError:R.string().optional().nullable(),attempts:R.number(),maxRetries:R.number(),priority:R.number(),createdAt:R.date(),updatedAt:R.date(),processedAt:R.date().optional().nullable(),completedAt:R.date().optional().nullable(),failedAt:R.date().optional().nullable()}),UB=R.object({jobId:R.string(),type:R.string(),status:gY,result:R.unknown().optional(),error:R.string().optional()}),hY=R.object({success:R.literal(!1),error:R.string().optional()}),P9=R.object({id:R.string(),type:R.enum(["job","batch"]),status:N9,message:R.string().optional(),progress:R.object({current:R.number(),total:R.number(),percentage:R.number()}).optional(),aggregationKey:R.string().optional(),batchDetails:R.object({totalOperations:R.number(),completedOperations:R.number(),failedOperations:R.number(),currentOperation:R.string().optional(),errors:R.array(R.string()).optional()}).optional(),jobDetails:R.object({jobType:R.string(),priority:R.number(),retryCount:R.number()}).optional(),metadata:t4});import{createClient as Ox}from"@libsql/client";var v=Symbol.for("drizzle:entityKind");function h1($,G){if(!$||typeof $!=="object")return!1;if($ instanceof G)return!0;if(!Object.prototype.hasOwnProperty.call(G,v))throw Error(`Class "${G.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 X=Object.getPrototypeOf($).constructor;if(X)while(X){if(v in X&&X[v]===G[v])return!0;X=Object.getPrototypeOf(X)}return!1}class r0{constructor($,G){this.table=$,this.config=G,this.name=G.name,this.keyAsName=G.keyAsName,this.notNull=G.notNull,this.default=G.default,this.defaultFn=G.defaultFn,this.onUpdateFn=G.onUpdateFn,this.hasDefault=G.hasDefault,this.primary=G.primaryKey,this.isUnique=G.isUnique,this.uniqueName=G.uniqueName,this.uniqueType=G.uniqueType,this.dataType=G.dataType,this.columnType=G.columnType,this.generated=G.generated,this.generatedIdentity=G.generatedIdentity}static[v]="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 Z9{static[v]="ColumnBuilder";config;constructor($,G,X){this.config={name:$,keyAsName:$==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:G,columnType:X,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 W0=Symbol.for("drizzle:Name");function kY($,...G){return $(...G)}function yY($,G){return`${$[W0]}_${G.join("_")}_unique`}class e4 extends r0{constructor($,G){if(!G.uniqueName)G.uniqueName=yY($,[G.name]);super($,G);this.table=$}static[v]="PgColumn"}class DB extends e4{static[v]="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 MB extends e4{static[v]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor($,G){super($,G);this.enum=G.enum}getSQLType(){return this.enum.enumName}}var fY=Symbol.for("drizzle:isPgEnum");function mY($){return!!$&&typeof $==="function"&&fY in $&&$[fY]===!0}class RB extends e4{static[v]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor($,G){super($,G);this.enum=G.enum}getSQLType(){return this.enum.enumName}}class R6{static[v]="Subquery";constructor($,G,X,Y=!1,q=[]){this._={brand:"Subquery",sql:$,selectedFields:G,alias:X,isWith:Y,usedTables:q}}}var uY="0.44.7";var L9,_9,pY={startActiveSpan($,G){if(!L9)return G();if(!_9)_9=L9.trace.getTracer("drizzle-orm",uY);return kY((X,Y)=>Y.startActiveSpan($,(q)=>{try{return G(q)}catch(V){throw q.setStatus({code:X.SpanStatusCode.ERROR,message:V instanceof Error?V.message:"Unknown error"}),V}finally{q.end()}}),L9,_9)}};var J4=Symbol.for("drizzle:ViewBaseConfig");var E9=Symbol.for("drizzle:Schema"),lY=Symbol.for("drizzle:Columns"),rY=Symbol.for("drizzle:ExtraConfigColumns"),j9=Symbol.for("drizzle:OriginalName"),C9=Symbol.for("drizzle:BaseName"),$5=Symbol.for("drizzle:IsAlias"),dY=Symbol.for("drizzle:ExtraConfigBuilder"),QB=Symbol.for("drizzle:IsDrizzleTable");class K1{static[v]="Table";static Symbol={Name:W0,Schema:E9,OriginalName:j9,Columns:lY,ExtraConfigColumns:rY,BaseName:C9,IsAlias:$5,ExtraConfigBuilder:dY};[W0];[j9];[E9];[lY];[rY];[C9];[$5]=!1;[QB]=!0;[dY]=void 0;constructor($,G,X){this[W0]=this[j9]=$,this[E9]=G,this[C9]=X}}function KB($){return $!==null&&$!==void 0&&typeof $.getSQL==="function"}function FB($){let G={sql:"",params:[]};for(let X of $)if(G.sql+=X.sql,G.params.push(...X.params),X.typings?.length){if(!G.typings)G.typings=[];G.typings.push(...X.typings)}return G}class t1{static[v]="StringChunk";value;constructor($){this.value=Array.isArray($)?$:[$]}getSQL(){return new F1([this])}}class F1{constructor($){this.queryChunks=$;for(let G of $)if(h1(G,K1)){let X=G[K1.Symbol.Schema];this.usedTables.push(X===void 0?G[K1.Symbol.Name]:X+"."+G[K1.Symbol.Name])}}static[v]="SQL";decoder=iY;shouldInlineParams=!1;usedTables=[];append($){return this.queryChunks.push(...$.queryChunks),this}toQuery($){return pY.startActiveSpan("drizzle.buildSQL",(G)=>{let X=this.buildQueryFromSourceParams(this.queryChunks,$);return G?.setAttributes({"drizzle.query.text":X.sql,"drizzle.query.params":JSON.stringify(X.params)}),X})}buildQueryFromSourceParams($,G){let X=Object.assign({},G,{inlineParams:G.inlineParams||this.shouldInlineParams,paramStartIndex:G.paramStartIndex||{value:0}}),{casing:Y,escapeName:q,escapeParam:V,prepareTyping:W,inlineParams:J,paramStartIndex:H}=X;return FB($.map((U)=>{if(h1(U,t1))return{sql:U.value.join(""),params:[]};if(h1(U,Q6))return{sql:q(U.value),params:[]};if(U===void 0)return{sql:"",params:[]};if(Array.isArray(U)){let D=[new t1("(")];for(let[M,A]of U.entries())if(D.push(A),M<U.length-1)D.push(new t1(", "));return D.push(new t1(")")),this.buildQueryFromSourceParams(D,X)}if(h1(U,F1))return this.buildQueryFromSourceParams(U.queryChunks,{...X,inlineParams:J||U.shouldInlineParams});if(h1(U,K1)){let D=U[K1.Symbol.Schema],M=U[K1.Symbol.Name];return{sql:D===void 0||U[$5]?q(M):q(D)+"."+q(M),params:[]}}if(h1(U,r0)){let D=Y.getColumnCasing(U);if(G.invokeSource==="indexes")return{sql:q(D),params:[]};let M=U.table[K1.Symbol.Schema];return{sql:U.table[$5]||M===void 0?q(U.table[K1.Symbol.Name])+"."+q(D):q(M)+"."+q(U.table[K1.Symbol.Name])+"."+q(D),params:[]}}if(h1(U,nY)){let D=U[J4].schema,M=U[J4].name;return{sql:D===void 0||U[J4].isAlias?q(M):q(D)+"."+q(M),params:[]}}if(h1(U,S9)){if(h1(U.value,K6))return{sql:V(H.value++,U),params:[U],typings:["none"]};let D=U.value===null?null:U.encoder.mapToDriverValue(U.value);if(h1(D,F1))return this.buildQueryFromSourceParams([D],X);if(J)return{sql:this.mapInlineParam(D,X),params:[]};let M=["none"];if(W)M=[W(U.encoder)];return{sql:V(H.value++,D),params:[D],typings:M}}if(h1(U,K6))return{sql:V(H.value++,U),params:[U],typings:["none"]};if(h1(U,F1.Aliased)&&U.fieldAlias!==void 0)return{sql:q(U.fieldAlias),params:[]};if(h1(U,R6)){if(U._.isWith)return{sql:q(U._.alias),params:[]};return this.buildQueryFromSourceParams([new t1("("),U._.sql,new t1(") "),new Q6(U._.alias)],X)}if(mY(U)){if(U.schema)return{sql:q(U.schema)+"."+q(U.enumName),params:[]};return{sql:q(U.enumName),params:[]}}if(KB(U)){if(U.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([U.getSQL()],X);return this.buildQueryFromSourceParams([new t1("("),U.getSQL(),new t1(")")],X)}if(J)return{sql:this.mapInlineParam(U,X),params:[]};return{sql:V(H.value++,U),params:[U],typings:["none"]}}))}mapInlineParam($,{escapeString:G}){if($===null)return"null";if(typeof $==="number"||typeof $==="boolean")return $.toString();if(typeof $==="string")return G($);if(typeof $==="object"){let X=$.toString();if(X==="[object Object]")return G(JSON.stringify($));return G(X)}throw Error("Unexpected param value: "+$)}getSQL(){return this}as($){if($===void 0)return this;return new F1.Aliased(this,$)}mapWith($){return this.decoder=typeof $==="function"?{mapFromDriverValue:$}:$,this}inlineParams(){return this.shouldInlineParams=!0,this}if($){return $?this:void 0}}class Q6{constructor($){this.value=$}static[v]="Name";brand;getSQL(){return new F1([this])}}var iY={mapFromDriverValue:($)=>$},cY={mapToDriverValue:($)=>$},Ab={...iY,...cY};class S9{constructor($,G=cY){this.value=$,this.encoder=G}static[v]="Param";brand;getSQL(){return new F1([this])}}function H4($,...G){let X=[];if(G.length>0||$.length>0&&$[0]!=="")X.push(new t1($[0]));for(let[Y,q]of G.entries())X.push(q,new t1($[Y+1]));return new F1(X)}(($)=>{function G(){return new F1([])}$.empty=G;function X(H){return new F1(H)}$.fromList=X;function Y(H){return new F1([new t1(H)])}$.raw=Y;function q(H,U){let D=[];for(let[M,A]of H.entries()){if(M>0&&U!==void 0)D.push(U);D.push(A)}return new F1(D)}$.join=q;function V(H){return new Q6(H)}$.identifier=V;function W(H){return new K6(H)}$.placeholder=W;function J(H,U){return new S9(H,U)}$.param=J})(H4||(H4={}));(($)=>{class G{constructor(X,Y){this.sql=X,this.fieldAlias=Y}static[v]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new G(this.sql,this.fieldAlias)}}$.Aliased=G})(F1||(F1={}));class K6{constructor($){this.name=$}static[v]="Placeholder";getSQL(){return new F1([this])}}var AB=Symbol.for("drizzle:IsDrizzleView");class nY{static[v]="View";[J4];[AB]=!0;constructor({name:$,schema:G,selectedFields:X,query:Y}){this[J4]={name:$,originalName:$,schema:G,selectedFields:X,query:Y,isExisting:!Y,isAlias:!1}}getSQL(){return new F1([this])}}r0.prototype.getSQL=function(){return new F1([this])};K1.prototype.getSQL=function(){return new F1([this])};R6.prototype.getSQL=function(){return new F1([this])};function F0($,G){return{name:typeof $==="string"&&$.length>0?$:"",config:typeof $==="object"?$:G}}var T9=typeof TextDecoder>"u"?null:new TextDecoder;class I9{static[v]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor($,G){if(this.reference=()=>{let{name:X,columns:Y,foreignColumns:q}=$();return{name:X,columns:Y,foreignTable:q[0].table,foreignColumns:q}},G)this._onUpdate=G.onUpdate,this._onDelete=G.onDelete}onUpdate($){return this._onUpdate=$,this}onDelete($){return this._onDelete=$,this}build($){return new oY($,this)}}class oY{constructor($,G){this.table=$,this.reference=G.reference,this.onUpdate=G._onUpdate,this.onDelete=G._onDelete}static[v]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:$,columns:G,foreignColumns:X}=this.reference(),Y=G.map((W)=>W.name),q=X.map((W)=>W.name),V=[this.table[W0],...Y,X[0].table[W0],...q];return $??`${V.join("_")}_fk`}}function sY($,G){return`${$[W0]}_${G.join("_")}_unique`}class N1 extends Z9{static[v]="SQLiteColumnBuilder";foreignKeyConfigs=[];references($,G={}){return this.foreignKeyConfigs.push({ref:$,actions:G}),this}unique($){return this.config.isUnique=!0,this.config.uniqueName=$,this}generatedAlwaysAs($,G){return this.config.generated={as:$,type:"always",mode:G?.mode??"virtual"},this}buildForeignKeys($,G){return this.foreignKeyConfigs.map(({ref:X,actions:Y})=>{return((q,V)=>{let W=new I9(()=>{let J=q();return{columns:[$],foreignColumns:[J]}});if(V.onUpdate)W.onUpdate(V.onUpdate);if(V.onDelete)W.onDelete(V.onDelete);return W.build(G)})(X,Y)})}}class P1 extends r0{constructor($,G){if(!G.uniqueName)G.uniqueName=sY($,[G.name]);super($,G);this.table=$}static[v]="SQLiteColumn"}class aY extends N1{static[v]="SQLiteBigIntBuilder";constructor($){super($,"bigint","SQLiteBigInt")}build($){return new tY($,this.config)}}class tY extends P1{static[v]="SQLiteBigInt";getSQLType(){return"blob"}mapFromDriverValue($){if(typeof Buffer<"u"&&Buffer.from){let G=Buffer.isBuffer($)?$:$ instanceof ArrayBuffer?Buffer.from($):$.buffer?Buffer.from($.buffer,$.byteOffset,$.byteLength):Buffer.from($);return BigInt(G.toString("utf8"))}return BigInt(T9.decode($))}mapToDriverValue($){return Buffer.from($.toString())}}class eY extends N1{static[v]="SQLiteBlobJsonBuilder";constructor($){super($,"json","SQLiteBlobJson")}build($){return new $q($,this.config)}}class $q extends P1{static[v]="SQLiteBlobJson";getSQLType(){return"blob"}mapFromDriverValue($){if(typeof Buffer<"u"&&Buffer.from){let G=Buffer.isBuffer($)?$:$ instanceof ArrayBuffer?Buffer.from($):$.buffer?Buffer.from($.buffer,$.byteOffset,$.byteLength):Buffer.from($);return JSON.parse(G.toString("utf8"))}return JSON.parse(T9.decode($))}mapToDriverValue($){return Buffer.from(JSON.stringify($))}}class Gq extends N1{static[v]="SQLiteBlobBufferBuilder";constructor($){super($,"buffer","SQLiteBlobBuffer")}build($){return new Xq($,this.config)}}class Xq extends P1{static[v]="SQLiteBlobBuffer";mapFromDriverValue($){if(Buffer.isBuffer($))return $;return Buffer.from($)}getSQLType(){return"blob"}}function Yq($,G){let{name:X,config:Y}=F0($,G);if(Y?.mode==="json")return new eY(X);if(Y?.mode==="bigint")return new aY(X);return new Gq(X)}class qq extends N1{static[v]="SQLiteCustomColumnBuilder";constructor($,G,X){super($,"custom","SQLiteCustomColumn");this.config.fieldConfig=G,this.config.customTypeParams=X}build($){return new Vq($,this.config)}}class Vq extends P1{static[v]="SQLiteCustomColumn";sqlName;mapTo;mapFrom;constructor($,G){super($,G);this.sqlName=G.customTypeParams.dataType(G.fieldConfig),this.mapTo=G.customTypeParams.toDriver,this.mapFrom=G.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue($){return typeof this.mapFrom==="function"?this.mapFrom($):$}mapToDriverValue($){return typeof this.mapTo==="function"?this.mapTo($):$}}function F6($){return(G,X)=>{let{name:Y,config:q}=F0(G,X);return new qq(Y,q,$)}}class A6 extends N1{static[v]="SQLiteBaseIntegerBuilder";constructor($,G,X){super($,G,X);this.config.autoIncrement=!1}primaryKey($){if($?.autoIncrement)this.config.autoIncrement=!0;return this.config.hasDefault=!0,super.primaryKey()}}class B6 extends P1{static[v]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}}class Wq extends A6{static[v]="SQLiteIntegerBuilder";constructor($){super($,"number","SQLiteInteger")}build($){return new Jq($,this.config)}}class Jq extends B6{static[v]="SQLiteInteger"}class Hq extends A6{static[v]="SQLiteTimestampBuilder";constructor($,G){super($,"date","SQLiteTimestamp");this.config.mode=G}defaultNow(){return this.default(H4`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build($){return new Uq($,this.config)}}class Uq extends B6{static[v]="SQLiteTimestamp";mode=this.config.mode;mapFromDriverValue($){if(this.config.mode==="timestamp")return new Date($*1000);return new Date($)}mapToDriverValue($){let G=$.getTime();if(this.config.mode==="timestamp")return Math.floor(G/1000);return G}}class Dq extends A6{static[v]="SQLiteBooleanBuilder";constructor($,G){super($,"boolean","SQLiteBoolean");this.config.mode=G}build($){return new Mq($,this.config)}}class Mq extends B6{static[v]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue($){return Number($)===1}mapToDriverValue($){return $?1:0}}function c1($,G){let{name:X,config:Y}=F0($,G);if(Y?.mode==="timestamp"||Y?.mode==="timestamp_ms")return new Hq(X,Y.mode);if(Y?.mode==="boolean")return new Dq(X,Y.mode);return new Wq(X)}class Rq extends N1{static[v]="SQLiteNumericBuilder";constructor($){super($,"string","SQLiteNumeric")}build($){return new Qq($,this.config)}}class Qq extends P1{static[v]="SQLiteNumeric";mapFromDriverValue($){if(typeof $==="string")return $;return String($)}getSQLType(){return"numeric"}}class Kq extends N1{static[v]="SQLiteNumericNumberBuilder";constructor($){super($,"number","SQLiteNumericNumber")}build($){return new Fq($,this.config)}}class Fq extends P1{static[v]="SQLiteNumericNumber";mapFromDriverValue($){if(typeof $==="number")return $;return Number($)}mapToDriverValue=String;getSQLType(){return"numeric"}}class Aq extends N1{static[v]="SQLiteNumericBigIntBuilder";constructor($){super($,"bigint","SQLiteNumericBigInt")}build($){return new Bq($,this.config)}}class Bq extends P1{static[v]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}function zq($,G){let{name:X,config:Y}=F0($,G),q=Y?.mode;return q==="number"?new Kq(X):q==="bigint"?new Aq(X):new Rq(X)}class wq extends N1{static[v]="SQLiteRealBuilder";constructor($){super($,"number","SQLiteReal")}build($){return new Oq($,this.config)}}class Oq extends P1{static[v]="SQLiteReal";getSQLType(){return"real"}}function Nq($){return new wq($??"")}class Pq extends N1{static[v]="SQLiteTextBuilder";constructor($,G){super($,"string","SQLiteText");this.config.enumValues=G.enum,this.config.length=G.length}build($){return new Zq($,this.config)}}class Zq extends P1{static[v]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor($,G){super($,G)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}}class Lq extends N1{static[v]="SQLiteTextJsonBuilder";constructor($){super($,"json","SQLiteTextJson")}build($){return new _q($,this.config)}}class _q extends P1{static[v]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue($){return JSON.parse($)}mapToDriverValue($){return JSON.stringify($)}}function M1($,G={}){let{name:X,config:Y}=F0($,G);if(Y.mode==="json")return new Lq(X);return new Pq(X,Y)}function Eq(){return{blob:Yq,customType:F6,integer:c1,numeric:zq,real:Nq,text:M1}}var v9=Symbol.for("drizzle:SQLiteInlineForeignKeys");class G5 extends K1{static[v]="SQLiteTable";static Symbol=Object.assign({},K1.Symbol,{InlineForeignKeys:v9});[K1.Symbol.Columns];[v9]=[];[K1.Symbol.ExtraConfigBuilder]=void 0}function BB($,G,X,Y,q=$){let V=new G5($,Y,q),W=typeof G==="function"?G(Eq()):G,J=Object.fromEntries(Object.entries(W).map(([U,D])=>{let M=D;M.setName(U);let A=M.build(V);return V[v9].push(...M.buildForeignKeys(A,V)),[U,A]})),H=Object.assign(V,J);if(H[K1.Symbol.Columns]=J,H[K1.Symbol.ExtraConfigColumns]=J,X)H[G5.Symbol.ExtraConfigBuilder]=X;return H}var U4=($,G,X)=>{return BB($,G,X)};class jq{constructor($,G){this.name=$,this.unique=G}static[v]="SQLiteIndexBuilderOn";on(...$){return new Cq(this.name,$,this.unique)}}class Cq{static[v]="SQLiteIndexBuilder";config;constructor($,G,X){this.config={name:$,columns:G,unique:X,where:void 0}}where($){return this.config.where=$,this}build($){return new Sq(this.config,$)}}class Sq{static[v]="SQLiteIndex";config;constructor($,G){this.config={...$,table:G}}}function z6($){return new jq($,!1)}function w6(...$){if($[0].columns)return new b9($[0].columns,$[0].name);return new b9($)}class b9{static[v]="SQLitePrimaryKeyBuilder";columns;name;constructor($,G){this.columns=$,this.name=G}build($){return new Tq($,this.columns,this.name)}}class Tq{constructor($,G,X){this.table=$,this.columns=G,this.name=X}static[v]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[G5.Symbol.Name]}_${this.columns.map(($)=>$.name).join("_")}_pk`}}var Iq=U4("job_queue",{id:M1("id").primaryKey().$defaultFn(()=>z2()),type:M1("type").notNull(),data:M1("data").notNull(),result:M1("result",{mode:"json"}),source:M1("source"),metadata:M1("metadata",{mode:"json"}).$type().notNull(),status:M1("status",{enum:["pending","processing","completed","failed"]}).notNull().default("pending"),priority:c1("priority").notNull().default(0),retryCount:c1("retryCount").notNull().default(0),maxRetries:c1("maxRetries").notNull().default(3),lastError:M1("lastError"),createdAt:c1("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:c1("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:c1("startedAt"),completedAt:c1("completedAt")},($)=>({queueReadyIdx:z6("idx_job_queue_ready").on($.status,$.priority,$.scheduledFor),jobTypeIdx:z6("idx_job_queue_type").on($.type,$.status),jobSourceIdx:z6("idx_job_queue_source").on($.source)}));var zB=R.object({id:R.string(),type:R.string(),data:R.string(),status:R.enum(["pending","processing","completed","failed"]),source:R.string().nullable(),priority:R.number(),retryCount:R.number(),maxRetries:R.number(),lastError:R.string().nullable(),createdAt:R.number(),scheduledFor:R.number(),startedAt:R.number().nullable(),completedAt:R.number().nullable(),metadata:t4,result:R.unknown().nullable().optional()});function x9($,G,X){return async(Y)=>{let{type:q,data:V,toolContext:W=null,options:J}=Y,{metadata:H,...U}=J??{},D={source:G,...J?.rootJobId&&{rootJobId:J.rootJobId},...U,metadata:{operationType:"data_processing",pluginId:G,...W&&{interfaceType:W.interfaceType,channelId:W.channelId},...H}},M=X&&!q.includes(":")?`${G}:${q}`:q;return $.enqueue({type:M,data:V,options:D})}}function g9($,G){return async(X,Y)=>{let q=z2(),V=X.map((J)=>({...J,type:J.type.includes(":")?J.type:`${G}:${J.type}`})),W={...Y,source:G,rootJobId:q,metadata:{...Y?.metadata,operationType:"batch_processing",pluginId:G}};return await $.enqueueBatch(V,W,q,G),q}}function h9($,G){return(X,Y)=>{let q=X.includes(":")?X:`${G}:${X}`;$.registerHandler(q,Y,G)}}var wB=R.object({name:R.string(),schema:R.custom(($)=>$ instanceof R.ZodType)});function vq($){return wB.safeParse($).success}function OB($){if(!$)return;return{status:$.status,message:$.message,lastCheck:$.lastCheck?.toISOString(),details:$.details}}function bq($){return{model:$.model,version:$.version,uptime:$.uptime,entities:$.entities,embeddings:$.embeddings,ai:$.ai,daemons:$.daemons.map((G)=>({name:G.name,pluginId:G.pluginId,status:G.status,health:OB(G.health)})),endpoints:$.endpoints}}var D4=R.record(R.unknown());var NB=R.object({id:R.string(),sessionId:R.string(),interfaceType:R.string(),channelId:R.string(),channelName:R.string().optional(),startedAt:R.string(),lastActiveAt:R.string(),createdAt:R.string(),updatedAt:R.string(),metadata:D4}),k9=R.enum(["user","assistant","system"]),PB=R.object({id:R.string(),conversationId:R.string(),role:k9,content:R.string(),timestamp:R.string(),metadata:D4});function xq($){if(!$)return{};try{let G=JSON.parse($);if(G&&typeof G==="object"&&!Array.isArray(G))return G}catch{}return{}}function ZB($){let G=k9.safeParse($);return G.success?G.data:"user"}function O6($){let G=xq($.metadata),X=typeof G.channelName==="string"?G.channelName:void 0;return{id:$.id,sessionId:$.sessionId,interfaceType:$.interfaceType,channelId:$.channelId,channelName:X,startedAt:$.started,lastActiveAt:$.lastActive,createdAt:$.created,updatedAt:$.updated,metadata:G}}function gq($){return{id:$.id,conversationId:$.conversationId,role:ZB($.role),content:$.content,timestamp:$.timestamp,metadata:xq($.metadata)}}var y9=R.object({name:R.string(),role:R.string(),purpose:R.string(),values:R.array(R.string())}),f9=R.object({name:R.string(),kind:R.enum(["professional","team","collective"]),organization:R.string().optional(),description:R.string().optional(),avatar:R.string().optional(),website:R.string().optional(),email:R.string().optional(),socialLinks:R.array(R.object({platform:R.enum(["github","instagram","linkedin","email","website"]),url:R.string(),label:R.string().optional()})).optional()});function hq($){return y9.parse($)}function kq($){return f9.parse($)}function yq($){return async()=>{return bq(await $.getAppInfo())}}function fq($,G){return{get:()=>hq($.getIdentity()),getProfile:()=>kq($.getProfile()),getAppInfo:G}}function mq($,G,X){let Y=$.getMessageBus();return{send:async(V)=>{return Y.send({...V,sender:G})},subscribe:(V,W)=>{if(vq(V)){let J=V,H=W,U=async(D)=>{let M=J.schema.safeParse(D.payload);if(!M.success)return X.warn(`Invalid payload for channel ${J.name}`,{error:M.error.message}),{noop:!0};let{payload:A,...F}=D;return H(M.data,F)};return Y.subscribe(J.name,U)}return Y.subscribe(V,W)}}}function uq($,G){let X=$.getJobQueueService();return{...$.jobs,enqueue:x9(X,G,!0),enqueueBatch:g9($.jobs,G),registerHandler:h9(X,G)}}function pq($){return{get:async(G)=>{let Y=await $.getConversationService().getConversation(G);return Y?O6(Y):null},search:async(G)=>{return(await $.getConversationService().searchConversations(G)).map(O6)},list:async(G)=>{return(await $.getConversationService().listConversations(G)).map(O6)},getMessages:async(G,X)=>{return(await $.getConversationService().getMessages(G,X)).map(gq)},countMessages:async(G)=>{return $.getConversationService().countMessages(G)}}}function lq($,G){return{registerHandler:(X,Y)=>{$.registerEvalHandler(G,X,Y)}}}function rq($){return{register:(G,X)=>{$.getInsightsRegistry().register(G,X)}}}function dq($,G){return{register:({label:X,url:Y,priority:q=100})=>{$.registerEndpoint({label:X,url:Y,pluginId:G,priority:q})}}}function M4($,G,X){let Y=$.getEntityService(),q=$.getLogger().child(G),V=$.getDomain(),W=yq($);return{pluginId:G,logger:q,entityService:Y,identity:fq($,W),appInfo:W,domain:V,siteUrl:V?`https://${V}`:void 0,previewUrl:V?`https://${w9(V)}`:void 0,entityDisplay:X?.entityDisplay,messaging:mq($,G,q),jobs:uq($,G),conversations:pq($),dataDir:$.getDataDir(),eval:lq($,G),insights:rq($),endpoints:dq($,G)}}import{createClient as rg}from"@libsql/client";var N6=U4("entities",{id:M1("id").notNull(),entityType:M1("entityType").notNull(),content:M1("content").notNull(),contentHash:M1("contentHash").notNull(),metadata:M1("metadata",{mode:"json"}).$type().notNull().default(H4`'{}'`),created:c1("created").notNull().$defaultFn(()=>Date.now()),updated:c1("updated").notNull().$defaultFn(()=>Date.now())},($)=>{return{pk:w6({columns:[$.id,$.entityType]})}});import{createClient as eg}from"@libsql/client";var iq=F6({dataType(){return"F32_BLOB(1536)"},toDriver($){return Buffer.from($.buffer)},fromDriver($){return new Float32Array($.buffer,$.byteOffset,$.byteLength/4)}});var P6=U4("embeddings",{entityId:M1("entity_id").notNull(),entityType:M1("entity_type").notNull(),embedding:iq("embedding").notNull(),contentHash:M1("content_hash").notNull()},($)=>{return{pk:w6({columns:[$.entityId,$.entityType]})}});var qh=R.object({id:R.string().min(1,"Entity ID is required"),entityType:R.string().min(1,"Entity type is required"),contentHash:R.string().min(1,"Content hash is required"),operation:R.enum(["create","update"])});var Hh=R.object({limit:R.number().int().positive().optional().default(20),offset:R.number().int().min(0).optional().default(0),types:R.array(R.string()).optional().default([]),excludeTypes:R.array(R.string()).optional().default([]),weight:R.record(R.string(),R.number()).optional()});var LB=R.object({field:R.string(),direction:R.enum(["asc","desc"]),nullsFirst:R.boolean().optional()}),zh=R.object({limit:R.number().int().positive().optional(),offset:R.number().int().min(0).optional().default(0),sortFields:R.array(LB).optional(),filter:R.object({metadata:R.record(R.string(),R.unknown()).optional()}).optional(),publishedOnly:R.boolean().optional()});var u9=J5($8(),1);function Z6($,G){if(Object.keys(G).length===0)return $;let X=Object.fromEntries(Object.entries(G).filter(([,Y])=>Y!==void 0));return u9.default.stringify($,X)}function m9($){if($ instanceof Date)return $.toISOString();if(Array.isArray($))return $.map(m9);if($!==null&&typeof $==="object"){let G={};for(let[X,Y]of Object.entries($))G[X]=m9(Y);return G}return $}function Y5($,G){let{content:X,data:Y}=u9.default($),q=m9(Y);return{content:X.trim(),metadata:G.parse(q)}}var cq=R.object({id:R.string(),entityType:R.string(),content:R.string(),created:R.string().datetime(),updated:R.string().datetime(),metadata:R.record(R.string(),R.unknown()),contentHash:R.string()});var gB=R.object({currentPage:R.number(),totalPages:R.number(),totalItems:R.number(),pageSize:R.number(),hasNextPage:R.boolean(),hasPrevPage:R.boolean()});function hB($){return $.replace(/:/g,"-")}function kB($){return $.split(/[:.-]/).map((G)=>G.charAt(0).toUpperCase()+G.slice(1)).join(" ")}var p9=new Map;async function oq($,G,X){let Y=p9.get(G);if(Y!==void 0)return Y;let q=hB(G),V;try{V=await $.getEntity({entityType:"prompt",id:q})}catch{return X}if(V?.content){let W=Y5(V.content,R.record(R.unknown())).content;return p9.set(G,W),W}try{let W=kB(G),J=Z6(X,{title:W,target:G});await $.createEntity({entity:{id:q,entityType:"prompt",content:J,metadata:{title:W,target:G,slug:q}}})}catch{}return p9.set(G,X),X}function L6($){let G=$.getEntityService(),X=$.getEntityRegistry(),Y=$.getDataSourceRegistry();return{register:(q,V,W,J)=>{X.registerEntityType(q,V,W,J)},getAdapter:(q)=>{try{return X.getAdapter(q)}catch{return}},extendFrontmatterSchema:(q,V)=>{X.extendFrontmatterSchema(q,V)},getEffectiveFrontmatterSchema:(q)=>{return X.getEffectiveFrontmatterSchema(q)},registerCreateInterceptor:(q,V)=>{X.registerCreateInterceptor(q,V)},update:async(q)=>{return G.updateEntity({entity:q})},registerDataSource:(q)=>{Y.register(q)}}}function _6($){return{resolve:(G,X)=>{return oq($,G,X)}}}function sq($,G,X){let Y=M4($,G,X),q=$.getEntityService();return{...Y,entityService:q,entities:L6($),ai:{query:(V,W)=>$.query(V,W),generate:async(V)=>{return $.generateContent(V)},generateObject:async(V,W)=>{return $.generateObject(V,W)},generateImage:async(V,W)=>{return $.generateImage(V,W)},canGenerateImages:()=>{return $.canGenerateImages()}},prompts:_6(q)}}function tq($,G,X){let Y=!1,q=!1;if($.jobs.registerHandler(X.job.type,X.job.handler),X.initialSync){let V=X.initialSync;$.messaging.subscribe("sync:initial:completed",async()=>{if(Y)return{success:!0};if(Y=!0,!(await V.shouldEnqueue?.()??!0))return G.info("Skipping derived entity projection initial sync",{projectionId:X.id,targetType:X.targetType}),{success:!0};return q=await aq($,G,X,V.jobData,fB(V.jobOptions),"initial-sync"),{success:!0}})}if(X.sourceChange){let V=X.sourceChange,W=new Set(V.sourceTypes),J=V.events??["entity:created","entity:updated"],H=async(U)=>{if(V.requireInitialSync&&!Y)return{success:!0};let D=U.payload,M=yB(V,D);if(!M||!W.has("*")&&!W.has(M))return{success:!0};if(!(await V.shouldEnqueue?.(D)??!0))return{success:!0};let F=await V.jobData(D);if(!F)return{success:!0};return await aq($,G,X,F,V.jobOptions?.(D),"source-change"),{success:!0}};for(let U of J)$.messaging.subscribe(U,H)}return{hasObservedInitialSync:()=>Y,hasQueuedInitialSync:()=>q}}function yB($,G){if($.sourceType)return $.sourceType;if($.sourceKind&&$.sourceKind!=="entity")return $.sourceKind;return G.entityType}async function aq($,G,X,Y,q,V){try{return await $.jobs.enqueue({type:X.job.type,data:Y,...q?{options:q}:{}}),G.info("Queued derived entity projection",{projectionId:X.id,targetType:X.targetType,reason:V}),!0}catch(W){return G.error("Failed to queue derived entity projection",{projectionId:X.id,targetType:X.targetType,reason:V,error:V0(W)}),!1}}function fB($){return typeof $==="function"?$():$}var mB=R.object({});class E6 extends w2{type="entity";derivedEntityProjectionControllers=new Map;constructor($,G,X={},Y=mB){super($,G,X,Y)}async register($,G){let X=sq($,this.id,G);if(this.context=X,this.setupMessageHandlers(X),X.entities.register(this.entityType,this.schema,this.adapter,this.getEntityTypeConfig()),this.interceptCreate!==E6.prototype.interceptCreate)X.entities.registerCreateInterceptor(this.entityType,(H,U)=>this.interceptCreate(H,U,X));let Y=this.createGenerationHandler(X);if(Y)X.jobs.registerHandler(`${this.entityType}:generation`,Y);let q=this.getTemplates();if(q&&Object.keys(q).length>0)$.registerTemplates(q,this.id);let V=this.getDataSources();for(let H of V)X.entities.registerDataSource(H);let W=this.getDerivedEntityProjections(X);for(let H of W){let U=tq(X,this.logger,H);this.derivedEntityProjectionControllers.set(H.id,U)}await this.onRegister(this.context);let J=await this.getInstructions();return{tools:[],resources:[],...J&&{instructions:J}}}async interceptCreate($,G,X){return{kind:"continue",input:$}}createGenerationHandler($){return null}getTemplates(){return null}getDataSources(){return[]}getEntityTypeConfig(){return}getDerivedEntityProjections($){return[]}getDerivedEntityProjectionController($){return this.derivedEntityProjectionControllers.get($)}}class eq extends E6{hooks;constructor($,G,X,Y,q){super($,G,X,Y);this.hooks=q}get entityType(){return this.hooks.getEntityType()}get schema(){return this.hooks.getSchema()}get adapter(){return this.hooks.getAdapter()}onRegister($){return this.hooks.onRegister($)}onReady($){return this.hooks.onReady($)}onShutdown(){return this.hooks.onShutdown()}getEntityTypeConfig(){return this.hooks.getEntityTypeConfig()}getDataSources(){return this.hooks.getDataSources()}getInstructions(){return this.hooks.getInstructions()}interceptCreate($,G,X){return this.hooks.interceptCreate($,G,X)}}class l9{type="entity";id;version;packageName;description;delegate;constructor($,G,X,Y){if(this.id=$,this.version=G.version,this.packageName=G.name,G.description!==void 0)this.description=G.description;this.delegate=new eq($,G,X,Y,{getEntityType:()=>this.entityType,getSchema:()=>this.schema,getAdapter:()=>this.adapter,onRegister:(q)=>this.onRegister(q),onReady:(q)=>this.onReady(q),onShutdown:()=>this.onShutdown(),getEntityTypeConfig:()=>this.getEntityTypeConfig(),getDataSources:()=>this.getDataSources(),getInstructions:()=>this.getInstructions(),interceptCreate:(q,V,W)=>this.interceptCreate(q,V,W)})}register($,G){return this.delegate.register($,G)}async onRegister($){}async onReady($){}async onShutdown(){}async getInstructions(){return}getEntityTypeConfig(){return}getDataSources(){return[]}async interceptCreate($,G,X){return{kind:"continue",input:$}}ready(){return this.delegate.ready()}shutdown(){return this.delegate.shutdown?.()??Promise.resolve()}}function $V($){return{text:$.text,...$.toolResults&&{toolResults:$.toolResults.map((G)=>({toolName:G.toolName,...G.args&&{args:G.args},...G.jobId!==void 0&&{jobId:G.jobId},...G.data!==void 0&&{data:G.data}}))},...$.pendingConfirmation&&{pendingConfirmation:{toolName:$.pendingConfirmation.toolName,description:$.pendingConfirmation.description,args:$.pendingConfirmation.args}},usage:$.usage}}function uB($){if(!$)return;return{...$.userPermissionLevel&&{userPermissionLevel:$.userPermissionLevel},...$.interfaceType&&{interfaceType:$.interfaceType},...$.channelId&&{channelId:$.channelId},...$.channelName&&{channelName:$.channelName}}}function GV($){return{chat:async(G,X,Y)=>{return $V(await $.chat(G,X,uB(Y)))},confirmPendingAction:async(G,X)=>{return $V(await $.confirmPendingAction(G,X))},invalidate:()=>{$.invalidateAgent()}}}function XV($,G,X){let Y=M4($,G,X),q=$.getMCPService(),V=$.getPermissionService(),W=GV($.getAgentService());return{...Y,mcpTransport:q,agent:W,permissions:{getUserLevel:(J,H)=>{return V.determineUserLevel(J,H)}},daemons:{register:(J,H)=>{let U=`${G}:${J}`;$.registerDaemon(U,H,G),Y.logger.debug(`Registered daemon: ${U}`)}},conversations:{...Y.conversations,start:async(J)=>{return $.getConversationService().startConversation(J)},addMessage:async(J)=>{await $.getConversationService().addMessage(J)}},tools:{listForPermissionLevel:(J)=>{return $.listToolsForPermissionLevel(J)}},apiRoutes:{getRoutes:()=>{return $.getPluginApiRoutes()},getMessageBus:()=>{return $.getMessageBus()}},webRoutes:{getRoutes:()=>{return $.getPluginWebRoutes()}},plugins:{has:(J)=>$.hasPlugin(J)}}}var pB=3600000;class q5 extends w2{type="interface";daemon;jobTrackingEntries=new Map;jobTrackingTtlMs=pB;async register($,G){let X=XV($,this.id,G);if(this.context=X,this.initializeDaemon(),this.daemon)await this.registerDaemon(X);return this.setupMessageHandlers(X),await this.onRegister(X),this.getCapabilities()}async onRegister($){}async registerDaemon($){if(!this.daemon)return;$.daemons.register(this.id,this.daemon),$.logger.debug(`Registered daemon for interface: ${this.id}`)}createDaemon(){return}requiresDaemonStartup(){return!1}getWebRoutes(){return[]}initializeDaemon(){let $=this.createDaemon();if($)this.daemon=$}async handleProgressEvent($,G){}cleanupExpiredEntries(){let $=Date.now(),G=[];for(let[X,Y]of this.jobTrackingEntries)if($-Y.createdAt>this.jobTrackingTtlMs)G.push(X);for(let X of G)this.jobTrackingEntries.delete(X)}ownsJob($,G){return this.jobTrackingEntries.has($)||G!==void 0&&this.jobTrackingEntries.has(G)}getJobTracking($,G){let X=this.jobTrackingEntries.get($);if(X)return X.info;if(G){let Y=this.jobTrackingEntries.get(G);if(Y)return Y.info}return}setJobTracking($,G){this.cleanupExpiredEntries(),this.jobTrackingEntries.set($,{info:G,createdAt:Date.now()})}removeJobTracking($){this.jobTrackingEntries.delete($)}async createJobWithTracking($,G){let Y=await this.getContext().jobs.enqueue($);return this.setJobTracking(Y,G),Y}async createBatchWithTracking($,G,X){let q=await this.getContext().jobs.enqueueBatch($,X);return this.setJobTracking(q,G),q}}class YV extends q5{hooks;constructor($,G,X,Y,q){super($,G,X,Y);this.hooks=q}onRegister($){return this.hooks.onRegister($)}onReady($){return this.hooks.onReady($)}onShutdown(){return this.hooks.onShutdown()}getTools(){return this.hooks.getTools()}getResources(){return this.hooks.getResources()}getInstructions(){return this.hooks.getInstructions()}getWebRoutes(){return this.hooks.getWebRoutes()}requiresDaemonStartup(){return this.hooks.requiresDaemonStartup()}}class V5{type="interface";id;version;packageName;description;delegate;constructor($,G,X,Y){if(this.id=$,this.version=G.version,this.packageName=G.name,G.description!==void 0)this.description=G.description;this.delegate=new YV($,G,X,Y,{onRegister:(q)=>this.onRegister(q),onReady:(q)=>this.onReady(q),onShutdown:()=>this.onShutdown(),getTools:()=>this.getTools(),getResources:()=>this.getResources(),getInstructions:()=>this.getInstructions(),getWebRoutes:()=>this.getWebRoutes(),requiresDaemonStartup:()=>this.requiresDaemonStartup()})}register($,G){return this.delegate.register($,G)}async onRegister($){}async onReady($){}async onShutdown(){}async getTools(){return[]}async getResources(){return[]}async getInstructions(){return}getWebRoutes(){return[]}requiresDaemonStartup(){return!1}ready(){return this.delegate.ready()}shutdown(){return this.delegate.shutdown?.()??Promise.resolve()}}function qV($,G){$.messaging.subscribe("job-progress",async(X)=>{try{let Y=P9.safeParse(X.payload);if(!Y.success)return G.onInvalidSchema(),{success:!1};let q=Y.data;return await G.onProgress(q,q.metadata),{success:!0}}catch(Y){return G.onError(Y),{success:!1}}})}function VV($){let G=$.status==="completed"?"\u2705":"\u274C",X=$.status==="completed"?"completed":"failed",Y=$.metadata.operationType.replace(/_/g," "),q=$.metadata.operationTarget?`: ${$.metadata.operationTarget}`:"",V=`${G} **${Y}${q}** ${X}`;if($.message)V+=`
169
+ `)}}var XS=R.object({slug:R.string(),title:R.string(),type:R.string(),entityId:R.string(),contentHash:R.string()});import{webcrypto as EY}from"crypto";var _Y="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict";var fA=128,B2,W4;function mA($){if(!B2||B2.length<$)B2=Buffer.allocUnsafe($*fA),EY.getRandomValues(B2),W4=0;else if(W4+$>B2.length)EY.getRandomValues(B2),W4=0;W4+=$}function jY($=21){mA($|=0);let G="";for(let X=W4-$;X<W4;X++)G+=_Y[B2[X]&63];return G}function z2($=12){return jY($)}function w9($){let G=$.trim().replace(/^https?:\/\//,""),X=G.split(".").filter(Boolean);if(X.length>=3){let[Y,...q]=X;if(!Y||q.length===0)return`preview.${G}`;return`${Y}-preview.${q.join(".")}`}return`preview.${G}`}function V0($){return $ instanceof Error?$.message:String($)}var pA=R.object({success:R.boolean(),entityId:R.string().optional(),error:R.string().optional()});function dA($){return $}function iA($){return $}function cA($){return $===void 0?{success:!0}:{success:!0,data:$}}function nA($){return{success:!1,error:$}}var oA=R.object({captureUrls:R.boolean().default(!1),blockedUrlDomains:R.array(R.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"])});function sA($,G){return{name:$,schema:G}}var aA=R.object({status:R.enum(["healthy","warning","error","unknown"]),message:R.string().optional(),lastCheck:R.date().optional(),details:R.record(R.string(),R.unknown()).optional()}),CY=R.object({name:R.string(),pluginId:R.string(),status:R.string(),health:aA.optional()});var O9=R.enum(["anchor","trusted","public"]);var tA=R.object({name:R.string(),description:R.string(),schema:R.any(),basePrompt:R.string().optional(),useKnowledgeContext:R.boolean().optional(),requiredPermission:O9,formatter:R.any().optional(),layout:R.object({component:R.any(),fullscreen:R.boolean().optional()}).optional(),dataSourceId:R.string().optional()});class a4{static canGenerate($){return!!$.basePrompt&&!!$.dataSourceId&&$.dataSourceId.includes("ai-content")}static canFetch($){return!!$.dataSourceId&&!this.canGenerate($)}static canRender($){return!!$.layout?.component}static isStaticOnly($){return!this.canGenerate($)&&!this.canFetch($)}static getCapabilities($){return{canGenerate:this.canGenerate($),canFetch:this.canFetch($),canRender:this.canRender($),isStaticOnly:this.isStaticOnly($)}}static validate($){let G=[];if($.dataSourceId?.includes("ai-content")&&!$.basePrompt)G.push(`Template "${$.name}" has AI-content dataSourceId but no basePrompt. AI generation requires a basePrompt.`);if($.basePrompt&&(!$.dataSourceId||!$.dataSourceId.includes("ai-content")))G.push(`Template "${$.name}" has basePrompt but no AI-content dataSourceId. The basePrompt won't be used.`);return G}static logCapabilities($,G){let X=this.getCapabilities($),Y=this.validate($);if(G)G.debug(`Template capabilities for "${$.name}":`,{...X,errors:Y.length>0?Y:void 0})}}var eA=R.enum(["site-content-preview","site-content-production"]),$B=R.object({name:R.string(),schema:R.any(),description:R.string().optional(),pluginId:R.string(),renderers:R.object({web:R.union([R.function(),R.string()]).optional()})}),GB=R.object({enableContentGeneration:R.boolean().default(!1),outputDir:R.string(),workingDir:R.string().optional(),environment:R.enum(["preview","production"]).default("preview"),siteConfig:R.object({title:R.string(),description:R.string(),url:R.string().optional()}).optional()}),XB=R.object({success:R.boolean(),routesBuilt:R.number(),errors:R.array(R.string()).optional(),warnings:R.array(R.string()).optional()});import{McpServer as uI,ResourceTemplate as pI}from"@modelcontextprotocol/sdk/server/mcp.js";var M6=R.object({interfaceType:R.string(),userId:R.string(),channelId:R.string().optional(),channelName:R.string().optional()}),SY=R.object({success:R.literal(!0),data:R.unknown(),message:R.string().optional()}),TY=R.object({success:R.literal(!1),error:R.string(),code:R.string().optional()}),IY=R.object({needsConfirmation:R.literal(!0),toolName:R.string(),description:R.string(),args:R.unknown()}),vY=R.union([SY,TY,IY]);var qB=R.union([R.object({success:R.literal(!0),data:R.unknown(),message:R.string().optional()}),R.object({success:R.literal(!1),error:R.string(),code:R.string().optional()})]);var Ov=R.object({id:R.string(),type:R.string(),version:R.string(),status:R.string()}),Nv=R.object({name:R.string(),description:R.string()}),VB=R.object({label:R.string(),url:R.string(),pluginId:R.string(),priority:R.number().default(100)}),Pv=R.object({model:R.string(),version:R.string(),uptime:R.number(),entities:R.number(),embeddings:R.number(),ai:R.object({model:R.string(),embeddingModel:R.string()}),daemons:R.array(CY),endpoints:R.array(VB)});var Zv=R.object({id:R.string(),version:R.string(),type:R.enum(["core","entity","service","interface"]),description:R.string().optional(),dependencies:R.array(R.string()).optional(),packageName:R.string()});var WB=R.object({toolName:R.string(),args:R.unknown(),progressToken:R.union([R.string(),R.number()]).optional(),hasProgress:R.boolean().optional(),...M6.shape}),JB=R.object({resourceUri:R.string()});class w2{id;version;description;packageName;config;context;get logger(){return this.context?.logger??L1.createFresh({context:this.id})}constructor($,G,X,Y){this.id=$,this.packageName=G.name,this.version=G.version,this.description=G.description??`${G.name} plugin`,this.config=Y.parse(X)}setupMessageHandlers($){$.messaging.subscribe(`plugin:${this.id}:tool:execute`,async(G)=>{try{let{toolName:X,args:Y,progressToken:q,hasProgress:V,interfaceType:W,userId:J,channelId:H}=WB.parse(G.payload),D=(await this.getTools()).find((F)=>F.name===X);if(!D)return{success:!1,error:`Tool not found: ${X}`};let M={interfaceType:W,userId:J,...H&&{channelId:H},...V&&q!==void 0&&{progressToken:q,sendProgress:async(F)=>{await $.messaging.send({type:`plugin:${this.id}:progress`,payload:{progressToken:q,notification:F}})}}};return{success:!0,data:await D.handler(Y,M)}}catch(X){if(X instanceof R.ZodError)return{success:!1,error:"Invalid tool execution request format"};return this.logger.error("Tool execution error",X),{success:!1,error:V0(X)}}}),$.messaging.subscribe(`plugin:${this.id}:resource:get`,async(G)=>{try{let{resourceUri:X}=JB.parse(G.payload),q=(await this.getResources()).find((W)=>W.uri===X);if(!q)return{success:!1,error:`Resource not found: ${X}`};return{success:!0,data:await q.handler()}}catch(X){if(X instanceof R.ZodError)return{success:!1,error:"Invalid resource get request format"};return this.logger.error("Resource fetch error",X),{success:!1,error:V0(X)}}})}async onRegister($){}async onReady($){}async ready(){await this.onReady(this.getContext())}async getCapabilities(){let $=await this.getInstructions();return{tools:await this.getTools(),resources:await this.getResources(),...$&&{instructions:$}}}async getTools(){return[]}async getResources(){return[]}async getInstructions(){return}async shutdown(){await this.onShutdown()}async onShutdown(){}getContext(){if(!this.context)throw Error(`Plugin ${this.id}: Plugin not registered yet`);return this.context}determineUserPermissionLevel($){return"public"}createProgressBridge($){if(!$)return;let G=this.context;if(!G)return;let X=this.id;return m0.from(async(Y)=>{await G.messaging.send({type:`plugin:${X}:progress`,payload:{progressToken:$,notification:{progress:Y.progress,total:Y.total,message:Y.message}}})})}}var bY=R.enum(["file_operations","content_operations","data_processing","batch_processing"]),xY=R.object({pluginId:R.string().optional(),progressToken:R.union([R.string(),R.number()]).optional(),operationType:bY,operationTarget:R.string().optional(),interfaceType:R.string().optional(),channelId:R.string().optional()}),t4=xY.extend({rootJobId:R.string()}),Iv=R.enum(["none","skip","replace","coalesce"]);var N9=R.enum(["pending","processing","completed","failed"]),gY=R.enum(["completed","failed"]);var HB=R.object({id:R.string(),type:R.string(),status:N9,data:R.unknown(),result:R.unknown().optional(),lastError:R.string().optional().nullable(),attempts:R.number(),maxRetries:R.number(),priority:R.number(),createdAt:R.date(),updatedAt:R.date(),processedAt:R.date().optional().nullable(),completedAt:R.date().optional().nullable(),failedAt:R.date().optional().nullable()}),UB=R.object({jobId:R.string(),type:R.string(),status:gY,result:R.unknown().optional(),error:R.string().optional()}),hY=R.object({success:R.literal(!1),error:R.string().optional()}),P9=R.object({id:R.string(),type:R.enum(["job","batch"]),status:N9,message:R.string().optional(),progress:R.object({current:R.number(),total:R.number(),percentage:R.number()}).optional(),aggregationKey:R.string().optional(),batchDetails:R.object({totalOperations:R.number(),completedOperations:R.number(),failedOperations:R.number(),currentOperation:R.string().optional(),errors:R.array(R.string()).optional()}).optional(),jobDetails:R.object({jobType:R.string(),priority:R.number(),retryCount:R.number()}).optional(),metadata:t4});import{createClient as Ox}from"@libsql/client";var v=Symbol.for("drizzle:entityKind");function h1($,G){if(!$||typeof $!=="object")return!1;if($ instanceof G)return!0;if(!Object.prototype.hasOwnProperty.call(G,v))throw Error(`Class "${G.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 X=Object.getPrototypeOf($).constructor;if(X)while(X){if(v in X&&X[v]===G[v])return!0;X=Object.getPrototypeOf(X)}return!1}class r0{constructor($,G){this.table=$,this.config=G,this.name=G.name,this.keyAsName=G.keyAsName,this.notNull=G.notNull,this.default=G.default,this.defaultFn=G.defaultFn,this.onUpdateFn=G.onUpdateFn,this.hasDefault=G.hasDefault,this.primary=G.primaryKey,this.isUnique=G.isUnique,this.uniqueName=G.uniqueName,this.uniqueType=G.uniqueType,this.dataType=G.dataType,this.columnType=G.columnType,this.generated=G.generated,this.generatedIdentity=G.generatedIdentity}static[v]="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 Z9{static[v]="ColumnBuilder";config;constructor($,G,X){this.config={name:$,keyAsName:$==="",notNull:!1,default:void 0,hasDefault:!1,primaryKey:!1,isUnique:!1,uniqueName:void 0,uniqueType:void 0,dataType:G,columnType:X,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 W0=Symbol.for("drizzle:Name");function kY($,...G){return $(...G)}function yY($,G){return`${$[W0]}_${G.join("_")}_unique`}class e4 extends r0{constructor($,G){if(!G.uniqueName)G.uniqueName=yY($,[G.name]);super($,G);this.table=$}static[v]="PgColumn"}class DB extends e4{static[v]="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 MB extends e4{static[v]="PgEnumObjectColumn";enum;enumValues=this.config.enum.enumValues;constructor($,G){super($,G);this.enum=G.enum}getSQLType(){return this.enum.enumName}}var fY=Symbol.for("drizzle:isPgEnum");function mY($){return!!$&&typeof $==="function"&&fY in $&&$[fY]===!0}class RB extends e4{static[v]="PgEnumColumn";enum=this.config.enum;enumValues=this.config.enum.enumValues;constructor($,G){super($,G);this.enum=G.enum}getSQLType(){return this.enum.enumName}}class R6{static[v]="Subquery";constructor($,G,X,Y=!1,q=[]){this._={brand:"Subquery",sql:$,selectedFields:G,alias:X,isWith:Y,usedTables:q}}}var uY="0.44.7";var L9,_9,pY={startActiveSpan($,G){if(!L9)return G();if(!_9)_9=L9.trace.getTracer("drizzle-orm",uY);return kY((X,Y)=>Y.startActiveSpan($,(q)=>{try{return G(q)}catch(V){throw q.setStatus({code:X.SpanStatusCode.ERROR,message:V instanceof Error?V.message:"Unknown error"}),V}finally{q.end()}}),L9,_9)}};var J4=Symbol.for("drizzle:ViewBaseConfig");var E9=Symbol.for("drizzle:Schema"),lY=Symbol.for("drizzle:Columns"),rY=Symbol.for("drizzle:ExtraConfigColumns"),j9=Symbol.for("drizzle:OriginalName"),C9=Symbol.for("drizzle:BaseName"),$5=Symbol.for("drizzle:IsAlias"),dY=Symbol.for("drizzle:ExtraConfigBuilder"),QB=Symbol.for("drizzle:IsDrizzleTable");class K1{static[v]="Table";static Symbol={Name:W0,Schema:E9,OriginalName:j9,Columns:lY,ExtraConfigColumns:rY,BaseName:C9,IsAlias:$5,ExtraConfigBuilder:dY};[W0];[j9];[E9];[lY];[rY];[C9];[$5]=!1;[QB]=!0;[dY]=void 0;constructor($,G,X){this[W0]=this[j9]=$,this[E9]=G,this[C9]=X}}function KB($){return $!==null&&$!==void 0&&typeof $.getSQL==="function"}function FB($){let G={sql:"",params:[]};for(let X of $)if(G.sql+=X.sql,G.params.push(...X.params),X.typings?.length){if(!G.typings)G.typings=[];G.typings.push(...X.typings)}return G}class t1{static[v]="StringChunk";value;constructor($){this.value=Array.isArray($)?$:[$]}getSQL(){return new F1([this])}}class F1{constructor($){this.queryChunks=$;for(let G of $)if(h1(G,K1)){let X=G[K1.Symbol.Schema];this.usedTables.push(X===void 0?G[K1.Symbol.Name]:X+"."+G[K1.Symbol.Name])}}static[v]="SQL";decoder=iY;shouldInlineParams=!1;usedTables=[];append($){return this.queryChunks.push(...$.queryChunks),this}toQuery($){return pY.startActiveSpan("drizzle.buildSQL",(G)=>{let X=this.buildQueryFromSourceParams(this.queryChunks,$);return G?.setAttributes({"drizzle.query.text":X.sql,"drizzle.query.params":JSON.stringify(X.params)}),X})}buildQueryFromSourceParams($,G){let X=Object.assign({},G,{inlineParams:G.inlineParams||this.shouldInlineParams,paramStartIndex:G.paramStartIndex||{value:0}}),{casing:Y,escapeName:q,escapeParam:V,prepareTyping:W,inlineParams:J,paramStartIndex:H}=X;return FB($.map((U)=>{if(h1(U,t1))return{sql:U.value.join(""),params:[]};if(h1(U,Q6))return{sql:q(U.value),params:[]};if(U===void 0)return{sql:"",params:[]};if(Array.isArray(U)){let D=[new t1("(")];for(let[M,A]of U.entries())if(D.push(A),M<U.length-1)D.push(new t1(", "));return D.push(new t1(")")),this.buildQueryFromSourceParams(D,X)}if(h1(U,F1))return this.buildQueryFromSourceParams(U.queryChunks,{...X,inlineParams:J||U.shouldInlineParams});if(h1(U,K1)){let D=U[K1.Symbol.Schema],M=U[K1.Symbol.Name];return{sql:D===void 0||U[$5]?q(M):q(D)+"."+q(M),params:[]}}if(h1(U,r0)){let D=Y.getColumnCasing(U);if(G.invokeSource==="indexes")return{sql:q(D),params:[]};let M=U.table[K1.Symbol.Schema];return{sql:U.table[$5]||M===void 0?q(U.table[K1.Symbol.Name])+"."+q(D):q(M)+"."+q(U.table[K1.Symbol.Name])+"."+q(D),params:[]}}if(h1(U,nY)){let D=U[J4].schema,M=U[J4].name;return{sql:D===void 0||U[J4].isAlias?q(M):q(D)+"."+q(M),params:[]}}if(h1(U,S9)){if(h1(U.value,K6))return{sql:V(H.value++,U),params:[U],typings:["none"]};let D=U.value===null?null:U.encoder.mapToDriverValue(U.value);if(h1(D,F1))return this.buildQueryFromSourceParams([D],X);if(J)return{sql:this.mapInlineParam(D,X),params:[]};let M=["none"];if(W)M=[W(U.encoder)];return{sql:V(H.value++,D),params:[D],typings:M}}if(h1(U,K6))return{sql:V(H.value++,U),params:[U],typings:["none"]};if(h1(U,F1.Aliased)&&U.fieldAlias!==void 0)return{sql:q(U.fieldAlias),params:[]};if(h1(U,R6)){if(U._.isWith)return{sql:q(U._.alias),params:[]};return this.buildQueryFromSourceParams([new t1("("),U._.sql,new t1(") "),new Q6(U._.alias)],X)}if(mY(U)){if(U.schema)return{sql:q(U.schema)+"."+q(U.enumName),params:[]};return{sql:q(U.enumName),params:[]}}if(KB(U)){if(U.shouldOmitSQLParens?.())return this.buildQueryFromSourceParams([U.getSQL()],X);return this.buildQueryFromSourceParams([new t1("("),U.getSQL(),new t1(")")],X)}if(J)return{sql:this.mapInlineParam(U,X),params:[]};return{sql:V(H.value++,U),params:[U],typings:["none"]}}))}mapInlineParam($,{escapeString:G}){if($===null)return"null";if(typeof $==="number"||typeof $==="boolean")return $.toString();if(typeof $==="string")return G($);if(typeof $==="object"){let X=$.toString();if(X==="[object Object]")return G(JSON.stringify($));return G(X)}throw Error("Unexpected param value: "+$)}getSQL(){return this}as($){if($===void 0)return this;return new F1.Aliased(this,$)}mapWith($){return this.decoder=typeof $==="function"?{mapFromDriverValue:$}:$,this}inlineParams(){return this.shouldInlineParams=!0,this}if($){return $?this:void 0}}class Q6{constructor($){this.value=$}static[v]="Name";brand;getSQL(){return new F1([this])}}var iY={mapFromDriverValue:($)=>$},cY={mapToDriverValue:($)=>$},Ab={...iY,...cY};class S9{constructor($,G=cY){this.value=$,this.encoder=G}static[v]="Param";brand;getSQL(){return new F1([this])}}function H4($,...G){let X=[];if(G.length>0||$.length>0&&$[0]!=="")X.push(new t1($[0]));for(let[Y,q]of G.entries())X.push(q,new t1($[Y+1]));return new F1(X)}(($)=>{function G(){return new F1([])}$.empty=G;function X(H){return new F1(H)}$.fromList=X;function Y(H){return new F1([new t1(H)])}$.raw=Y;function q(H,U){let D=[];for(let[M,A]of H.entries()){if(M>0&&U!==void 0)D.push(U);D.push(A)}return new F1(D)}$.join=q;function V(H){return new Q6(H)}$.identifier=V;function W(H){return new K6(H)}$.placeholder=W;function J(H,U){return new S9(H,U)}$.param=J})(H4||(H4={}));(($)=>{class G{constructor(X,Y){this.sql=X,this.fieldAlias=Y}static[v]="SQL.Aliased";isSelectionField=!1;getSQL(){return this.sql}clone(){return new G(this.sql,this.fieldAlias)}}$.Aliased=G})(F1||(F1={}));class K6{constructor($){this.name=$}static[v]="Placeholder";getSQL(){return new F1([this])}}var AB=Symbol.for("drizzle:IsDrizzleView");class nY{static[v]="View";[J4];[AB]=!0;constructor({name:$,schema:G,selectedFields:X,query:Y}){this[J4]={name:$,originalName:$,schema:G,selectedFields:X,query:Y,isExisting:!Y,isAlias:!1}}getSQL(){return new F1([this])}}r0.prototype.getSQL=function(){return new F1([this])};K1.prototype.getSQL=function(){return new F1([this])};R6.prototype.getSQL=function(){return new F1([this])};function F0($,G){return{name:typeof $==="string"&&$.length>0?$:"",config:typeof $==="object"?$:G}}var T9=typeof TextDecoder>"u"?null:new TextDecoder;class I9{static[v]="SQLiteForeignKeyBuilder";reference;_onUpdate;_onDelete;constructor($,G){if(this.reference=()=>{let{name:X,columns:Y,foreignColumns:q}=$();return{name:X,columns:Y,foreignTable:q[0].table,foreignColumns:q}},G)this._onUpdate=G.onUpdate,this._onDelete=G.onDelete}onUpdate($){return this._onUpdate=$,this}onDelete($){return this._onDelete=$,this}build($){return new oY($,this)}}class oY{constructor($,G){this.table=$,this.reference=G.reference,this.onUpdate=G._onUpdate,this.onDelete=G._onDelete}static[v]="SQLiteForeignKey";reference;onUpdate;onDelete;getName(){let{name:$,columns:G,foreignColumns:X}=this.reference(),Y=G.map((W)=>W.name),q=X.map((W)=>W.name),V=[this.table[W0],...Y,X[0].table[W0],...q];return $??`${V.join("_")}_fk`}}function sY($,G){return`${$[W0]}_${G.join("_")}_unique`}class N1 extends Z9{static[v]="SQLiteColumnBuilder";foreignKeyConfigs=[];references($,G={}){return this.foreignKeyConfigs.push({ref:$,actions:G}),this}unique($){return this.config.isUnique=!0,this.config.uniqueName=$,this}generatedAlwaysAs($,G){return this.config.generated={as:$,type:"always",mode:G?.mode??"virtual"},this}buildForeignKeys($,G){return this.foreignKeyConfigs.map(({ref:X,actions:Y})=>{return((q,V)=>{let W=new I9(()=>{let J=q();return{columns:[$],foreignColumns:[J]}});if(V.onUpdate)W.onUpdate(V.onUpdate);if(V.onDelete)W.onDelete(V.onDelete);return W.build(G)})(X,Y)})}}class P1 extends r0{constructor($,G){if(!G.uniqueName)G.uniqueName=sY($,[G.name]);super($,G);this.table=$}static[v]="SQLiteColumn"}class aY extends N1{static[v]="SQLiteBigIntBuilder";constructor($){super($,"bigint","SQLiteBigInt")}build($){return new tY($,this.config)}}class tY extends P1{static[v]="SQLiteBigInt";getSQLType(){return"blob"}mapFromDriverValue($){if(typeof Buffer<"u"&&Buffer.from){let G=Buffer.isBuffer($)?$:$ instanceof ArrayBuffer?Buffer.from($):$.buffer?Buffer.from($.buffer,$.byteOffset,$.byteLength):Buffer.from($);return BigInt(G.toString("utf8"))}return BigInt(T9.decode($))}mapToDriverValue($){return Buffer.from($.toString())}}class eY extends N1{static[v]="SQLiteBlobJsonBuilder";constructor($){super($,"json","SQLiteBlobJson")}build($){return new $q($,this.config)}}class $q extends P1{static[v]="SQLiteBlobJson";getSQLType(){return"blob"}mapFromDriverValue($){if(typeof Buffer<"u"&&Buffer.from){let G=Buffer.isBuffer($)?$:$ instanceof ArrayBuffer?Buffer.from($):$.buffer?Buffer.from($.buffer,$.byteOffset,$.byteLength):Buffer.from($);return JSON.parse(G.toString("utf8"))}return JSON.parse(T9.decode($))}mapToDriverValue($){return Buffer.from(JSON.stringify($))}}class Gq extends N1{static[v]="SQLiteBlobBufferBuilder";constructor($){super($,"buffer","SQLiteBlobBuffer")}build($){return new Xq($,this.config)}}class Xq extends P1{static[v]="SQLiteBlobBuffer";mapFromDriverValue($){if(Buffer.isBuffer($))return $;return Buffer.from($)}getSQLType(){return"blob"}}function Yq($,G){let{name:X,config:Y}=F0($,G);if(Y?.mode==="json")return new eY(X);if(Y?.mode==="bigint")return new aY(X);return new Gq(X)}class qq extends N1{static[v]="SQLiteCustomColumnBuilder";constructor($,G,X){super($,"custom","SQLiteCustomColumn");this.config.fieldConfig=G,this.config.customTypeParams=X}build($){return new Vq($,this.config)}}class Vq extends P1{static[v]="SQLiteCustomColumn";sqlName;mapTo;mapFrom;constructor($,G){super($,G);this.sqlName=G.customTypeParams.dataType(G.fieldConfig),this.mapTo=G.customTypeParams.toDriver,this.mapFrom=G.customTypeParams.fromDriver}getSQLType(){return this.sqlName}mapFromDriverValue($){return typeof this.mapFrom==="function"?this.mapFrom($):$}mapToDriverValue($){return typeof this.mapTo==="function"?this.mapTo($):$}}function F6($){return(G,X)=>{let{name:Y,config:q}=F0(G,X);return new qq(Y,q,$)}}class A6 extends N1{static[v]="SQLiteBaseIntegerBuilder";constructor($,G,X){super($,G,X);this.config.autoIncrement=!1}primaryKey($){if($?.autoIncrement)this.config.autoIncrement=!0;return this.config.hasDefault=!0,super.primaryKey()}}class B6 extends P1{static[v]="SQLiteBaseInteger";autoIncrement=this.config.autoIncrement;getSQLType(){return"integer"}}class Wq extends A6{static[v]="SQLiteIntegerBuilder";constructor($){super($,"number","SQLiteInteger")}build($){return new Jq($,this.config)}}class Jq extends B6{static[v]="SQLiteInteger"}class Hq extends A6{static[v]="SQLiteTimestampBuilder";constructor($,G){super($,"date","SQLiteTimestamp");this.config.mode=G}defaultNow(){return this.default(H4`(cast((julianday('now') - 2440587.5)*86400000 as integer))`)}build($){return new Uq($,this.config)}}class Uq extends B6{static[v]="SQLiteTimestamp";mode=this.config.mode;mapFromDriverValue($){if(this.config.mode==="timestamp")return new Date($*1000);return new Date($)}mapToDriverValue($){let G=$.getTime();if(this.config.mode==="timestamp")return Math.floor(G/1000);return G}}class Dq extends A6{static[v]="SQLiteBooleanBuilder";constructor($,G){super($,"boolean","SQLiteBoolean");this.config.mode=G}build($){return new Mq($,this.config)}}class Mq extends B6{static[v]="SQLiteBoolean";mode=this.config.mode;mapFromDriverValue($){return Number($)===1}mapToDriverValue($){return $?1:0}}function c1($,G){let{name:X,config:Y}=F0($,G);if(Y?.mode==="timestamp"||Y?.mode==="timestamp_ms")return new Hq(X,Y.mode);if(Y?.mode==="boolean")return new Dq(X,Y.mode);return new Wq(X)}class Rq extends N1{static[v]="SQLiteNumericBuilder";constructor($){super($,"string","SQLiteNumeric")}build($){return new Qq($,this.config)}}class Qq extends P1{static[v]="SQLiteNumeric";mapFromDriverValue($){if(typeof $==="string")return $;return String($)}getSQLType(){return"numeric"}}class Kq extends N1{static[v]="SQLiteNumericNumberBuilder";constructor($){super($,"number","SQLiteNumericNumber")}build($){return new Fq($,this.config)}}class Fq extends P1{static[v]="SQLiteNumericNumber";mapFromDriverValue($){if(typeof $==="number")return $;return Number($)}mapToDriverValue=String;getSQLType(){return"numeric"}}class Aq extends N1{static[v]="SQLiteNumericBigIntBuilder";constructor($){super($,"bigint","SQLiteNumericBigInt")}build($){return new Bq($,this.config)}}class Bq extends P1{static[v]="SQLiteNumericBigInt";mapFromDriverValue=BigInt;mapToDriverValue=String;getSQLType(){return"numeric"}}function zq($,G){let{name:X,config:Y}=F0($,G),q=Y?.mode;return q==="number"?new Kq(X):q==="bigint"?new Aq(X):new Rq(X)}class wq extends N1{static[v]="SQLiteRealBuilder";constructor($){super($,"number","SQLiteReal")}build($){return new Oq($,this.config)}}class Oq extends P1{static[v]="SQLiteReal";getSQLType(){return"real"}}function Nq($){return new wq($??"")}class Pq extends N1{static[v]="SQLiteTextBuilder";constructor($,G){super($,"string","SQLiteText");this.config.enumValues=G.enum,this.config.length=G.length}build($){return new Zq($,this.config)}}class Zq extends P1{static[v]="SQLiteText";enumValues=this.config.enumValues;length=this.config.length;constructor($,G){super($,G)}getSQLType(){return`text${this.config.length?`(${this.config.length})`:""}`}}class Lq extends N1{static[v]="SQLiteTextJsonBuilder";constructor($){super($,"json","SQLiteTextJson")}build($){return new _q($,this.config)}}class _q extends P1{static[v]="SQLiteTextJson";getSQLType(){return"text"}mapFromDriverValue($){return JSON.parse($)}mapToDriverValue($){return JSON.stringify($)}}function M1($,G={}){let{name:X,config:Y}=F0($,G);if(Y.mode==="json")return new Lq(X);return new Pq(X,Y)}function Eq(){return{blob:Yq,customType:F6,integer:c1,numeric:zq,real:Nq,text:M1}}var v9=Symbol.for("drizzle:SQLiteInlineForeignKeys");class G5 extends K1{static[v]="SQLiteTable";static Symbol=Object.assign({},K1.Symbol,{InlineForeignKeys:v9});[K1.Symbol.Columns];[v9]=[];[K1.Symbol.ExtraConfigBuilder]=void 0}function BB($,G,X,Y,q=$){let V=new G5($,Y,q),W=typeof G==="function"?G(Eq()):G,J=Object.fromEntries(Object.entries(W).map(([U,D])=>{let M=D;M.setName(U);let A=M.build(V);return V[v9].push(...M.buildForeignKeys(A,V)),[U,A]})),H=Object.assign(V,J);if(H[K1.Symbol.Columns]=J,H[K1.Symbol.ExtraConfigColumns]=J,X)H[G5.Symbol.ExtraConfigBuilder]=X;return H}var U4=($,G,X)=>{return BB($,G,X)};class jq{constructor($,G){this.name=$,this.unique=G}static[v]="SQLiteIndexBuilderOn";on(...$){return new Cq(this.name,$,this.unique)}}class Cq{static[v]="SQLiteIndexBuilder";config;constructor($,G,X){this.config={name:$,columns:G,unique:X,where:void 0}}where($){return this.config.where=$,this}build($){return new Sq(this.config,$)}}class Sq{static[v]="SQLiteIndex";config;constructor($,G){this.config={...$,table:G}}}function z6($){return new jq($,!1)}function w6(...$){if($[0].columns)return new b9($[0].columns,$[0].name);return new b9($)}class b9{static[v]="SQLitePrimaryKeyBuilder";columns;name;constructor($,G){this.columns=$,this.name=G}build($){return new Tq($,this.columns,this.name)}}class Tq{constructor($,G,X){this.table=$,this.columns=G,this.name=X}static[v]="SQLitePrimaryKey";columns;name;getName(){return this.name??`${this.table[G5.Symbol.Name]}_${this.columns.map(($)=>$.name).join("_")}_pk`}}var Iq=U4("job_queue",{id:M1("id").primaryKey().$defaultFn(()=>z2()),type:M1("type").notNull(),data:M1("data").notNull(),result:M1("result",{mode:"json"}),source:M1("source"),metadata:M1("metadata",{mode:"json"}).$type().notNull(),status:M1("status",{enum:["pending","processing","completed","failed"]}).notNull().default("pending"),priority:c1("priority").notNull().default(0),retryCount:c1("retryCount").notNull().default(0),maxRetries:c1("maxRetries").notNull().default(3),lastError:M1("lastError"),createdAt:c1("createdAt").notNull().$defaultFn(()=>Date.now()),scheduledFor:c1("scheduledFor").notNull().$defaultFn(()=>Date.now()),startedAt:c1("startedAt"),completedAt:c1("completedAt")},($)=>({queueReadyIdx:z6("idx_job_queue_ready").on($.status,$.priority,$.scheduledFor),jobTypeIdx:z6("idx_job_queue_type").on($.type,$.status),jobSourceIdx:z6("idx_job_queue_source").on($.source)}));var zB=R.object({id:R.string(),type:R.string(),data:R.string(),status:R.enum(["pending","processing","completed","failed"]),source:R.string().nullable(),priority:R.number(),retryCount:R.number(),maxRetries:R.number(),lastError:R.string().nullable(),createdAt:R.number(),scheduledFor:R.number(),startedAt:R.number().nullable(),completedAt:R.number().nullable(),metadata:t4,result:R.unknown().nullable().optional()});function x9($,G,X){return async(Y)=>{let{type:q,data:V,toolContext:W=null,options:J}=Y,{metadata:H,...U}=J??{},D={source:G,...J?.rootJobId&&{rootJobId:J.rootJobId},...U,metadata:{operationType:"data_processing",pluginId:G,...W&&{interfaceType:W.interfaceType,channelId:W.channelId},...H}},M=X&&!q.includes(":")?`${G}:${q}`:q;return $.enqueue({type:M,data:V,options:D})}}function g9($,G){return async(X,Y)=>{let q=z2(),V=X.map((J)=>({...J,type:J.type.includes(":")?J.type:`${G}:${J.type}`})),W={...Y,source:G,rootJobId:q,metadata:{...Y?.metadata,operationType:"batch_processing",pluginId:G}};return await $.enqueueBatch(V,W,q,G),q}}function h9($,G){return(X,Y)=>{let q=X.includes(":")?X:`${G}:${X}`;$.registerHandler(q,Y,G)}}var wB=R.object({name:R.string(),schema:R.custom(($)=>$ instanceof R.ZodType)});function vq($){return wB.safeParse($).success}function OB($){if(!$)return;return{status:$.status,message:$.message,lastCheck:$.lastCheck?.toISOString(),details:$.details}}function bq($){return{model:$.model,version:$.version,uptime:$.uptime,entities:$.entities,embeddings:$.embeddings,ai:$.ai,daemons:$.daemons.map((G)=>({name:G.name,pluginId:G.pluginId,status:G.status,health:OB(G.health)})),endpoints:$.endpoints}}var D4=R.record(R.unknown());var NB=R.object({id:R.string(),sessionId:R.string(),interfaceType:R.string(),channelId:R.string(),channelName:R.string().optional(),startedAt:R.string(),lastActiveAt:R.string(),createdAt:R.string(),updatedAt:R.string(),metadata:D4}),k9=R.enum(["user","assistant","system"]),PB=R.object({id:R.string(),conversationId:R.string(),role:k9,content:R.string(),timestamp:R.string(),metadata:D4});function xq($){if(!$)return{};try{let G=JSON.parse($);if(G&&typeof G==="object"&&!Array.isArray(G))return G}catch{}return{}}function ZB($){let G=k9.safeParse($);return G.success?G.data:"user"}function O6($){let G=xq($.metadata),X=typeof G.channelName==="string"?G.channelName:void 0;return{id:$.id,sessionId:$.sessionId,interfaceType:$.interfaceType,channelId:$.channelId,channelName:X,startedAt:$.started,lastActiveAt:$.lastActive,createdAt:$.created,updatedAt:$.updated,metadata:G}}function gq($){return{id:$.id,conversationId:$.conversationId,role:ZB($.role),content:$.content,timestamp:$.timestamp,metadata:xq($.metadata)}}var y9=R.object({name:R.string(),role:R.string(),purpose:R.string(),values:R.array(R.string())}),f9=R.object({name:R.string(),kind:R.enum(["professional","team","collective"]),organization:R.string().optional(),description:R.string().optional(),avatar:R.string().optional(),website:R.string().optional(),email:R.string().optional(),socialLinks:R.array(R.object({platform:R.enum(["github","instagram","linkedin","email","website"]),url:R.string(),label:R.string().optional()})).optional()});function hq($){return y9.parse($)}function kq($){return f9.parse($)}function yq($){return async()=>{return bq(await $.getAppInfo())}}function fq($,G){return{get:()=>hq($.getIdentity()),getProfile:()=>kq($.getProfile()),getAppInfo:G}}function mq($,G,X){let Y=$.getMessageBus();return{send:async(V)=>{return Y.send({...V,sender:G})},subscribe:(V,W)=>{if(vq(V)){let J=V,H=W,U=async(D)=>{let M=J.schema.safeParse(D.payload);if(!M.success)return X.warn(`Invalid payload for channel ${J.name}`,{error:M.error.message}),{noop:!0};let{payload:A,...F}=D;return H(M.data,F)};return Y.subscribe(J.name,U)}return Y.subscribe(V,W)}}}function uq($,G){let X=$.getJobQueueService();return{...$.jobs,enqueue:x9(X,G,!0),enqueueBatch:g9($.jobs,G),registerHandler:h9(X,G)}}function pq($){return{get:async(G)=>{let Y=await $.getConversationService().getConversation(G);return Y?O6(Y):null},search:async(G)=>{return(await $.getConversationService().searchConversations(G)).map(O6)},list:async(G)=>{return(await $.getConversationService().listConversations(G)).map(O6)},getMessages:async(G,X)=>{return(await $.getConversationService().getMessages(G,X)).map(gq)},countMessages:async(G)=>{return $.getConversationService().countMessages(G)}}}function lq($,G){return{registerHandler:(X,Y)=>{$.registerEvalHandler(G,X,Y)}}}function rq($){return{register:(G,X)=>{$.getInsightsRegistry().register(G,X)}}}function dq($,G){return{register:({label:X,url:Y,priority:q=100})=>{$.registerEndpoint({label:X,url:Y,pluginId:G,priority:q})}}}function M4($,G,X){let Y=$.getEntityService(),q=$.getLogger().child(G),V=$.getDomain(),W=yq($);return{pluginId:G,logger:q,entityService:Y,identity:fq($,W),appInfo:W,domain:V,siteUrl:V?`https://${V}`:void 0,previewUrl:V?`https://${w9(V)}`:void 0,entityDisplay:X?.entityDisplay,spaces:$.getSpaces(),messaging:mq($,G,q),jobs:uq($,G),conversations:pq($),dataDir:$.getDataDir(),eval:lq($,G),insights:rq($),endpoints:dq($,G)}}import{createClient as rg}from"@libsql/client";var N6=U4("entities",{id:M1("id").notNull(),entityType:M1("entityType").notNull(),content:M1("content").notNull(),contentHash:M1("contentHash").notNull(),metadata:M1("metadata",{mode:"json"}).$type().notNull().default(H4`'{}'`),created:c1("created").notNull().$defaultFn(()=>Date.now()),updated:c1("updated").notNull().$defaultFn(()=>Date.now())},($)=>{return{pk:w6({columns:[$.id,$.entityType]})}});import{createClient as eg}from"@libsql/client";var iq=F6({dataType(){return"F32_BLOB(1536)"},toDriver($){return Buffer.from($.buffer)},fromDriver($){return new Float32Array($.buffer,$.byteOffset,$.byteLength/4)}});var P6=U4("embeddings",{entityId:M1("entity_id").notNull(),entityType:M1("entity_type").notNull(),embedding:iq("embedding").notNull(),contentHash:M1("content_hash").notNull()},($)=>{return{pk:w6({columns:[$.entityId,$.entityType]})}});var qh=R.object({id:R.string().min(1,"Entity ID is required"),entityType:R.string().min(1,"Entity type is required"),contentHash:R.string().min(1,"Content hash is required"),operation:R.enum(["create","update"])});var Hh=R.object({limit:R.number().int().positive().optional().default(20),offset:R.number().int().min(0).optional().default(0),types:R.array(R.string()).optional().default([]),excludeTypes:R.array(R.string()).optional().default([]),weight:R.record(R.string(),R.number()).optional()});var LB=R.object({field:R.string(),direction:R.enum(["asc","desc"]),nullsFirst:R.boolean().optional()}),zh=R.object({limit:R.number().int().positive().optional(),offset:R.number().int().min(0).optional().default(0),sortFields:R.array(LB).optional(),filter:R.object({metadata:R.record(R.string(),R.unknown()).optional()}).optional(),publishedOnly:R.boolean().optional()});var u9=J5($8(),1);function Z6($,G){if(Object.keys(G).length===0)return $;let X=Object.fromEntries(Object.entries(G).filter(([,Y])=>Y!==void 0));return u9.default.stringify($,X)}function m9($){if($ instanceof Date)return $.toISOString();if(Array.isArray($))return $.map(m9);if($!==null&&typeof $==="object"){let G={};for(let[X,Y]of Object.entries($))G[X]=m9(Y);return G}return $}function Y5($,G){let{content:X,data:Y}=u9.default($),q=m9(Y);return{content:X.trim(),metadata:G.parse(q)}}var cq=R.object({id:R.string(),entityType:R.string(),content:R.string(),created:R.string().datetime(),updated:R.string().datetime(),metadata:R.record(R.string(),R.unknown()),contentHash:R.string()});var gB=R.object({currentPage:R.number(),totalPages:R.number(),totalItems:R.number(),pageSize:R.number(),hasNextPage:R.boolean(),hasPrevPage:R.boolean()});function hB($){return $.replace(/:/g,"-")}function kB($){return $.split(/[:.-]/).map((G)=>G.charAt(0).toUpperCase()+G.slice(1)).join(" ")}var p9=new Map;async function oq($,G,X){let Y=p9.get(G);if(Y!==void 0)return Y;let q=hB(G),V;try{V=await $.getEntity({entityType:"prompt",id:q})}catch{return X}if(V?.content){let W=Y5(V.content,R.record(R.unknown())).content;return p9.set(G,W),W}try{let W=kB(G),J=Z6(X,{title:W,target:G});await $.createEntity({entity:{id:q,entityType:"prompt",content:J,metadata:{title:W,target:G,slug:q}}})}catch{}return p9.set(G,X),X}function L6($){let G=$.getEntityService(),X=$.getEntityRegistry(),Y=$.getDataSourceRegistry();return{register:(q,V,W,J)=>{X.registerEntityType(q,V,W,J)},getAdapter:(q)=>{try{return X.getAdapter(q)}catch{return}},extendFrontmatterSchema:(q,V)=>{X.extendFrontmatterSchema(q,V)},getEffectiveFrontmatterSchema:(q)=>{return X.getEffectiveFrontmatterSchema(q)},registerCreateInterceptor:(q,V)=>{X.registerCreateInterceptor(q,V)},update:async(q)=>{return G.updateEntity({entity:q})},registerDataSource:(q)=>{Y.register(q)}}}function _6($){return{resolve:(G,X)=>{return oq($,G,X)}}}function sq($,G,X){let Y=M4($,G,X),q=$.getEntityService();return{...Y,entityService:q,entities:L6($),ai:{query:(V,W)=>$.query(V,W),generate:async(V)=>{return $.generateContent(V)},generateObject:async(V,W)=>{return $.generateObject(V,W)},generateImage:async(V,W)=>{return $.generateImage(V,W)},canGenerateImages:()=>{return $.canGenerateImages()}},prompts:_6(q)}}function tq($,G,X){let Y=!1,q=!1;if($.jobs.registerHandler(X.job.type,X.job.handler),X.initialSync){let V=X.initialSync;$.messaging.subscribe("sync:initial:completed",async()=>{if(Y)return{success:!0};if(Y=!0,!(await V.shouldEnqueue?.()??!0))return G.info("Skipping derived entity projection initial sync",{projectionId:X.id,targetType:X.targetType}),{success:!0};return q=await aq($,G,X,V.jobData,fB(V.jobOptions),"initial-sync"),{success:!0}})}if(X.sourceChange){let V=X.sourceChange,W=new Set(V.sourceTypes),J=V.events??["entity:created","entity:updated"],H=async(U)=>{if(V.requireInitialSync&&!Y)return{success:!0};let D=U.payload,M=yB(V,D);if(!M||!W.has("*")&&!W.has(M))return{success:!0};if(!(await V.shouldEnqueue?.(D)??!0))return{success:!0};let F=await V.jobData(D);if(!F)return{success:!0};return await aq($,G,X,F,V.jobOptions?.(D),"source-change"),{success:!0}};for(let U of J)$.messaging.subscribe(U,H)}return{hasObservedInitialSync:()=>Y,hasQueuedInitialSync:()=>q}}function yB($,G){if($.sourceType)return $.sourceType;if($.sourceKind&&$.sourceKind!=="entity")return $.sourceKind;return G.entityType}async function aq($,G,X,Y,q,V){try{return await $.jobs.enqueue({type:X.job.type,data:Y,...q?{options:q}:{}}),G.info("Queued derived entity projection",{projectionId:X.id,targetType:X.targetType,reason:V}),!0}catch(W){return G.error("Failed to queue derived entity projection",{projectionId:X.id,targetType:X.targetType,reason:V,error:V0(W)}),!1}}function fB($){return typeof $==="function"?$():$}var mB=R.object({});class E6 extends w2{type="entity";derivedEntityProjectionControllers=new Map;constructor($,G,X={},Y=mB){super($,G,X,Y)}async register($,G){let X=sq($,this.id,G);if(this.context=X,this.setupMessageHandlers(X),X.entities.register(this.entityType,this.schema,this.adapter,this.getEntityTypeConfig()),this.interceptCreate!==E6.prototype.interceptCreate)X.entities.registerCreateInterceptor(this.entityType,(H,U)=>this.interceptCreate(H,U,X));let Y=this.createGenerationHandler(X);if(Y)X.jobs.registerHandler(`${this.entityType}:generation`,Y);let q=this.getTemplates();if(q&&Object.keys(q).length>0)$.registerTemplates(q,this.id);let V=this.getDataSources();for(let H of V)X.entities.registerDataSource(H);let W=this.getDerivedEntityProjections(X);for(let H of W){let U=tq(X,this.logger,H);this.derivedEntityProjectionControllers.set(H.id,U)}await this.onRegister(this.context);let J=await this.getInstructions();return{tools:[],resources:[],...J&&{instructions:J}}}async interceptCreate($,G,X){return{kind:"continue",input:$}}createGenerationHandler($){return null}getTemplates(){return null}getDataSources(){return[]}getEntityTypeConfig(){return}getDerivedEntityProjections($){return[]}getDerivedEntityProjectionController($){return this.derivedEntityProjectionControllers.get($)}}class eq extends E6{hooks;constructor($,G,X,Y,q){super($,G,X,Y);this.hooks=q}get entityType(){return this.hooks.getEntityType()}get schema(){return this.hooks.getSchema()}get adapter(){return this.hooks.getAdapter()}onRegister($){return this.hooks.onRegister($)}onReady($){return this.hooks.onReady($)}onShutdown(){return this.hooks.onShutdown()}getEntityTypeConfig(){return this.hooks.getEntityTypeConfig()}getDataSources(){return this.hooks.getDataSources()}getInstructions(){return this.hooks.getInstructions()}interceptCreate($,G,X){return this.hooks.interceptCreate($,G,X)}}class l9{type="entity";id;version;packageName;description;delegate;constructor($,G,X,Y){if(this.id=$,this.version=G.version,this.packageName=G.name,G.description!==void 0)this.description=G.description;this.delegate=new eq($,G,X,Y,{getEntityType:()=>this.entityType,getSchema:()=>this.schema,getAdapter:()=>this.adapter,onRegister:(q)=>this.onRegister(q),onReady:(q)=>this.onReady(q),onShutdown:()=>this.onShutdown(),getEntityTypeConfig:()=>this.getEntityTypeConfig(),getDataSources:()=>this.getDataSources(),getInstructions:()=>this.getInstructions(),interceptCreate:(q,V,W)=>this.interceptCreate(q,V,W)})}register($,G){return this.delegate.register($,G)}async onRegister($){}async onReady($){}async onShutdown(){}async getInstructions(){return}getEntityTypeConfig(){return}getDataSources(){return[]}async interceptCreate($,G,X){return{kind:"continue",input:$}}ready(){return this.delegate.ready()}shutdown(){return this.delegate.shutdown?.()??Promise.resolve()}}function $V($){return{text:$.text,...$.toolResults&&{toolResults:$.toolResults.map((G)=>({toolName:G.toolName,...G.args&&{args:G.args},...G.jobId!==void 0&&{jobId:G.jobId},...G.data!==void 0&&{data:G.data}}))},...$.pendingConfirmation&&{pendingConfirmation:{toolName:$.pendingConfirmation.toolName,description:$.pendingConfirmation.description,args:$.pendingConfirmation.args}},usage:$.usage}}function uB($){if(!$)return;return{...$.userPermissionLevel&&{userPermissionLevel:$.userPermissionLevel},...$.interfaceType&&{interfaceType:$.interfaceType},...$.channelId&&{channelId:$.channelId},...$.channelName&&{channelName:$.channelName}}}function GV($){return{chat:async(G,X,Y)=>{return $V(await $.chat(G,X,uB(Y)))},confirmPendingAction:async(G,X)=>{return $V(await $.confirmPendingAction(G,X))},invalidate:()=>{$.invalidateAgent()}}}function XV($,G,X){let Y=M4($,G,X),q=$.getMCPService(),V=$.getPermissionService(),W=GV($.getAgentService());return{...Y,mcpTransport:q,agent:W,permissions:{getUserLevel:(J,H)=>{return V.determineUserLevel(J,H)}},daemons:{register:(J,H)=>{let U=`${G}:${J}`;$.registerDaemon(U,H,G),Y.logger.debug(`Registered daemon: ${U}`)}},conversations:{...Y.conversations,start:async(J)=>{return $.getConversationService().startConversation(J)},addMessage:async(J)=>{await $.getConversationService().addMessage(J)}},tools:{listForPermissionLevel:(J)=>{return $.listToolsForPermissionLevel(J)}},apiRoutes:{getRoutes:()=>{return $.getPluginApiRoutes()},getMessageBus:()=>{return $.getMessageBus()}},webRoutes:{getRoutes:()=>{return $.getPluginWebRoutes()}},plugins:{has:(J)=>$.hasPlugin(J)}}}var pB=3600000;class q5 extends w2{type="interface";daemon;jobTrackingEntries=new Map;jobTrackingTtlMs=pB;async register($,G){let X=XV($,this.id,G);if(this.context=X,this.initializeDaemon(),this.daemon)await this.registerDaemon(X);return this.setupMessageHandlers(X),await this.onRegister(X),this.getCapabilities()}async onRegister($){}async registerDaemon($){if(!this.daemon)return;$.daemons.register(this.id,this.daemon),$.logger.debug(`Registered daemon for interface: ${this.id}`)}createDaemon(){return}requiresDaemonStartup(){return!1}getWebRoutes(){return[]}initializeDaemon(){let $=this.createDaemon();if($)this.daemon=$}async handleProgressEvent($,G){}cleanupExpiredEntries(){let $=Date.now(),G=[];for(let[X,Y]of this.jobTrackingEntries)if($-Y.createdAt>this.jobTrackingTtlMs)G.push(X);for(let X of G)this.jobTrackingEntries.delete(X)}ownsJob($,G){return this.jobTrackingEntries.has($)||G!==void 0&&this.jobTrackingEntries.has(G)}getJobTracking($,G){let X=this.jobTrackingEntries.get($);if(X)return X.info;if(G){let Y=this.jobTrackingEntries.get(G);if(Y)return Y.info}return}setJobTracking($,G){this.cleanupExpiredEntries(),this.jobTrackingEntries.set($,{info:G,createdAt:Date.now()})}removeJobTracking($){this.jobTrackingEntries.delete($)}async createJobWithTracking($,G){let Y=await this.getContext().jobs.enqueue($);return this.setJobTracking(Y,G),Y}async createBatchWithTracking($,G,X){let q=await this.getContext().jobs.enqueueBatch($,X);return this.setJobTracking(q,G),q}}class YV extends q5{hooks;constructor($,G,X,Y,q){super($,G,X,Y);this.hooks=q}onRegister($){return this.hooks.onRegister($)}onReady($){return this.hooks.onReady($)}onShutdown(){return this.hooks.onShutdown()}getTools(){return this.hooks.getTools()}getResources(){return this.hooks.getResources()}getInstructions(){return this.hooks.getInstructions()}getWebRoutes(){return this.hooks.getWebRoutes()}requiresDaemonStartup(){return this.hooks.requiresDaemonStartup()}}class V5{type="interface";id;version;packageName;description;delegate;constructor($,G,X,Y){if(this.id=$,this.version=G.version,this.packageName=G.name,G.description!==void 0)this.description=G.description;this.delegate=new YV($,G,X,Y,{onRegister:(q)=>this.onRegister(q),onReady:(q)=>this.onReady(q),onShutdown:()=>this.onShutdown(),getTools:()=>this.getTools(),getResources:()=>this.getResources(),getInstructions:()=>this.getInstructions(),getWebRoutes:()=>this.getWebRoutes(),requiresDaemonStartup:()=>this.requiresDaemonStartup()})}register($,G){return this.delegate.register($,G)}async onRegister($){}async onReady($){}async onShutdown(){}async getTools(){return[]}async getResources(){return[]}async getInstructions(){return}getWebRoutes(){return[]}requiresDaemonStartup(){return!1}ready(){return this.delegate.ready()}shutdown(){return this.delegate.shutdown?.()??Promise.resolve()}}function qV($,G){$.messaging.subscribe("job-progress",async(X)=>{try{let Y=P9.safeParse(X.payload);if(!Y.success)return G.onInvalidSchema(),{success:!1};let q=Y.data;return await G.onProgress(q,q.metadata),{success:!0}}catch(Y){return G.onError(Y),{success:!1}}})}function VV($){let G=$.status==="completed"?"\u2705":"\u274C",X=$.status==="completed"?"completed":"failed",Y=$.metadata.operationType.replace(/_/g," "),q=$.metadata.operationTarget?`: ${$.metadata.operationTarget}`:"",V=`${G} **${Y}${q}** ${X}`;if($.message)V+=`
170
170
  ${$.message}`;return V}function r9($){let G=$.metadata.operationType.replace(/_/g," "),X=$.metadata.operationTarget?`: ${$.metadata.operationTarget}`:"",Y=`\uD83D\uDD04 **${G}${X}**`;if($.progress&&$.progress.total>0)Y+=` ${$.progress.current}/${$.progress.total} (${$.progress.percentage}%)`;if($.message)Y+=`
171
171
  ${$.message}`;return Y}var lB=1e5,rB=[".md",".txt",".markdown"],dB=["text/plain","text/markdown","text/x-markdown"],iB=/https?:\/\/[^\s<>"{}|\\^`[\]]+?(?=[,;:\s]|$)/gi,cB=["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"],nB=R.object({captureUrls:R.boolean().default(!1),blockedUrlDomains:R.array(R.string()).default(cB)});function WV($,G){if(G&&dB.some((X)=>G.startsWith(X)))return!0;return rB.some((X)=>$.toLowerCase().endsWith(X))}function JV($){return $<=lB}function HV($,G){return`User uploaded a file "${$}":
172
172
 
@@ -174,5 +174,5 @@ ${G}`}function UV($,G){let X=$.match(iB)??[];return[...new Set(X)].filter((Y)=>{
174
174
 
175
175
  ${G}`}extractCaptureableUrls($,G){let X=$.match(/https?:\/\/[^\s<>"{}|\\^`[\]]+?(?=[,;:\s]|$)/gi)??[];return[...new Set(X)].filter((Y)=>{try{let{hostname:q}=new URL(Y);return!G.some((V)=>q===V||q.endsWith(`.${V}`))}catch{return!1}})}captureUrlViaAgent($,G,X,Y){return this.messageDelegate.captureUrlViaAgentPublic($,G,X,Y)}trackAgentResponseForJob($,G,X){this.messageDelegate.trackAgentResponseForJobPublic($,G,X)}registerProgressCallback($){this.messageDelegate.registerProgressCallback($)}unregisterProgressCallback(){this.messageDelegate.unregisterProgressCallback()}getProgressEvents(){return this.messageDelegate.getProgressEvents()}getActiveProgressEvents(){return this.messageDelegate.getActiveProgressEvents()}startProcessingInput($=null){this.messageDelegate.startProcessingInput($)}endProcessingInput(){this.messageDelegate.endProcessingInput()}getCurrentChannelId(){return this.messageDelegate.getCurrentChannelIdPublic()}ready(){return this.messageDelegate.ready()}shutdown(){return this.messageDelegate.shutdown?.()??Promise.resolve()}}function RV($,G,X){let Y=M4($,G,X),q=$.getEntityService(),V=$.getRenderService(),W=$.getContentService();return{...Y,entityService:q,entities:L6($),templates:{register:(J,H)=>{$.registerTemplates(J,H??G)},format:(J,H)=>{return W.formatContent(J,H,{pluginId:G})},parse:(J,H)=>{return W.parseContent(J,H,G)},resolve:async(J,H)=>{return await W.resolveContent(J,H,G)},getCapabilities:(J)=>{let H=J.includes(":")?J:`${G}:${J}`,U=$.getTemplate(H);if(!U)return null;let D=a4.getCapabilities(U);return{canGenerate:D.canGenerate,canFetch:D.canFetch,canRender:D.canRender,isStaticOnly:D.isStaticOnly}}},views:{get:(J)=>{return V.get(J)??void 0},list:()=>{return V.list()},hasRenderer:(J)=>{return V.hasRenderer(J,"web")},getRenderer:(J)=>{return V.getRenderer(J,"web")},validate:(J,H)=>{return V.validate(J,H)}},prompts:_6(q),registerInstructions:(J)=>{$.registerInstructions(G,J)}}}class c9 extends w2{type="service";getApiRoutes(){return[]}getWebRoutes(){return[]}async register($,G){let X=RV($,this.id,G);return this.context=X,this.setupMessageHandlers(X),await this.onRegister(X),this.getCapabilities()}get entityService(){return this.getContext().entityService}registerEntityType($,G,X,Y){this.getContext().entities.register($,G,X,Y)}async enqueueJob($){return this.getContext().jobs.enqueue($)}async enqueueBatch($,G){return this.getContext().jobs.enqueueBatch($,G)}async registerEntityTypes($){}async registerJobHandlers($){}async onRegister($){await this.registerEntityTypes($),await this.registerJobHandlers($)}}class QV extends c9{hooks;constructor($,G,X,Y,q){super($,G,X,Y);this.hooks=q}onRegister($){return this.hooks.onRegister($)}onReady($){return this.hooks.onReady($)}onShutdown(){return this.hooks.onShutdown()}getTools(){return this.hooks.getTools()}getResources(){return this.hooks.getResources()}getInstructions(){return this.hooks.getInstructions()}}class n9{type="service";id;version;packageName;description;delegate;constructor($,G,X,Y){if(this.id=$,this.version=G.version,this.packageName=G.name,G.description!==void 0)this.description=G.description;this.delegate=new QV($,G,X,Y,{onRegister:(q)=>this.onRegister(q),onReady:(q)=>this.onReady(q),onShutdown:()=>this.onShutdown(),getTools:()=>this.getTools(),getResources:()=>this.getResources(),getInstructions:()=>this.getInstructions()})}register($,G){return this.delegate.register($,G)}async onRegister($){}async onReady($){}async onShutdown(){}async getTools(){return[]}async getResources(){return[]}async getInstructions(){return}ready(){return this.delegate.ready()}shutdown(){return this.delegate.shutdown?.()??Promise.resolve()}}var oB=R.object({userPermissionLevel:R.enum(["public","trusted","anchor"]).optional(),interfaceType:R.string().optional(),channelId:R.string().optional(),channelName:R.string().optional()}),KV=R.object({toolName:R.string(),description:R.string(),args:R.unknown()}),FV=R.object({toolName:R.string(),args:R.record(R.unknown()).optional(),jobId:R.string().optional(),data:R.unknown().optional()}),sB=R.object({text:R.string(),toolResults:R.array(FV).optional(),pendingConfirmation:KV.optional(),usage:R.object({promptTokens:R.number(),completionTokens:R.number(),totalTokens:R.number()})});var aB=R.object({label:R.string(),url:R.string(),pluginId:R.string(),priority:R.number()}),tB=R.object({status:R.enum(["healthy","warning","error","unknown"]),message:R.string().optional(),lastCheck:R.string().optional(),details:R.record(R.unknown()).optional()}),eB=R.object({name:R.string(),pluginId:R.string(),status:R.string(),health:tB.optional()}),$z=R.object({model:R.string(),version:R.string(),uptime:R.number(),entities:R.number(),embeddings:R.number(),ai:R.object({model:R.string(),embeddingModel:R.string()}),daemons:R.array(eB),endpoints:R.array(aB)});var Gz=R.union([R.object({success:R.boolean(),data:R.unknown().optional(),error:R.string().optional()}),R.object({noop:R.literal(!0)})]),Xz=R.object({id:R.string(),timestamp:R.string(),type:R.string(),source:R.string(),target:R.string().optional(),metadata:D4.optional()});export{oA as urlCaptureConfigSchema,cA as toolSuccess,nA as toolError,sA as defineChannel,dA as createTool,iA as createResource,FV as ToolResultDataSchema,n9 as ServicePlugin,KV as PendingConfirmationSchema,PB as MessageSchema,Gz as MessageResponseSchema,i9 as MessageInterfacePlugin,V5 as InterfacePlugin,D4 as ExtensionMetadataSchema,l9 as EntityPlugin,NB as ConversationSchema,oB as ChatContextSchema,y9 as BrainCharacterSchema,Xz as BaseMessageSchema,$z as AppInfoSchema,f9 as AnchorProfileSchema,sB as AgentResponseSchema};
176
176
 
177
- //# debugId=31F613C1AD99F3F964756E2164756E21
177
+ //# debugId=06258F76F3D5E4A264756E2164756E21
178
178
  //# sourceMappingURL=plugins.js.map