@rizom/brain 0.2.0-alpha.353 → 0.2.0-alpha.355
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/brain.js +37 -37
- package/dist/chunks/{app-bmwdrf3f.js → app-c5pdekt0.js} +2 -2
- package/dist/chunks/{blog-post-adapter-bqm9vrja.js → blog-post-adapter-njnq5kyv.js} +2 -2
- package/dist/chunks/{index-dj1tsbr6.js → index-6ckkrggy.js} +3 -3
- package/dist/chunks/{index-dj1tsbr6.js.map → index-6ckkrggy.js.map} +1 -1
- package/dist/chunks/{index-3qsz79tf.js → index-bjmmrp5q.js} +3 -3
- package/dist/chunks/{index-3qsz79tf.js.map → index-bjmmrp5q.js.map} +3 -3
- package/dist/chunks/{index-qpztpfw8.js → index-e2scq3d5.js} +2 -2
- package/dist/chunks/{index-d6q3sk2w.js → index-p49nmsdm.js} +2 -2
- package/dist/chunks/{index-d6q3sk2w.js.map → index-p49nmsdm.js.map} +2 -2
- package/dist/chunks/{index-cyevdq6v.js → index-v3xvnwsn.js} +2 -2
- package/dist/chunks/{index-4mr9k51y.js → index-w5e9n75h.js} +3 -3
- package/dist/chunks/{index-4mr9k51y.js.map → index-w5e9n75h.js.map} +3 -3
- package/dist/chunks/{linkedin-template-d4av3dpq.js → linkedin-template-2yn0zvz4.js} +2 -2
- package/dist/chunks/{rss-datasource-5vhyhygh.js → rss-datasource-6drt6y87.js} +2 -2
- package/dist/entities.js +1 -1
- package/dist/index.js +1 -1
- package/dist/interfaces.js +1 -1
- package/dist/model.js +38 -38
- package/dist/model.js.map +13 -13
- package/dist/plugins.js +1 -1
- package/dist/services.js +1 -1
- package/dist/ui/studio-app.js +3 -3
- package/dist/ui/studio-app.js.map +3 -3
- package/dist/ui/studio-asset-manifest.json +4 -4
- package/dist/ui/studio-chunks/{main-x38k1kej.js → main-8g7rwpye.js} +5 -9
- package/dist/ui/studio-chunks/{main-x38k1kej.js.map → main-8g7rwpye.js.map} +3 -3
- package/dist/ui/studio-chunks/{studio-chat-workspace-a7km8rss.js → studio-chat-workspace-z9973dz1.js} +1 -1
- package/package.json +1 -1
- package/templates/deploy/scripts/create-predeploy-backup.ts +11 -1
- package/templates/deploy/scripts/update-dns.ts +32 -9
- /package/dist/chunks/{app-bmwdrf3f.js.map → app-c5pdekt0.js.map} +0 -0
- /package/dist/chunks/{blog-post-adapter-bqm9vrja.js.map → blog-post-adapter-njnq5kyv.js.map} +0 -0
- /package/dist/chunks/{index-qpztpfw8.js.map → index-e2scq3d5.js.map} +0 -0
- /package/dist/chunks/{index-cyevdq6v.js.map → index-v3xvnwsn.js.map} +0 -0
- /package/dist/chunks/{linkedin-template-d4av3dpq.js.map → linkedin-template-2yn0zvz4.js.map} +0 -0
- /package/dist/chunks/{rss-datasource-5vhyhygh.js.map → rss-datasource-6drt6y87.js.map} +0 -0
- /package/dist/ui/studio-chunks/{studio-chat-workspace-a7km8rss.js.map → studio-chat-workspace-z9973dz1.js.map} +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Sc as o}from"./index-
|
|
2
|
+
import{Sc as o}from"./index-w5e9n75h.js";import{kj as t}from"./index-a7613zm4.js";var a=t.enum(["generating","draft","queued","published","failed"]),e=t.object({title:t.string(),slug:t.string().optional(),status:a,publishedAt:t.string().datetime().optional(),excerpt:t.string(),author:t.string(),coverImageId:t.string().optional(),ogImageId:t.string().optional(),seriesName:t.string().optional(),seriesIndex:t.number().optional(),ogImage:t.string().url().optional(),ogDescription:t.string().optional(),twitterCard:t.enum(["summary","summary_large_image"]).optional(),canonicalUrl:t.string().url().optional(),atprotoUri:t.string().optional()}),i=e.pick({title:!0,status:!0,publishedAt:!0,seriesName:!0,seriesIndex:!0}).extend({slug:t.string(),error:t.string().optional()}),n=o.extend({entityType:t.literal("post"),metadata:i}),r=n.extend({frontmatter:e,body:t.string(),coverImageUrl:t.string().optional()}),s=r.extend({url:t.string().optional(),typeLabel:t.string().optional(),listUrl:t.string().optional(),listLabel:t.string().optional(),seriesUrl:t.string().optional(),coverImageUrl:t.string().optional(),ogImageUrl:t.string().optional(),coverImageWidth:t.number().optional(),coverImageHeight:t.number().optional(),coverImageSrcset:t.string().optional(),coverImageSizes:t.string().optional()}),d=r.extend({url:t.string(),typeLabel:t.string(),listUrl:t.string(),listLabel:t.string(),seriesUrl:t.string().optional(),coverImageUrl:t.string().optional(),ogImageUrl:t.string().optional(),coverImageWidth:t.number().optional(),coverImageHeight:t.number().optional(),coverImageSrcset:t.string().optional(),coverImageSizes:t.string().optional()});
|
|
3
3
|
export{a as E,e as F,n as G,r as H};
|
|
4
4
|
|
|
5
5
|
//# debugId=A607AE481ED7F7D264756E2164756E21
|
|
6
|
-
//# sourceMappingURL=index-
|
|
6
|
+
//# sourceMappingURL=index-e2scq3d5.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{F as o,G as n}from"./index-
|
|
2
|
+
import{F as o,G as n}from"./index-e2scq3d5.js";import{Oa as s,cd as a}from"./index-w5e9n75h.js";class l extends a{constructor(){super({entityType:"post",purpose:"A long-form published article, essay, or blog post written for an audience.",schema:n,frontmatterSchema:o,supportsCoverImage:!0})}toMarkdown(t){let e=this.extractBody(t.content);try{let r=this.parseFrontMatter(t.content,o),i={...r,slug:r.slug??t.metadata.slug};return this.buildMarkdown(e,i)}catch{return e}}fromMarkdown(t){let e=this.parseFrontMatter(t,o),r=e.slug??s(e.title);return{content:t,entityType:"post",metadata:{title:e.title,slug:r,status:e.status,publishedAt:e.publishedAt,seriesName:e.seriesName,seriesIndex:e.seriesIndex}}}parsePostFrontmatter(t){return this.parseFrontMatter(t.content,o)}createPostContent(t,e){return this.buildMarkdown(e,t)}buildStub(t){let e={title:t.title,slug:t.id,status:"generating",excerpt:"",author:"AI"};return{content:this.buildMarkdown("",e),metadata:{title:t.title,slug:t.id,status:"generating"}}}}var p=new l;
|
|
3
3
|
export{l as B,p as C};
|
|
4
4
|
|
|
5
5
|
//# debugId=69125530DF9E982E64756E2164756E21
|
|
6
|
-
//# sourceMappingURL=index-
|
|
6
|
+
//# sourceMappingURL=index-p49nmsdm.js.map
|
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../entities/blog/src/adapters/blog-post-adapter.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
5
|
-
"import { BaseEntityAdapter } from \"@brains/plugins\";\nimport { slugify } from \"@brains/utils/string-utils\";\nimport {\n blogPostSchema,\n blogPostFrontmatterSchema,\n type BlogPost,\n type BlogPostFrontmatter,\n type BlogPostMetadata,\n} from \"../schemas/blog-post\";\n\n/**\n * Entity adapter for blog post entities\n * Following summary plugin pattern - frontmatter in content, key fields duplicated in metadata\n */\nexport class BlogPostAdapter extends BaseEntityAdapter<\n BlogPost,\n BlogPostMetadata,\n BlogPostFrontmatter\n> {\n constructor() {\n super({\n entityType: \"post\",\n purpose:\n \"A long-form published article, essay, or blog post written for an audience.\",\n schema: blogPostSchema,\n frontmatterSchema: blogPostFrontmatterSchema,\n supportsCoverImage: true,\n });\n }\n\n /**\n * Convert blog post entity to markdown with frontmatter\n * Merges auto-generated metadata (like slug) back into frontmatter\n */\n public override toMarkdown(entity: BlogPost): string {\n const body = this.extractBody(entity.content);\n try {\n const frontmatter = this.parseFrontMatter(\n entity.content,\n blogPostFrontmatterSchema,\n );\n\n // Merge auto-generated slug from metadata if missing in frontmatter\n const completeFrontmatter = {\n ...frontmatter,\n slug: frontmatter.slug ?? entity.metadata.slug,\n };\n\n return this.buildMarkdown(body, completeFrontmatter);\n } catch {\n return body;\n }\n }\n\n /**\n * Parse markdown with frontmatter to create partial blog post entity\n * Syncs frontmatter → metadata for key searchable fields\n * Auto-generates slug from title if not provided in frontmatter\n */\n public fromMarkdown(markdown: string): Partial<BlogPost> {\n const frontmatter = this.parseFrontMatter(\n markdown,\n blogPostFrontmatterSchema,\n );\n const slug = frontmatter.slug ?? slugify(frontmatter.title);\n\n return {\n content: markdown,\n entityType: \"post\",\n metadata: {\n title: frontmatter.title,\n slug,\n status: frontmatter.status,\n publishedAt: frontmatter.publishedAt,\n seriesName: frontmatter.seriesName,\n seriesIndex: frontmatter.seriesIndex,\n },\n };\n }\n\n /** Parse blog post frontmatter from entity content */\n public parsePostFrontmatter(entity: BlogPost): BlogPostFrontmatter {\n return this.parseFrontMatter(entity.content, blogPostFrontmatterSchema);\n }\n\n /** Create blog post content with frontmatter */\n public createPostContent(\n frontmatter: BlogPostFrontmatter,\n body: string,\n ): string {\n return this.buildMarkdown(body, frontmatter);\n }\n\n public buildStub(input: { id: string; title: string }): {\n content: string;\n metadata: BlogPostMetadata;\n } {\n const frontmatter: BlogPostFrontmatter = {\n title: input.title,\n slug: input.id,\n status: \"generating\",\n excerpt: \"\",\n author: \"AI\",\n };\n return {\n content: this.buildMarkdown(\"\", frontmatter),\n metadata: {\n title: input.title,\n slug: input.id,\n status: \"generating\",\n },\n };\n }\n}\n\n// Create default instance\nexport const blogPostAdapter: BlogPostAdapter = new BlogPostAdapter();\n"
|
|
5
|
+
"import { BaseEntityAdapter } from \"@brains/plugins\";\nimport { slugify } from \"@brains/utils/string-utils\";\nimport {\n blogPostSchema,\n blogPostFrontmatterSchema,\n type BlogPost,\n type BlogPostFrontmatter,\n type BlogPostMetadata,\n} from \"../schemas/blog-post\";\n\n/**\n * Entity adapter for blog post entities\n * Following summary plugin pattern - frontmatter in content, key fields duplicated in metadata\n */\nexport class BlogPostAdapter extends BaseEntityAdapter<\n BlogPost,\n BlogPostMetadata,\n BlogPostFrontmatter\n> {\n constructor() {\n super({\n entityType: \"post\",\n purpose:\n \"A long-form published article, essay, or blog post written for an audience.\",\n schema: blogPostSchema,\n frontmatterSchema: blogPostFrontmatterSchema,\n supportsCoverImage: true,\n });\n }\n\n /**\n * Convert blog post entity to markdown with frontmatter\n * Merges auto-generated metadata (like slug) back into frontmatter\n */\n public override toMarkdown(entity: BlogPost): string {\n const body = this.extractBody(entity.content);\n try {\n const frontmatter = this.parseFrontMatter(\n entity.content,\n blogPostFrontmatterSchema,\n );\n\n // Merge auto-generated slug from metadata if missing in frontmatter\n const completeFrontmatter = {\n ...frontmatter,\n slug: frontmatter.slug ?? entity.metadata.slug,\n };\n\n return this.buildMarkdown(body, completeFrontmatter);\n } catch {\n // Stored content is hand-editable. A post whose frontmatter no longer\n // parses should still render its body rather than disappear.\n return body;\n }\n }\n\n /**\n * Parse markdown with frontmatter to create partial blog post entity\n * Syncs frontmatter → metadata for key searchable fields\n * Auto-generates slug from title if not provided in frontmatter\n */\n public fromMarkdown(markdown: string): Partial<BlogPost> {\n const frontmatter = this.parseFrontMatter(\n markdown,\n blogPostFrontmatterSchema,\n );\n const slug = frontmatter.slug ?? slugify(frontmatter.title);\n\n return {\n content: markdown,\n entityType: \"post\",\n metadata: {\n title: frontmatter.title,\n slug,\n status: frontmatter.status,\n publishedAt: frontmatter.publishedAt,\n seriesName: frontmatter.seriesName,\n seriesIndex: frontmatter.seriesIndex,\n },\n };\n }\n\n /** Parse blog post frontmatter from entity content */\n public parsePostFrontmatter(entity: BlogPost): BlogPostFrontmatter {\n return this.parseFrontMatter(entity.content, blogPostFrontmatterSchema);\n }\n\n /** Create blog post content with frontmatter */\n public createPostContent(\n frontmatter: BlogPostFrontmatter,\n body: string,\n ): string {\n return this.buildMarkdown(body, frontmatter);\n }\n\n public buildStub(input: { id: string; title: string }): {\n content: string;\n metadata: BlogPostMetadata;\n } {\n const frontmatter: BlogPostFrontmatter = {\n title: input.title,\n slug: input.id,\n status: \"generating\",\n excerpt: \"\",\n author: \"AI\",\n };\n return {\n content: this.buildMarkdown(\"\", frontmatter),\n metadata: {\n title: input.title,\n slug: input.id,\n status: \"generating\",\n },\n };\n }\n}\n\n// Create default instance\nexport const blogPostAdapter: BlogPostAdapter = new BlogPostAdapter();\n"
|
|
6
6
|
],
|
|
7
|
-
"mappings": ";gGAcO,MAAM,UAAwB,CAInC,CACA,WAAW,EAAG,CACZ,MAAM,CACJ,WAAY,OACZ,QACE,8EACF,OAAQ,EACR,kBAAmB,EACnB,mBAAoB,EACtB,CAAC,EAOa,UAAU,CAAC,EAA0B,CACnD,IAAM,EAAO,KAAK,YAAY,EAAO,OAAO,EAC5C,GAAI,CACF,IAAM,EAAc,KAAK,iBACvB,EAAO,QACP,CACF,EAGM,EAAsB,IACvB,EACH,KAAM,EAAY,MAAQ,EAAO,SAAS,IAC5C,EAEA,OAAO,KAAK,cAAc,EAAM,CAAmB,EACnD,KAAM,
|
|
7
|
+
"mappings": ";gGAcO,MAAM,UAAwB,CAInC,CACA,WAAW,EAAG,CACZ,MAAM,CACJ,WAAY,OACZ,QACE,8EACF,OAAQ,EACR,kBAAmB,EACnB,mBAAoB,EACtB,CAAC,EAOa,UAAU,CAAC,EAA0B,CACnD,IAAM,EAAO,KAAK,YAAY,EAAO,OAAO,EAC5C,GAAI,CACF,IAAM,EAAc,KAAK,iBACvB,EAAO,QACP,CACF,EAGM,EAAsB,IACvB,EACH,KAAM,EAAY,MAAQ,EAAO,SAAS,IAC5C,EAEA,OAAO,KAAK,cAAc,EAAM,CAAmB,EACnD,KAAM,CAGN,OAAO,GASJ,YAAY,CAAC,EAAqC,CACvD,IAAM,EAAc,KAAK,iBACvB,EACA,CACF,EACM,EAAO,EAAY,MAAQ,EAAQ,EAAY,KAAK,EAE1D,MAAO,CACL,QAAS,EACT,WAAY,OACZ,SAAU,CACR,MAAO,EAAY,MACnB,OACA,OAAQ,EAAY,OACpB,YAAa,EAAY,YACzB,WAAY,EAAY,WACxB,YAAa,EAAY,WAC3B,CACF,EAIK,oBAAoB,CAAC,EAAuC,CACjE,OAAO,KAAK,iBAAiB,EAAO,QAAS,CAAyB,EAIjE,iBAAiB,CACtB,EACA,EACQ,CACR,OAAO,KAAK,cAAc,EAAM,CAAW,EAGtC,SAAS,CAAC,EAGf,CACA,IAAM,EAAmC,CACvC,MAAO,EAAM,MACb,KAAM,EAAM,GACZ,OAAQ,aACR,QAAS,GACT,OAAQ,IACV,EACA,MAAO,CACL,QAAS,KAAK,cAAc,GAAI,CAAW,EAC3C,SAAU,CACR,MAAO,EAAM,MACb,KAAM,EAAM,GACZ,OAAQ,YACV,CACF,EAEJ,CAGO,IAAM,EAAmC,IAAI",
|
|
8
8
|
"debugId": "69125530DF9E982E64756E2164756E21",
|
|
9
9
|
"names": []
|
|
10
10
|
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{la as h}from"./index-
|
|
2
|
+
import{la as h}from"./index-bjmmrp5q.js";import{$a as D,Zd as a,bb as R}from"./index-w5e9n75h.js";import{Yf as i}from"./index-tn0cdbvz.js";import{$i as m,_i as c,aj as v}from"./index-jmww3sdn.js";import{kj as e}from"./index-a7613zm4.js";function j(t,n={}){if(!a(t))throw Error("use() expects a package definition returned by a @rizom/brain define helper");return Object.freeze({kind:"rizom-configured-plugin",definition:t,config:Object.freeze({...n})})}function w(t){if(t===null||typeof t!=="object")return!1;return Reflect.get(t,"kind")==="rizom-configured-plugin"&&a(Reflect.get(t,"definition"))&&typeof Reflect.get(t,"config")==="object"}var Oe=e.array(e.string()),Ee=e.record(e.string(),e.unknown()),Ie=e.unknown();var ze=e.enum(["eval"]),g=e.enum(["person","team","organization"]);function M(t){if(t.bundleContract?.trim().length===0)throw Error("Brain bundleContract must not be empty");return t}function p(t){if(Array.isArray(t))return t.map((n)=>p(n));if(i(t))return Object.fromEntries(Object.entries(t).map(([n,o])=>[n,p(o)]));return t}function f(t){return p(t)}var r=e.string().min(1),F=e.strictObject({member:r,value:e.record(e.string(),e.unknown()),overrides:r.optional()}),K=e.custom(i,{message:"Expected an opaque permission config object"}),V=e.strictObject({member:r,config:K,overrides:r.optional()}),G=e.strictObject({id:r,members:e.array(r),config:e.array(F).optional(),permissions:e.array(V).optional(),agentInstructions:e.array(e.string().min(1)).optional(),evalDisable:e.array(r).optional()});function O(t,n,o,L){let x=new Set;for(let[Z,d]of t.entries()){if(x.has(d))L.addIssue({code:e.ZodIssueCode.custom,message:`Duplicate ${n} "${d}"`,path:[o,Z]});x.add(d)}}var q=G.superRefine((t,n)=>{O(t.members,"member","members",n),O(t.evalDisable??[],"eval exclusion","evalDisable",n)});function E(t){return f(q.parse(t))}function U(t){if(t===void 0)return[];return Array.isArray(t)?t:[t]}var H=e.record(e.string(),e.unknown()),ft=e.record(e.string(),e.unknown()),J=e.enum(["eval"]),W=e.enum(["debug","info","warn","error"]),Y=c,s=m,Q=e.strictObject({create:s.optional(),update:s.optional(),delete:s.optional(),extract:s.optional(),publish:s.optional()}),X=e.record(e.string(),Q),I=H.superRefine((t,n)=>{if(typeof t.package!=="string")return;n.addIssue({code:"custom",message:'"package" uses the removed alpha external-plugin contract. Default-export a declarative package definition from a @rizom/brain define helper and compose it with use() in defineBrain().'})}),ut=e.strictObject({brain:e.string().optional(),bundleContract:e.string().trim().min(1).optional(),anchor:g.optional(),site:e.object({package:e.string().optional(),variant:e.string().optional(),theme:e.string().optional(),themeOverride:e.string().optional()}).optional(),name:e.string().optional(),kind:e.string().trim().min(1).optional(),logLevel:W.optional(),logFile:e.string().optional(),port:e.number().optional(),domain:e.string().optional(),database:e.string().optional(),embedding:e.strictObject({enabled:e.boolean().optional()}).optional(),model:e.string().optional(),reasoningEffort:h.optional(),bundles:e.array(e.string().min(1)).optional(),mode:J.optional(),add:e.array(e.string()).optional(),remove:e.array(e.string()).optional(),admins:e.array(e.string()).optional(),anchors:e.array(e.string()).optional(),trusted:e.array(e.string()).optional(),spaces:e.array(e.string()).optional(),plugins:e.record(e.string(),I).optional(),permissions:e.object({admins:e.array(e.string()).optional(),anchors:e.array(e.string()).optional(),trusted:e.array(e.string()).optional(),rules:e.array(e.object({pattern:e.string(),level:Y})).optional(),entityActions:X.optional()}).optional()});var Ct=e.record(e.string(),e.unknown());var te=e.strictObject({pattern:e.string(),level:c}),Ot=e.strictObject({admins:e.array(e.string()).optional(),anchors:e.array(e.string()).optional(),trusted:e.array(e.string()).optional(),rules:e.array(te).optional(),entityActions:v.optional()});var A=`/* ============================================
|
|
3
3
|
THEME BASE - Shared utilities for all themes
|
|
4
4
|
============================================
|
|
5
5
|
This file contains CSS that is IDENTICAL across all themes.
|
|
@@ -528,4 +528,4 @@ import{la as h}from"./index-3qsz79tf.js";import{$a as D,Zd as a,bb as R}from"./i
|
|
|
528
528
|
`+t}var z=e.custom((t)=>R.safeParse(t).success),ae=e.custom((t)=>{if(!i(t))return!1;let{plugin:n,...o}=t;if(n!==void 0&&typeof n!=="function")return!1;return D.safeParse(o).success});var ce=e.looseObject({id:e.string().min(1)}),le=e.looseObject({label:e.string().min(1)}),de=e.custom((t)=>typeof t==="function"),ge=e.looseObject({layouts:e.record(e.string(),e.unknown()).optional(),plugin:de.optional(),pluginConfig:e.record(e.string(),e.unknown()).optional(),routes:e.array(ce).optional(),entityDisplay:e.record(e.string(),le).optional(),content:e.unknown().optional(),themeOverride:e.string().optional(),headScripts:e.array(e.string()).optional(),staticAssets:e.record(e.string(),e.string()).optional()}),qt=e.custom((t)=>ge.safeParse(t).success);var On=e.looseObject({name:e.string().min(1),version:e.string().min(1),dependencies:e.record(e.string(),e.string()).optional(),peerDependencies:e.record(e.string(),e.string()).optional()});export{j as M,w as N,M as O,E as P,U as Q,ie as R};
|
|
529
529
|
|
|
530
530
|
//# debugId=3467F18038196F9664756E2164756E21
|
|
531
|
-
//# sourceMappingURL=index-
|
|
531
|
+
//# sourceMappingURL=index-v3xvnwsn.js.map
|
|
@@ -73,7 +73,7 @@ params: ${t}`);if(this.query=e,this.params=t,this.cause=n,Error.captureStackTrac
|
|
|
73
73
|
`).slice(1).join(`
|
|
74
74
|
`).trim()}if(o){let s=o.replace(/\s+/g," ").trim(),c=s.length>500?s.substring(0,500)+"...":s;t.push(c)}}return t.join(`
|
|
75
75
|
|
|
76
|
-
`)}parse(e){throw Error("BaseEntityFormatter is for display only. Use BaseEntityAdapter for parsing operations.")}}class DS{cache=null;cacheParseError=null;logger;entityService;entityType;defaultBody;readScope;constructor(e,t,n,r,o="public"){this.entityService=e,this.logger=t.child(this.constructor.name),this.entityType=n,this.defaultBody=r,this.readScope=o}async initialize(){if(await this.load())return;if(await this.load())return;this.logger.info(`No ${this.entityType} found, creating default ${this.entityType}`);try{let e=this.createContent(this.defaultBody);await this.entityService.createEntity({entity:{id:this.entityType,entityType:this.entityType,content:e,metadata:{}}}),await this.load(),this.logger.info(`Default ${this.entityType} created successfully`)}catch(e){this.logger.error(`Failed to create default ${this.entityType}`,{error:e})}}get(){if(this.cache&&!this.cacheParseError)return this.parseBody(this.cache.content);return this.defaultBody}getContent(){if(this.cache)return this.cache.content;return this.createContent(this.defaultBody)}async refreshCache(){await this.load()}async load(){try{let e=await this.entityService.getEntity({entityType:this.entityType,id:this.entityType,visibilityScope:this.readScope});if(this.cache=e,this.cacheParseError=null,e)try{return this.parseBody(e.content),this.logger.debug(`${this.entityType} loaded`),!0}catch(t){return this.cacheParseError=t instanceof Error?t:Error(String(t)),this.logger.error(`Failed to parse ${this.entityType} \u2014 using default. Fix the entity content to clear this error.`,{error:this.cacheParseError.message}),!0}else this.logger.debug(`No ${this.entityType} found in database`)}catch(e){this.logger.warn(`Failed to load ${this.entityType}`,{error:e}),this.cache=null,this.cacheParseError=null}return!1}}function nme(e,t){let n=e.getAdapter(t.entityType);if(!n.buildStub)return;let r=n.buildStub({id:t.id,title:t.title}),o=new Date().toISOString();return{id:t.id,entityType:t.entityType,content:r.content,metadata:r.metadata,visibility:"public",created:o,updated:o,contentHash:""}}function M2(e,t){return t==="public"?e:`${e}-${t}`}function _2(e,t,n,r){let o=r.getEntityTypeConfig(e).publish?.publishStatuses;if(!o?.length||typeof n!=="string")return"non-publish";let i=typeof t==="string"&&o.includes(t);if(!o.includes(n))return"non-publish";return i?"within-publish-set":"boundary"}class SP{dataSources=new Map;logger;static createFresh(e){return new SP(e)}constructor(e){this.logger=e.child("DataSourceRegistry")}register(e){let t=e.id.includes(":")?e.id:`shell:${e.id}`;this.registerWithId(t,e)}registerWithId(e,t){if(this.dataSources.has(e)){let n=Error(`DataSource with id "${e}" already exists`);throw this.logger.error("DataSource registration failed",{error:n,id:e}),n}this.dataSources.set(e,t),this.logger.debug("DataSource registered",{id:e,name:t.name})}unregister(e){if(this.dataSources.delete(e))this.logger.debug("DataSource unregistered",{id:e});else this.logger.warn("Attempted to unregister non-existent DataSource",{id:e})}get(e){return this.dataSources.get(e)}has(e){return this.dataSources.has(e)}list(){return Array.from(this.dataSources.values())}getIds(){return Array.from(this.dataSources.keys())}getByCapability(e){return this.list().filter((t)=>{switch(e){case"canFetch":return!!t.fetch;case"canGenerate":return!!t.generate;case"canTransform":return!!t.transform;default:return!1}})}find(e){return this.list().filter(e)}clear(){let e=this.dataSources.size;this.dataSources.clear(),this.logger.debug("DataSource registry cleared",{count:e})}}var F2=a.object({currentPage:a.number(),totalPages:a.number(),totalItems:a.number(),pageSize:a.number(),hasNextPage:a.boolean(),hasPrevPage:a.boolean()});function vP(e,t,n){let r=Math.max(1,Math.ceil(e/n));return{currentPage:t,totalPages:r,totalItems:e,pageSize:n,hasNextPage:t<r,hasPrevPage:t>1}}async function TP(e,t,n,r,o="public"){try{let i=await e.getEntity({entityType:t,id:n,visibilityScope:o});if(i)return i;let s=await e.listEntities({entityType:t,options:{limit:1,filter:{metadata:{slug:n},visibilityScope:o}}});if(s[0])return s[0];let c=await e.listEntities({entityType:t,options:{limit:1,filter:{metadata:{title:n},visibilityScope:o}}});if(c[0])return c[0];let l=await e.listEntities({entityType:t,options:{limit:1,filter:{metadata:{title:sd(n)},visibilityScope:o}}});if(l[0])return l[0];let u=await e.listEntities({entityType:t,options:{limit:200,filter:{visibilityScope:o}}}),d=sd(n);return u.find((m)=>typeof m.metadata.title==="string"&&sd(m.metadata.title)===d)??null}catch(i){if(r)r.error(`Failed to find entity ${t}:${n}`,{error:i});return null}}async function N2(e,t,n,r,o="Entity",i="public"){let s=await TP(e,t,n,r,i);if(!s)return{ok:!1,error:`${o} not found: ${t}/${n}`};return{ok:!0,entity:s}}function Ys(e,t){return e.parse(t)}class Xs{callback;heartbeatInterval;constructor(e){this.callback=e}static from(e){if(!e)return;return new Xs(e)}static noop(){return new Xs(async()=>{})}createSub(e){let{scale:t}=e??{};if(t){let{start:n,end:r}=t,o=r-n;return new Xs(async(i)=>{let s=n+i.progress/(i.total??100)*o;await this.callback({...i,progress:s,total:100})})}return new Xs(this.callback)}async report(e){await this.callback(e)}startHeartbeat(e,t=5000){this.stopHeartbeat(),this.heartbeatInterval=setInterval(()=>{this.report({message:e,progress:0}).catch(()=>{})},t)}stopHeartbeat(){if(this.heartbeatInterval)clearInterval(this.heartbeatInterval),this.heartbeatInterval=void 0}toCallback(){return this.callback}}var rme=a.object({enabled:a.boolean().describe("Whether the plugin is enabled"),debug:a.boolean().describe("Enable debug logging for this plugin")});function ome(e){return e.map((t)=>`${t.path||"<root>"}: ${t.message}`).join("; ")}class rg extends Error{pluginId;issues;constructor(e,t){super(`Invalid plugin config for ${e} at ${ome(t)}; correct the listed fields in brain.yaml or the package's use() configuration`);this.name="PluginConfigValidationError",this.pluginId=e,this.issues=t}}var ime=a.object({toolName:a.string(),args:a.unknown(),progressToken:a.union([a.string(),a.number()]).optional(),hasProgress:a.boolean().optional(),interfaceType:a.string(),actor:zl,displayName:a.string().optional(),conversationId:a.string().optional(),channelId:a.string().optional(),channelName:a.string().optional(),runId:a.string().optional(),toolCallId:a.string().optional(),userPermissionLevel:a.enum(["admin","trusted","public"]).optional(),isAnchor:a.boolean().optional(),signal:a.custom((e)=>e instanceof AbortSignal).optional()}),sme=a.object({resourceUri:a.string()});class Ll{id;version;description;packageName;config;context;get logger(){return this.context?.logger??qi.createFresh({context:this.id})}constructor(e,t,n,r){this.id=e,this.packageName=t.name,this.version=t.version,this.description=t.description??`${t.name} plugin`;let o=r.safeParse(n);if(!o.success)throw new rg(e,o.error.issues.map((i)=>({path:i.path.map(String).join("."),code:i.code,message:i.message})));this.config=o.data}setupMessageHandlers(e){e.messaging.subscribe(og.toolExecute(this.id),async(t)=>{try{let n=ime.safeParse(t.payload);if(!n.success)return{success:!1,error:"Invalid tool execution request format"};let{toolName:r,args:o,progressToken:i,hasProgress:s,interfaceType:c,actor:l,displayName:u,conversationId:d,channelId:m,channelName:g,runId:y,toolCallId:S,userPermissionLevel:T,isAnchor:R,signal:se}=n.data,ee=(await this.getTools()).find((ue)=>ue.name===r);if(!ee)return{success:!1,error:`Tool not found: ${r}`};let me={interfaceType:c,actor:l,...u&&{displayName:u},...d&&{conversationId:d},...m&&{channelId:m},...g&&{channelName:g},...y&&{runId:y},...S&&{toolCallId:S},...T&&{userPermissionLevel:T},...R!==void 0&&{isAnchor:R},...se&&{signal:se},...s&&i!==void 0&&{progressToken:i,sendProgress:async(ue)=>{await e.messaging.send({type:og.progress(this.id),payload:{progressToken:i,notification:ue}})}}};return{success:!0,data:await ee.handler(o,me)}}catch(n){return this.logger.error("Tool execution error",n),{success:!1,error:We(n)}}}),e.messaging.subscribe(og.resourceGet(this.id),async(t)=>{try{let n=sme.safeParse(t.payload);if(!n.success)return{success:!1,error:"Invalid resource get request format"};let{resourceUri:r}=n.data,i=(await this.getResources()).find((c)=>c.uri===r);if(!i)return{success:!1,error:`Resource not found: ${r}`};return{success:!0,data:await i.handler()}}catch(n){return this.logger.error("Resource fetch error",n),{success:!1,error:We(n)}}})}async onRegister(e){}async onRegistrationComplete(e){}async finalizeRegistration(){await this.onRegistrationComplete(this.getContext())}async onReady(e){}async ready(){await this.onReady(this.getContext())}async getCapabilities(){let e=await this.getInstructions();return{tools:await this.getTools(),resources:await this.getResources(),...e&&{instructions:e}}}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(e){return"public"}createProgressBridge(e){if(!e)return;let t=this.context;if(!t)return;let n=this.id;return Xs.from(async(r)=>{await t.messaging.send({type:og.progress(n),payload:{progressToken:e,notification:{progress:r.progress,total:r.total,message:r.message}}})})}}var z2=a.object({id:a.string(),template:a.string(),content:a.unknown().optional(),dataQuery:a.looseObject({entityType:a.string().optional(),template:a.string().optional(),query:a.looseObject({id:a.string().optional(),limit:a.number().optional(),offset:a.number().optional()}).optional()}).optional(),order:a.number().optional()}),EP=["primary","secondary"],L2=a.object({show:a.boolean().default(!1),label:a.string().optional(),slot:a.enum(EP).default("primary"),priority:a.number().min(0).max(100).default(50)}).optional(),wP=a.object({id:a.string(),path:a.string(),title:a.string().default(""),pageLabel:a.string().optional(),description:a.string().default(""),sections:a.array(z2).default([]),layout:a.string().default("default"),fullscreen:a.boolean().optional(),pluginId:a.string().optional(),sourceEntityType:a.string().optional(),external:a.boolean().optional(),navigation:L2}),B2=a.object({routes:a.array(wP),pluginId:a.string()}),q2=a.object({paths:a.array(a.string()).optional(),pluginId:a.string().optional()}),$2=a.object({pluginId:a.string().optional()}),U2=a.object({path:a.string()}),MS=a.object({label:a.string(),href:a.string(),priority:a.number()});var ame="site:metadata:get",cme="site:metadata:updated",CP=a.object({heading:a.string().describe("Main CTA heading text"),buttonText:a.string().describe("Call-to-action button text"),buttonLink:a.string().describe("URL or anchor for the CTA button")}),W2=a.object({blurb:a.string().optional().describe("Short italic subtitle under the section title")}),_S=a.object({represents:a.enum(["brain","anchor"]).default("anchor").describe("Identity represented by the site"),title:a.string().describe("The site's title"),description:a.string().describe("The site's description"),url:a.string().optional().describe("Canonical site URL"),copyright:a.string().optional().describe("Copyright notice text"),logo:a.boolean().optional().describe("Whether to display logo instead of title text in header"),themeMode:a.enum(["light","dark"]).optional().describe("Default theme mode"),analyticsScript:a.string().optional().describe("Analytics script HTML"),cta:CP.optional().describe("Call-to-action configuration"),sections:a.record(a.string(),W2).optional().describe("Optional per-section blurbs, keyed by section id (e.g. 'essays', 'presentations', 'about'). Used by homepage templates that render editorial section headers.")});var lme=a.object({platform:a.enum(["github","instagram","linkedin","email","website"]).describe("Social media platform"),url:a.string().describe("Profile or contact URL"),label:a.string().optional().describe("Optional display label")}),ume=_S.extend({copyright:a.string(),navigation:a.object({primary:a.array(MS),secondary:a.array(MS)}),socialLinks:a.array(lme).optional().describe("Social media links from profile metadata")});var pme=a.record(a.string(),a.unknown());function IP(e,t){let n=pme.safeParse(e);return n.success&&t.every((r)=>(r in n.data))}class Lp{parse(e){throw Error("This response format is read-only and cannot be parsed back to data")}formatKeyValue(e,t){if(t===void 0||t===null)return"";return`**${e}:** ${String(t)}`}formatList(e){return e.map((t)=>`- ${String(t)}`).join(`
|
|
76
|
+
`)}parse(e){throw Error("BaseEntityFormatter is for display only. Use BaseEntityAdapter for parsing operations.")}}class DS{cache=null;cacheParseError=null;logger;entityService;entityType;defaultBody;readScope;constructor(e,t,n,r,o="public"){this.entityService=e,this.logger=t.child(this.constructor.name),this.entityType=n,this.defaultBody=r,this.readScope=o}async initialize(){if(await this.load())return;if(await this.load())return;this.logger.info(`No ${this.entityType} found, creating default ${this.entityType}`);try{let e=this.createContent(this.defaultBody);await this.entityService.createEntity({entity:{id:this.entityType,entityType:this.entityType,content:e,metadata:{}}}),await this.load(),this.logger.info(`Default ${this.entityType} created successfully`)}catch(e){this.logger.error(`Failed to create default ${this.entityType}`,{error:e})}}get(){if(this.cache&&!this.cacheParseError)return this.parseBody(this.cache.content);return this.defaultBody}getContent(){if(this.cache)return this.cache.content;return this.createContent(this.defaultBody)}async refreshCache(){await this.load()}async load(){try{let e=await this.entityService.getEntity({entityType:this.entityType,id:this.entityType,visibilityScope:this.readScope});if(this.cache=e,this.cacheParseError=null,e)try{return this.parseBody(e.content),this.logger.debug(`${this.entityType} loaded`),!0}catch(t){return this.cacheParseError=t instanceof Error?t:Error(String(t)),this.logger.error(`Failed to parse ${this.entityType} \u2014 using default. Fix the entity content to clear this error.`,{error:this.cacheParseError.message}),!0}else this.logger.debug(`No ${this.entityType} found in database`)}catch(e){this.logger.warn(`Failed to load ${this.entityType}`,{error:e}),this.cache=null,this.cacheParseError=null}return!1}}function nme(e,t){let n=e.getAdapter(t.entityType);if(!n.buildStub)return;let r=n.buildStub({id:t.id,title:t.title}),o=new Date().toISOString();return{id:t.id,entityType:t.entityType,content:r.content,metadata:r.metadata,visibility:"public",created:o,updated:o,contentHash:""}}function M2(e,t){return t==="public"?e:`${e}-${t}`}function _2(e,t,n,r){let o=r.getEntityTypeConfig(e).publish?.publishStatuses;if(!o?.length||typeof n!=="string")return"non-publish";let i=typeof t==="string"&&o.includes(t);if(!o.includes(n))return"non-publish";return i?"within-publish-set":"boundary"}class SP{dataSources=new Map;logger;static createFresh(e){return new SP(e)}constructor(e){this.logger=e.child("DataSourceRegistry")}register(e){let t=e.id.includes(":")?e.id:`shell:${e.id}`;this.registerWithId(t,e)}registerWithId(e,t){if(this.dataSources.has(e)){let n=Error(`DataSource with id "${e}" already exists`);throw this.logger.error("DataSource registration failed",{error:n,id:e}),n}this.dataSources.set(e,t),this.logger.debug("DataSource registered",{id:e,name:t.name})}unregister(e){if(this.dataSources.delete(e))this.logger.debug("DataSource unregistered",{id:e});else this.logger.warn("Attempted to unregister non-existent DataSource",{id:e})}get(e){return this.dataSources.get(e)}has(e){return this.dataSources.has(e)}list(){return Array.from(this.dataSources.values())}getIds(){return Array.from(this.dataSources.keys())}getByCapability(e){return this.list().filter((t)=>{switch(e){case"canFetch":return!!t.fetch;case"canGenerate":return!!t.generate;case"canTransform":return!!t.transform;default:return!1}})}find(e){return this.list().filter(e)}clear(){let e=this.dataSources.size;this.dataSources.clear(),this.logger.debug("DataSource registry cleared",{count:e})}}var F2=a.object({currentPage:a.number(),totalPages:a.number(),totalItems:a.number(),pageSize:a.number(),hasNextPage:a.boolean(),hasPrevPage:a.boolean()});function vP(e,t,n){let r=Math.max(1,Math.ceil(e/n));return{currentPage:t,totalPages:r,totalItems:e,pageSize:n,hasNextPage:t<r,hasPrevPage:t>1}}async function TP(e,t,n,r,o="public"){try{let i=await e.getEntity({entityType:t,id:n,visibilityScope:o});if(i)return i;let s=await e.listEntities({entityType:t,options:{limit:1,filter:{metadata:{slug:n},visibilityScope:o}}});if(s[0])return s[0];let c=await e.listEntities({entityType:t,options:{limit:1,filter:{metadata:{title:n},visibilityScope:o}}});if(c[0])return c[0];let l=await e.listEntities({entityType:t,options:{limit:1,filter:{metadata:{title:sd(n)},visibilityScope:o}}});if(l[0])return l[0];let u=await e.listEntities({entityType:t,options:{limit:200,filter:{visibilityScope:o}}}),d=sd(n);return u.find((m)=>typeof m.metadata.title==="string"&&sd(m.metadata.title)===d)??null}catch(i){if(r)r.error(`Failed to find entity ${t}:${n}`,{error:i});throw i}}async function N2(e,t,n,r,o="Entity",i="public"){let s=await TP(e,t,n,r,i);if(!s)return{ok:!1,error:`${o} not found: ${t}/${n}`};return{ok:!0,entity:s}}function Ys(e,t){return e.parse(t)}class Xs{callback;heartbeatInterval;constructor(e){this.callback=e}static from(e){if(!e)return;return new Xs(e)}static noop(){return new Xs(async()=>{})}createSub(e){let{scale:t}=e??{};if(t){let{start:n,end:r}=t,o=r-n;return new Xs(async(i)=>{let s=n+i.progress/(i.total??100)*o;await this.callback({...i,progress:s,total:100})})}return new Xs(this.callback)}async report(e){await this.callback(e)}startHeartbeat(e,t=5000){this.stopHeartbeat(),this.heartbeatInterval=setInterval(()=>{this.report({message:e,progress:0}).catch(()=>{})},t)}stopHeartbeat(){if(this.heartbeatInterval)clearInterval(this.heartbeatInterval),this.heartbeatInterval=void 0}toCallback(){return this.callback}}var rme=a.object({enabled:a.boolean().describe("Whether the plugin is enabled"),debug:a.boolean().describe("Enable debug logging for this plugin")});function ome(e){return e.map((t)=>`${t.path||"<root>"}: ${t.message}`).join("; ")}class rg extends Error{pluginId;issues;constructor(e,t){super(`Invalid plugin config for ${e} at ${ome(t)}; correct the listed fields in brain.yaml or the package's use() configuration`);this.name="PluginConfigValidationError",this.pluginId=e,this.issues=t}}var ime=a.object({toolName:a.string(),args:a.unknown(),progressToken:a.union([a.string(),a.number()]).optional(),hasProgress:a.boolean().optional(),interfaceType:a.string(),actor:zl,displayName:a.string().optional(),conversationId:a.string().optional(),channelId:a.string().optional(),channelName:a.string().optional(),runId:a.string().optional(),toolCallId:a.string().optional(),userPermissionLevel:a.enum(["admin","trusted","public"]).optional(),isAnchor:a.boolean().optional(),signal:a.custom((e)=>e instanceof AbortSignal).optional()}),sme=a.object({resourceUri:a.string()});class Ll{id;version;description;packageName;config;context;get logger(){return this.context?.logger??qi.createFresh({context:this.id})}constructor(e,t,n,r){this.id=e,this.packageName=t.name,this.version=t.version,this.description=t.description??`${t.name} plugin`;let o=r.safeParse(n);if(!o.success)throw new rg(e,o.error.issues.map((i)=>({path:i.path.map(String).join("."),code:i.code,message:i.message})));this.config=o.data}setupMessageHandlers(e){e.messaging.subscribe(og.toolExecute(this.id),async(t)=>{try{let n=ime.safeParse(t.payload);if(!n.success)return{success:!1,error:"Invalid tool execution request format"};let{toolName:r,args:o,progressToken:i,hasProgress:s,interfaceType:c,actor:l,displayName:u,conversationId:d,channelId:m,channelName:g,runId:y,toolCallId:S,userPermissionLevel:T,isAnchor:R,signal:se}=n.data,ee=(await this.getTools()).find((ue)=>ue.name===r);if(!ee)return{success:!1,error:`Tool not found: ${r}`};let me={interfaceType:c,actor:l,...u&&{displayName:u},...d&&{conversationId:d},...m&&{channelId:m},...g&&{channelName:g},...y&&{runId:y},...S&&{toolCallId:S},...T&&{userPermissionLevel:T},...R!==void 0&&{isAnchor:R},...se&&{signal:se},...s&&i!==void 0&&{progressToken:i,sendProgress:async(ue)=>{await e.messaging.send({type:og.progress(this.id),payload:{progressToken:i,notification:ue}})}}};return{success:!0,data:await ee.handler(o,me)}}catch(n){return this.logger.error("Tool execution error",n),{success:!1,error:We(n)}}}),e.messaging.subscribe(og.resourceGet(this.id),async(t)=>{try{let n=sme.safeParse(t.payload);if(!n.success)return{success:!1,error:"Invalid resource get request format"};let{resourceUri:r}=n.data,i=(await this.getResources()).find((c)=>c.uri===r);if(!i)return{success:!1,error:`Resource not found: ${r}`};return{success:!0,data:await i.handler()}}catch(n){return this.logger.error("Resource fetch error",n),{success:!1,error:We(n)}}})}async onRegister(e){}async onRegistrationComplete(e){}async finalizeRegistration(){await this.onRegistrationComplete(this.getContext())}async onReady(e){}async ready(){await this.onReady(this.getContext())}async getCapabilities(){let e=await this.getInstructions();return{tools:await this.getTools(),resources:await this.getResources(),...e&&{instructions:e}}}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(e){return"public"}createProgressBridge(e){if(!e)return;let t=this.context;if(!t)return;let n=this.id;return Xs.from(async(r)=>{await t.messaging.send({type:og.progress(n),payload:{progressToken:e,notification:{progress:r.progress,total:r.total,message:r.message}}})})}}var z2=a.object({id:a.string(),template:a.string(),content:a.unknown().optional(),dataQuery:a.looseObject({entityType:a.string().optional(),template:a.string().optional(),query:a.looseObject({id:a.string().optional(),limit:a.number().optional(),offset:a.number().optional()}).optional()}).optional(),order:a.number().optional()}),EP=["primary","secondary"],L2=a.object({show:a.boolean().default(!1),label:a.string().optional(),slot:a.enum(EP).default("primary"),priority:a.number().min(0).max(100).default(50)}).optional(),wP=a.object({id:a.string(),path:a.string(),title:a.string().default(""),pageLabel:a.string().optional(),description:a.string().default(""),sections:a.array(z2).default([]),layout:a.string().default("default"),fullscreen:a.boolean().optional(),pluginId:a.string().optional(),sourceEntityType:a.string().optional(),external:a.boolean().optional(),navigation:L2}),B2=a.object({routes:a.array(wP),pluginId:a.string()}),q2=a.object({paths:a.array(a.string()).optional(),pluginId:a.string().optional()}),$2=a.object({pluginId:a.string().optional()}),U2=a.object({path:a.string()}),MS=a.object({label:a.string(),href:a.string(),priority:a.number()});var ame="site:metadata:get",cme="site:metadata:updated",CP=a.object({heading:a.string().describe("Main CTA heading text"),buttonText:a.string().describe("Call-to-action button text"),buttonLink:a.string().describe("URL or anchor for the CTA button")}),W2=a.object({blurb:a.string().optional().describe("Short italic subtitle under the section title")}),_S=a.object({represents:a.enum(["brain","anchor"]).default("anchor").describe("Identity represented by the site"),title:a.string().describe("The site's title"),description:a.string().describe("The site's description"),url:a.string().optional().describe("Canonical site URL"),copyright:a.string().optional().describe("Copyright notice text"),logo:a.boolean().optional().describe("Whether to display logo instead of title text in header"),themeMode:a.enum(["light","dark"]).optional().describe("Default theme mode"),analyticsScript:a.string().optional().describe("Analytics script HTML"),cta:CP.optional().describe("Call-to-action configuration"),sections:a.record(a.string(),W2).optional().describe("Optional per-section blurbs, keyed by section id (e.g. 'essays', 'presentations', 'about'). Used by homepage templates that render editorial section headers.")});var lme=a.object({platform:a.enum(["github","instagram","linkedin","email","website"]).describe("Social media platform"),url:a.string().describe("Profile or contact URL"),label:a.string().optional().describe("Optional display label")}),ume=_S.extend({copyright:a.string(),navigation:a.object({primary:a.array(MS),secondary:a.array(MS)}),socialLinks:a.array(lme).optional().describe("Social media links from profile metadata")});var pme=a.record(a.string(),a.unknown());function IP(e,t){let n=pme.safeParse(e);return n.success&&t.every((r)=>(r in n.data))}class Lp{parse(e){throw Error("This response format is read-only and cannot be parsed back to data")}formatKeyValue(e,t){if(t===void 0||t===null)return"";return`**${e}:** ${String(t)}`}formatList(e){return e.map((t)=>`- ${String(t)}`).join(`
|
|
77
77
|
`)}formatTable(e,t){let n=`| ${e.join(" | ")} |`,r=`| ${e.map(()=>"---").join(" | ")} |`,o=t.map((i)=>`| ${i.map((s)=>String(s??"")).join(" | ")} |`).join(`
|
|
78
78
|
`);return`${n}
|
|
79
79
|
${r}
|
|
@@ -132,5 +132,5 @@ Result:`);if(n===-1)return;let r=e.slice(n+9).trim();if(!r)return;try{return JSO
|
|
|
132
132
|
`)}function LG(e){return{identity:e.identity,interfaceType:e.interfaceType,role:e.role??"user",...e.displayName?{displayName:e.displayName}:{},...e.username?{username:e.username}:{},...e.isBot!==void 0?{isBot:vxe(e.isBot)}:{}}}function vxe(e){if(typeof e==="boolean")return e;return e.toLowerCase()==="true"}function BG(e){return{...e.messageId?{messageId:e.messageId}:{},...e.channelId?{channelId:e.channelId}:{},...e.channelName?{channelName:e.channelName}:{},...e.threadId?{threadId:e.threadId}:{},...e.metadata?{metadata:e.metadata}:{}}}function qG(e){if(e.skippedMessages.length===0)return{message:e.message};return{message:["Messages received while the previous response was still running (oldest first, for context only):",...e.skippedMessages.map(Txe),"","Latest message to answer:",e.message].join(`
|
|
133
133
|
`),metadata:{supersededMessageCount:e.skippedMessages.length,supersededMessageIds:e.skippedMessages.map((r)=>r.id).filter((r)=>r!==void 0)}}}function Txe(e){let t=e.text.trim(),n=e.authorName?.trim();return n?`- ${n}: ${t}`:`- ${t}`}async function Oxe(e){let{entityType:t,title:n,deriveId:r,regeneratePrompt:o,context:i}=e,s=r(n),c=await i.entityService.getEntity({entityType:t,id:s});if(!c||c.metadata.status==="generating")return n;i.logger.debug(`Entity ID collision: ${t}/${s}, asking AI for a new title`);let l=a.object({title:a.string().max(80).describe("A short, unique title (2-6 words)")}),{object:u}=await i.ai.generateObject(`The title "${n}" is already taken. ${o}`,l),d=u.title;return i.logger.debug(`AI suggested new title: "${d}"`),d}class jv{tail=Promise.resolve();run(e){let t=this.tail.then(()=>e());return this.tail=t.then(()=>{return},()=>{return}),t}async settle(){await this.tail}}var Dxe="current";class $G{store;schema;createEmpty;key;queue=new jv;statePromise;constructor(e){this.store=e.runtimeState.scoped({namespace:e.namespace,schema:e.schema}),this.schema=e.schema,this.createEmpty=e.createEmpty,this.key=e.key??Dxe}mutate(e){return this.queue.run(async()=>{let t=await this.load(),n=await e(t);return await this.persist(t),n})}async snapshot(){return await this.settle(),structuredClone(await this.load())}settle(){return this.queue.settle()}load(){return this.statePromise??=this.store.get(this.key).then((e)=>e??this.createEmpty()),this.statePromise}async persist(e){await this.store.set(this.key,this.schema.parse(e))}}var MO=Ao.extend({id:a.literal("brain-character"),entityType:a.literal("brain-character")}),zv=a.object({name:a.string().describe("The brain's friendly display name"),role:a.string().describe("The brain's primary role"),purpose:a.string().describe("The brain's purpose and goals"),values:a.array(a.string()).describe("Core values that guide behavior")});var Mxe=a.record(a.string(),a.unknown());class Ng extends oc{generateFrontMatter(e){let t=this.parseFrontmatter(e.content);return this.buildMarkdown("",Mxe.parse(t))}}class Lv extends Ng{constructor(){super({entityType:"brain-character",purpose:"The brain's own identity, character, and purpose (singleton).",schema:MO,frontmatterSchema:zv,isSingleton:!0,hasBody:!1})}createCharacterContent(e){return this.buildMarkdown("",e)}parseCharacterBody(e){return this.parseFrontmatter(e)}toMarkdown(e){return this.generateFrontMatter(e)}fromMarkdown(e){return{content:e,entityType:"brain-character"}}extractMetadata(e){let t=this.parseFrontmatter(e.content);return{role:t.role,values:t.values}}}class jg extends DS{codec;constructor(e,t,n,r,o,i){super(e,t,n,r,$i(o));this.codec=i}parseBody(e){return this.codec.parse(e)}createContent(e){return this.codec.create(e)}}class Bv extends jg{static getDefaultCharacter(){return{name:"Brain",role:"Knowledge assistant",purpose:"Help organize, understand, and retrieve information from your knowledge base",values:["clarity","accuracy","helpfulness"]}}static createFresh(e,t,n){return new Bv(e,t,n)}constructor(e,t,n){let r=new Lv;super(e,t,"brain-character",n??Bv.getDefaultCharacter(),"brain character is loaded at bootstrap before any user is in scope",{parse:(o)=>r.parseCharacterBody(o),create:(o)=>r.createCharacterContent(o)})}getCharacter(){return this.get()}getCharacterContent(){return this.getContent()}}var _O=Ao.extend({id:a.literal("anchor-profile"),entityType:a.literal("anchor-profile")}),UG=a.enum(["person","team","organization"]),Zl=a.object({name:a.string().describe("Name of the anchor"),organization:a.string().optional().describe("Organization the anchor belongs to"),description:a.string().optional().describe("Short description or biography"),avatar:a.string().optional().describe("URL or asset path to avatar/logo"),website:a.string().optional().describe("Primary website URL"),email:a.string().optional().describe("Contact email"),socialLinks:a.array(a.object({platform:a.enum(["github","instagram","linkedin","email","website"]).describe("Social media platform"),url:a.string().describe("Profile or contact URL"),label:a.string().optional().describe("Optional display label")})).optional().describe("Social media and contact links")});class qv extends Ng{constructor(){super({entityType:"anchor-profile",purpose:"The profile of the brain's Anchor (singleton).",schema:_O,frontmatterSchema:Zl,isSingleton:!0,hasBody:!0})}createProfileContent(e){let t=Zl.parse(e);return this.buildMarkdown("",t)}parseProfileBody(e,t){if(t){let{metadata:n,content:r}=or(e,t);return r?{...n,story:r}:n}return this.parseFrontmatter(e)}fromMarkdown(e){return{content:e,entityType:"anchor-profile"}}extractMetadata(e){let t=this.parseFrontmatter(e.content);return{name:t.name,email:t.email,website:t.website}}}class zg extends jg{static getDefaultProfile(){return{name:"Unknown"}}static createFresh(e,t,n){return new zg(e,t,n)}constructor(e,t,n){let r=new qv;super(e,t,"anchor-profile",n??zg.getDefaultProfile(),"anchor profile is loaded at bootstrap before any user is in scope",{parse:(o)=>r.parseProfileBody(o),create:(o)=>r.createProfileContent(o)})}getProfile(){return this.get()}getProfileContent(){return this.getContent()}}var $v=a.enum(["person","team","organization"]),_xe=a.object({kind:a.string().trim().min(1),category:$v,labels:a.object({singular:a.string().trim().min(1),plural:a.string().trim().min(1)})});function Fxe(e){if(typeof e!=="object"||e===null||!("shape"in e)||!("safeParse"in e)||typeof e.safeParse!=="function")throw Error("Profile kind fields must be a Zod object schema")}class WG{selectedKind;registrations=new Map;finalized=!1;resolved=null;selectedDefinition;constructor(e){let t=e?.trim();this.selectedKind=t===""?void 0:t}register(e,t){if(this.finalized)throw Error("Profile kind registration is closed");let n=_xe.parse(t);Fxe(t.fields);let r=Object.freeze({...t,kind:n.kind,category:n.category,labels:Object.freeze({...n.labels})}),o=this.registrations.get(n.kind)??[];o.push({pluginId:e,definition:r}),this.registrations.set(n.kind,o)}unregisterPlugin(e){for(let[t,n]of this.registrations){let r=n.filter((o)=>o.pluginId!==e);if(r.length===0)this.registrations.delete(t);else this.registrations.set(t,r)}}finalize(){if(this.finalized)return this.resolved;let t=[...this.registrations.entries()].filter(([,r])=>r.length>1).sort(([r],[o])=>r.localeCompare(o))[0];if(t){let[r,o]=t,i=o.map((s)=>s.pluginId).sort().join(", ");throw Error(`Profile kind "${r}" is registered by multiple plugins: ${i}`)}if(!this.selectedKind)return this.finalized=!0,this.resolved=null,null;let n=this.registrations.get(this.selectedKind)?.[0];if(!n)throw Error(`Selected profile kind "${this.selectedKind}" is not registered`);return this.selectedDefinition=n.definition,this.resolved=Object.freeze({kind:n.definition.kind,category:n.definition.category,labels:Object.freeze({...n.definition.labels})}),this.finalized=!0,this.resolved}getResolved(){return this.assertFinalized(),this.resolved}getSelectedDefinition(){return this.assertFinalized(),this.selectedDefinition}isFinalized(){return this.finalized}assertFinalized(){if(!this.finalized)throw Error("Profile kind selection has not been finalized")}}var HG=30000;class NO{logger;resolver;links=[];actorIndex=new Map;negativeActorIndex=new Map;static createFresh(e,t){return new NO(e,t)}constructor(e,t){this.logger=e.child("CanonicalIdentityService"),this.resolver=t}async refreshCache(){this.links=[],this.actorIndex=new Map,this.negativeActorIndex=new Map,this.logger.debug("Canonical identity links refreshed",{linkCount:0,actorCount:0})}getLinks(){return this.links}resolveActor(e){let t=FO(e),n=this.actorIndex.get(t);if(!n)return null;if(n.expiresAt<=Date.now())return this.actorIndex.delete(t),null;return n.resolution}async enrichActor(e){if(e.identity.kind==="user"&&e.identity.canonicalId||e.role!=="user")return e;let t=this.resolveActor(e.identity);if(t)return this.enrichedActor(e,t);let n=FO(e.identity),r=this.negativeActorIndex.get(n);if(r&&r>Date.now())return e;this.negativeActorIndex.delete(n);let o=await this.resolver?.(e.identity);if(!o)return this.negativeActorIndex.set(n,Date.now()+HG),e;let i={identity:e.identity,...e.displayName?{label:e.displayName}:{}},s={...o,actors:[i],matchedActor:i};return this.actorIndex.set(n,{resolution:s,expiresAt:Date.now()+HG}),this.links=[...this.links.filter((c)=>c.userId!==s.userId),s],this.enrichedActor(e,s)}enrichedActor(e,t){return{...e,identity:{kind:"user",userId:t.userId,canonicalId:t.canonicalId},...t.displayName?{displayName:t.displayName}:{}}}}var JG="https://rizom.ai/ext/anchor-profile/v1",ZG=a.looseObject({id:a.string(),description:a.string(),name:a.string().optional(),tags:a.array(a.string()).optional().default([])}),VG=Zl.extend({kind:a.string().trim().min(1).optional(),category:$v.optional()}).superRefine((e,t)=>{if(e.kind===void 0!==(e.category===void 0))t.addIssue({code:"custom",message:"Anchor kind and category must be provided together"})}),Nxe=a.looseObject({uri:a.string(),params:a.record(a.string(),a.unknown()).optional()}),KG=a.looseObject({name:a.string(),url:a.string(),description:a.string().optional(),skills:a.array(ZG).optional().default([]),capabilities:a.looseObject({extensions:a.array(Nxe).optional().default([])}).optional()});function jxe(e){let t=KG.safeParse(e);if(!t.success)return null;let n=t.data,o=(n.capabilities?.extensions??[]).find((s)=>s.uri===JG),i=null;if(o?.params){let s=VG.safeParse(o.params);if(s.success)i=s.data}return{brainName:n.name,url:n.url,description:n.description??"",skills:n.skills.map((s)=>({id:s.id,name:s.name??s.id,description:s.description,tags:s.tags})),anchor:i}}import{EventEmitter as YG}from"events";var Wt={REGISTERED:"registered",INITIALIZED:"initialized",ERROR:"error",DISABLED:"disabled"},Fo={REGISTERED:"plugin:registered",BEFORE_INITIALIZE:"plugin:before_initialize",INITIALIZED:"plugin:initialized",ERROR:"plugin:error",DISABLED:"plugin:disabled"};class No extends Error{pluginId;constructor(e,t){super(`Plugin ${e}: ${t}`);this.name="PluginError",this.pluginId=e}}function Wi(e,t){return Reflect.get(e,t,e)}function Hi(e,t,n){if(typeof e!=="function")throw TypeError("Cannot apply a non-callable trapped member");return Reflect.apply(e,t,n)}class jO{scope;ingress=new Set;closePromise=null;closed=!1;constructor(){this.scope=oe.runSync(ln.make())}addFinalizer(e){if(this.closed)throw Error("Cannot register a resource after plugin teardown");oe.runSync(ln.addFinalizer(this.scope,oe.promise(async()=>{await e()})))}addIngress(e){if(this.closed)throw Error("Cannot register ingress after plugin teardown");this.ingress.add(e)}close(e=Ft.void){return this.closed=!0,this.closePromise??=this.closeScope(e),this.closePromise}async closeScope(e){let t,n=!1,r=[...this.ingress].reverse();for(let c of r)try{c.stopAdmission()}catch(l){if(!n)t=l;n=!0}let o=await Promise.allSettled(r.map((c)=>Promise.resolve().then(()=>c.drain())));this.ingress.clear();let i=o.find((c)=>c.status==="rejected");if(!n&&i)t=i.reason,n=!0;let s=await oe.runPromiseExit(ln.close(this.scope,e));if(!n&&Ft.isFailure(s))t=Ro.squash(s.cause),n=!0;if(n)throw t}}function QG(e,t){let n=e.getMessageBus(),r=new Set,o={send:(te)=>n.send(te),hasHandlers:(te)=>n.hasHandlers?.(te)??!1,subscribe:(te,ne,G)=>{let Se=!0,ke=new Set,Ne=(Qt)=>{if(!Se)return{noop:!0};let ai,Er=new Promise((wr)=>{ai=wr});ke.add(Er);let Lr=()=>{ke.delete(Er),ai()},sa;try{sa=Promise.resolve(ne(Qt))}catch(wr){throw Lr(),wr}return sa.then((wr)=>(Lr(),wr),(wr)=>{throw Lr(),wr})},le=n.subscribe(te,Ne,G),wt={type:te,originalHandler:ne,stopAdmission:()=>{if(!Se)return;Se=!1,le(),r.delete(wt)}};r.add(wt);try{t.addIngress({stopAdmission:wt.stopAdmission,drain:async()=>{await Promise.all(ke)}})}catch(Qt){throw wt.stopAdmission(),Qt}return wt.stopAdmission},unsubscribe:(te,ne)=>{let G=[...r].filter((Se)=>Se.type===te&&Se.originalHandler===ne);if(G.length===0){n.unsubscribe(te,ne);return}for(let Se of G)Se.stopAdmission()},collect:(te)=>n.collect(te),validateMessage:(te,ne)=>n.validateMessage(te,ne),getHandlerCount:(te)=>n.getHandlerCount(te),getTargetedHandlerCount:(te,ne)=>n.getTargetedHandlerCount(te,ne),clearHandlers:(te)=>n.clearHandlers(te),clearAllHandlers:()=>n.clearAllHandlers()},i=e.getAttachmentRegistry(),s={...i,register:(te,ne,G)=>{let Se=!0,ke=i.register(te,ne,G),Ne=()=>{if(!Se)return;Se=!1,ke()};return t.addFinalizer(Ne),Ne}},c=e.getEntityRegistry(),l=new Proxy(c,{get(te,ne){let G=Wi(te,ne);if(ne==="registerEntityType"&&typeof G==="function")return(...Se)=>{let ke=Hi(G,te,Se),Ne=Se[0];if(typeof Ne==="string")t.addFinalizer(()=>te.unregisterEntityType(Ne));return ke};return typeof G==="function"?G.bind(te):G}}),u=e.getProfileKindRegistry(),d=new Proxy(u,{get(te,ne){let G=Wi(te,ne);if(ne==="register"&&typeof G==="function")return(...Se)=>{let ke=Hi(G,te,Se),Ne=Se[0];if(typeof Ne==="string")t.addFinalizer(()=>te.unregisterPlugin(Ne));return ke};return typeof G==="function"?G.bind(te):G}}),m=e.getChannelRegistry(),g=new Proxy(m,{get(te,ne){let G=Wi(te,ne);if((ne==="registerDescriptor"||ne==="registerDeliveryProvider")&&typeof G==="function")return(...Se)=>{let ke=Hi(G,te,Se),Ne=Se[0];if(typeof Ne==="string")t.addFinalizer(()=>te.unregisterPlugin(Ne));return ke};return typeof G==="function"?G.bind(te):G}}),y=e.getInboxRegistry(),S=new Proxy(y,{get(te,ne){let G=Wi(te,ne);if(ne==="registerSource"&&typeof G==="function")return(...Se)=>{let ke=Hi(G,te,Se),Ne=Se[0];if(typeof Ne==="string")t.addFinalizer(()=>te.unregisterPlugin(Ne));return ke};return typeof G==="function"?G.bind(te):G}}),T=e.getInboxFollowUpRegistry(),R=new Proxy(T,{get(te,ne){let G=Wi(te,ne);if(ne==="registerKind"&&typeof G==="function")return(...Se)=>{let ke=Hi(G,te,Se),Ne=Se[0];if(typeof Ne==="string")t.addFinalizer(()=>te.unregisterPlugin(Ne));return ke};return typeof G==="function"?G.bind(te):G}}),se=e.getAccountSettingsRegistry(),V=new Proxy(se,{get(te,ne){let G=Wi(te,ne);if(ne==="register"&&typeof G==="function")return(...Se)=>{let ke=Hi(G,te,Se);return t.addFinalizer(()=>{Hi(te.unregister,te,[ke])}),ke};return typeof G==="function"?G.bind(te):G}}),ee=e.getOperationalHealthRegistry(),me=new Proxy(ee,{get(te,ne){let G=Wi(te,ne);if(ne==="register"&&typeof G==="function")return(...Se)=>{let ke=Hi(G,te,Se),Ne=Se[0];if(typeof Ne==="string")t.addFinalizer(()=>te.unregisterPlugin(Ne));return ke};return typeof G==="function"?G.bind(te):G}}),_e=e.getDataSourceRegistry(),ue=new Proxy(_e,{get(te,ne){let G=Wi(te,ne);if(ne==="register"&&typeof G==="function")return(...Se)=>{let ke=Hi(G,te,Se),Ne=Se[0];if(typeof Ne==="object"&&Ne!==null&&"id"in Ne&&typeof Ne.id==="string"){let le=Ne.id.includes(":")?Ne.id:`shell:${Ne.id}`;t.addFinalizer(()=>te.unregister(le))}return ke};return typeof G==="function"?G.bind(te):G}}),De=e.getInsightsRegistry(),Me=new Proxy(De,{get(te,ne){let G=Wi(te,ne);if(ne==="register"&&typeof G==="function")return(...Se)=>{let ke=Hi(G,te,Se),Ne=Se[0];if(typeof Ne==="string")t.addFinalizer(()=>te.unregister(Ne));return ke};return typeof G==="function"?G.bind(te):G}}),tt=new Proxy(e,{get(te,ne){if(ne==="getMessageBus")return()=>o;if(ne==="getAttachmentRegistry")return()=>s;if(ne==="getEntityRegistry")return()=>l;if(ne==="getDataSourceRegistry")return()=>ue;if(ne==="getProfileKindRegistry")return()=>d;if(ne==="getChannelRegistry")return()=>g;if(ne==="getInboxRegistry")return()=>S;if(ne==="getInboxFollowUpRegistry")return()=>R;if(ne==="getOperationalHealthRegistry")return()=>me;if(ne==="getAccountSettingsRegistry")return()=>V;if(ne==="getInsightsRegistry")return()=>Me;let G=Wi(te,ne);return typeof G==="function"?G.bind(te):G}});return QK(e,tt),tt}class zO{plugins;events;daemonRegistry;logger;projectionRegistry;resourceScopes=new Map;releasePromises=new Map;constructor(e,t,n,r,o){this.plugins=e,this.events=t,this.daemonRegistry=n,this.projectionRegistry=r,this.logger=o.child("PluginLifecycle")}async initializePlugin(e,t,n){let r=this.plugins.get(e);if(!r)throw new No(e,"Registration failed: Plugin is not registered");let o=r.plugin,i=new jO;i.addFinalizer(()=>t.unregisterPluginCapabilities?.(e)),i.addFinalizer(()=>t.getJobQueueService().unregisterPluginHandlers(e)),i.addFinalizer(()=>this.projectionRegistry.unregisterPlugin(e)),this.resourceScopes.set(e,i),this.releasePromises.delete(e),this.logger.debug(`Initializing plugin: ${e}`);try{this.events.emit(Fo.BEFORE_INITIALIZE,e,o);let s=await o.register(QG(t,i),n);return r.status=Wt.INITIALIZED,this.logger.debug(`Initialized plugin: ${e}`),this.events.emit(Fo.INITIALIZED,e,o),s}catch(s){throw this.logger.error(`Error initializing plugin ${e}: ${We(s)}`),await this.failPluginInitialization(e,s),s}}async finalizePluginRegistration(e){let t=this.plugins.get(e);if(!t)throw new No(e,"Registration finalization failed: Plugin is not registered");if(t.status!==Wt.INITIALIZED)return;try{await t.plugin.finalizeRegistration?.(),this.logger.debug(`Registration finalized for plugin: ${e}`)}catch(n){throw await this.failPluginInitialization(e,n),n}}async readyPlugin(e){let t=this.plugins.get(e);if(!t)throw new No(e,"Ready failed: Plugin is not registered");if(t.status!==Wt.INITIALIZED){this.logger.debug(`Skipping ready hook for non-initialized plugin: ${e}`);return}try{await t.plugin.ready?.(),this.logger.debug(`Ready hook completed for plugin: ${e}`)}catch(n){let r=Up(n);t.status=Wt.ERROR,t.error=r;try{this.events.emit(Fo.ERROR,e,r)}catch(o){this.logger.error(`Plugin error listener failed for ${e}`,o)}throw r}}async startPluginDaemons(e){let t=this.plugins.get(e);if(t?.status!==Wt.INITIALIZED)return;try{await this.daemonRegistry.startPlugin(e),this.logger.debug(`Started daemons for plugin: ${e}`)}catch(n){if(t.plugin.requiresDaemonStartup?.())throw n;this.logger.warn(`Daemon ${e} failed to start: ${We(n)}`)}}async failPluginInitialization(e,t){let n=this.plugins.get(e);if(!n)return;let r=n.status!==Wt.ERROR,o=Up(t);if(n.status=Wt.ERROR,n.error=o,await this.releasePluginResources(e,Ft.fail(t)),r)try{this.events.emit(Fo.ERROR,e,o)}catch(i){this.logger.error(`Plugin error listener failed for ${e}`,i)}}async disablePlugin(e){let t=this.plugins.get(e);if(!t){this.logger.warn(`Cannot disable plugin ${e}: not registered`);return}if(t.status===Wt.DISABLED)return;this.logger.debug(`Disabling plugin: ${e}`);let n=t.status===Wt.ERROR;await this.releasePluginResources(e,Ft.void);let r=this.plugins.get(e);if(!n&&r&&r.status!==Wt.DISABLED)r.status=Wt.DISABLED,this.events.emit(Fo.DISABLED,e,r.plugin);this.logger.debug(`Disabled plugin: ${e}`)}releasePluginResources(e,t){let n=this.releasePromises.get(e);if(n)return n;let r=this.releasePluginResourcesOnce(e,t);return this.releasePromises.set(e,r),r}async releasePluginResourcesOnce(e,t){let n=this.plugins.get(e);if(!n)return;try{await this.daemonRegistry.stopPlugin(e),this.logger.debug(`Stopped daemons for plugin: ${e}`)}catch(o){this.logger.error(`Failed to stop daemons for plugin: ${e}`,o)}let r=this.resourceScopes.get(e);if(this.resourceScopes.delete(e),r)try{await r.close(t)}catch(o){this.logger.error(`Failed to close resources for plugin ${e}`,o)}if(n.plugin.shutdown)try{await n.plugin.shutdown(),this.logger.debug(`Shutdown completed for plugin: ${e}`)}catch(o){this.logger.error(`Plugin shutdown failed for ${e}:`,o)}for(let o of this.daemonRegistry.getByPlugin(e))try{await this.daemonRegistry.unregister(o.name)}catch(i){this.logger.error(`Failed to unregister daemon ${o.name} for plugin ${e}`,i)}}}class LO{plugins;events;logger;constructor(e,t,n){this.plugins=e,this.events=t,this.logger=n.child("DependencyResolver")}async resolveInitializationOrder(e){this.logger.debug("Resolving plugin initialization order...");let t=Array.from(this.plugins.keys()),n=new Set,r=!0;while(r&&n.size<t.length){r=!1;for(let s of t){if(n.has(s))continue;if(!this.plugins.get(s))continue;if(this.getUnmetDependencies(s).length===0)try{await e(s),n.add(s),r=!0}catch(u){let d=We(u);this.logger.error(`Failed to initialize plugin ${s}: ${d}`),n.add(s),r=!0}}}let o=t.filter((s)=>!n.has(s));if(o.length>0){let s=o.join(", ");this.logger.error(`Failed to initialize plugins due to dependency issues: ${s}`);for(let c of o){let l=this.getUnmetDependencies(c);this.logger.error(`Plugin ${c} has unmet dependencies: ${l.join(", ")}`);let u=this.plugins.get(c);if(u)u.status=Wt.ERROR,u.error=new No(c,`Unmet dependencies: ${l.join(", ")}`);this.events.emit(Fo.ERROR,c,u?.error)}}let i=new Set;for(let[s,c]of this.plugins)if(c.status===Wt.INITIALIZED)i.add(s);return this.logger.debug(`Resolved ${i.size} of ${t.length} plugins`),{initialized:i,failed:o}}getUnmetDependencies(e){let t=this.plugins.get(e);if(!t)return[];let{dependencies:n}=t,r=[];for(let o of n){let i=this.plugins.get(o);if(!i){r.push(o);continue}if(i.status!==Wt.INITIALIZED)r.push(o)}return r}}class BO{logger;projectionRegistry;constructor(e,t){this.logger=e.child("CapabilityRegistrar"),this.projectionRegistry=t}async registerCapabilities(e,t,n,r){if(!r?.executionOnly&&n.tools.length>0)e.registerTools(t,n.tools),this.logger.debug(`Registered ${n.tools.length} tools from ${t}`);if(!r?.executionOnly&&n.resources.length>0)e.registerResources(t,n.resources),this.logger.debug(`Registered ${n.resources.length} resources from ${t}`);if(!r?.executionOnly&&n.instructions)e.registerInstructions(t,n.instructions),this.logger.debug(`Registered instructions from ${t}`);let o=n.projectionRules??[];try{for(let i of o)this.projectionRegistry.registerRule(t,i)}catch(i){throw this.projectionRegistry.unregisterPlugin(t),i}if(o.length>0)this.logger.debug(`Registered ${o.length} projection rules from ${t}`)}}class Uv{projections=new Map;rules=new Map;static createFresh(){return new Uv}constructor(){}registerRule(e,t){if(!Object.isFrozen(t))throw Error(`Projection rule "${t.id}" must be created with defineProjectionRule`);let n=this.projections.get(t.id);if(n)throw Error(`Projection "${t.id}" is already registered by "${n.pluginId}"`);let r={id:t.id,pluginId:e,targetType:t.targetType,sources:t.sources.map((i)=>({kind:i.kind,types:[...i.types],...i.excludeTypes?{excludeTypes:[...i.excludeTypes]}:{}}))};this.projections.set(t.id,r),this.rules.set(t.id,t);let o=!0;return()=>{if(!o)return;if(o=!1,this.rules.get(t.id)===t)this.rules.delete(t.id);if(this.projections.get(t.id)===r)this.projections.delete(t.id)}}unregisterPlugin(e){for(let[t,n]of this.projections)if(n.pluginId===e)this.projections.delete(t),this.rules.delete(t)}list(){return Array.from(this.projections.values()).sort((e,t)=>e.id.localeCompare(t.id)).map(Bxe)}listRules(){return[...this.rules.values()].sort((e,t)=>e.id.localeCompare(t.id))}validate(e){let t=this.list(),n=new Set(e.map(({type:s})=>s));for(let s of t)if(!n.has(s.targetType))throw Error(`Projection "${s.id}" targets unregistered entity type "${s.targetType}"`);let r=e.filter(({projectionSource:s})=>s).map(({type:s})=>s).sort(),o=qxe(t,r),i=Uxe(t,o)[0];if(i){let s=Wxe(i,o);throw Error(`Projection cycle is not supported: ${[...s,s[0]].join(" -> ")}`)}return Lxe({projections:t,edges:o,unknownSourceTypes:zxe(t,n)})}}function zxe(e,t){let n=[];for(let r of e){let o=[...new Set(r.sources.flatMap((i)=>[...i.types,...i.excludeTypes??[]]).filter((i)=>i!=="*"&&!t.has(i)))].sort();if(o.length>0)n.push({projectionId:r.id,types:o})}return n}function Lxe(e){for(let t of e.projections){for(let n of t.sources){if(Object.freeze(n.types),n.excludeTypes)Object.freeze(n.excludeTypes);Object.freeze(n)}Object.freeze(t.sources),Object.freeze(t)}for(let t of e.edges)Object.freeze(t.causes),Object.freeze(t);for(let t of e.unknownSourceTypes)Object.freeze(t.types),Object.freeze(t);return Object.freeze(e.unknownSourceTypes),Object.freeze(e.projections),Object.freeze(e.edges),Object.freeze(e)}function Bxe(e){return{...e,sources:e.sources.map((t)=>({...t,types:[...t.types],...t.excludeTypes?{excludeTypes:[...t.excludeTypes]}:{}}))}}function qxe(e,t){let n=new Map;for(let r of e)for(let o of e){let i=$xe(r,o,t);if(i.length===0)continue;n.set(`${r.id}\x00${o.id}`,new Set(i))}return Array.from(n,([r,o])=>{let[i="",s=""]=r.split("\x00");return{from:i,to:s,causes:[...o].sort()}}).sort((r,o)=>r.from.localeCompare(o.from)||r.to.localeCompare(o.to))}function $xe(e,t,n){let r=[];for(let o of t.sources){let i=new Set(o.excludeTypes??[]);if((o.types.includes("*")?[...o.types.filter((c)=>c!=="*"),...n]:o.types).includes(e.targetType)&&!i.has(e.targetType))r.push(`entity:${e.targetType}`)}return[...new Set(r)]}function Uxe(e,t){let n=e.map(({id:m})=>m).sort(),r=GG(n,t),o=new Map,i=new Map,s=[],c=new Set,l=[],u=0,d=(m)=>{o.set(m,u),i.set(m,u),u++,s.push(m),c.add(m);for(let T of r.get(m)??[])if(!o.has(T))d(T),i.set(m,Math.min(i.get(m)??0,i.get(T)??0));else if(c.has(T))i.set(m,Math.min(i.get(m)??0,o.get(T)??0));if(i.get(m)!==o.get(m))return;let g=[],y;do{if(y=s.pop(),!y)break;c.delete(y),g.push(y)}while(y!==m);let S=r.get(m)?.includes(m)??!1;if(g.length>1||S)l.push(g.sort())};for(let m of n)if(!o.has(m))d(m);return l.sort((m,g)=>(m[0]??"").localeCompare(g[0]??""))}function Wxe(e,t){let n=new Set(e),r=GG(e,t),o=[...e].sort()[0];if(!o)return[];if(r.get(o)?.includes(o))return[o];let i=(s,c)=>{for(let l of r.get(s)??[]){if(!n.has(l))continue;if(l===o)return c;if(c.includes(l))continue;let u=i(l,[...c,l]);if(u)return u}return};return i(o,[o])??[...e].sort()}function GG(e,t){let n=new Map;for(let r of e)n.set(r,[]);for(let r of t){let o=n.get(r.from);if(o&&!o.includes(r.to))o.push(r.to)}for(let r of n.values())r.sort();return n}async function XG(e){let n=(await oe.runPromise(oe.all(e.map((r)=>oe.either(oe.tryPromise({try:r,catch:(o)=>o}))),{concurrency:"unbounded"}))).find(ur.isLeft);if(n)throw n.left}class Wv{plugins=new Map;logger;events=new YG;daemonRegistry;shell=null;initializedPluginIds=[];pluginLifecycle;dependencyResolver;capabilityRegistrar;projectionRegistry=Uv.createFresh();projectionGraph;static createFresh(e,t){return new Wv(e,t)}setShell(e){this.shell=e}constructor(e,t){this.logger=e.child("PluginManager"),this.events=new YG,this.daemonRegistry=t,this.pluginLifecycle=new zO(this.plugins,this.events,this.daemonRegistry,this.projectionRegistry,e),this.dependencyResolver=new LO(this.plugins,this.events,e),this.capabilityRegistrar=new BO(e,this.projectionRegistry)}registerPlugin(e){if(!e.id)throw new No("unknown","Registration failed: Plugin must have an id");if(this.logger.debug(`Registering plugin: ${e.id} (${e.version})`),this.plugins.has(e.id)){let o=this.plugins.get(e.id)?.plugin.version;throw new No(e.id,`Registration failed: Plugin is already registered with version ${o}`)}let t=e.dependencies??[],n={plugin:e,status:Wt.REGISTERED,dependencies:t};this.plugins.set(e.id,n),this.logger.debug(`Registered plugin: ${e.id} (${e.version})`),this.events.emit(Fo.REGISTERED,e.id,e)}async initializePlugins(e){this.logger.debug("Initializing plugins..."),this.initializedPluginIds=[];let t=await this.dependencyResolver.resolveInitializationOrder(async(n)=>{await this.initializePlugin(n,e)});this.logger.debug(`Initialized ${t.initialized.size} of ${this.plugins.size} plugins`)}async initializePlugin(e,t){if(!this.shell)throw new No(e,"Cannot initialize plugin: Shell not set. Call setShell() first.");let n=this.shell;try{let r=await this.pluginLifecycle.initializePlugin(e,n,t);await this.capabilityRegistrar.registerCapabilities(n,e,r,{executionOnly:t?.executionOnly}),this.initializedPluginIds.push(e)}catch(r){throw await this.pluginLifecycle.failPluginInitialization(e,r),r}}async finalizePluginRegistrations(){this.logger.debug("Finalizing plugin registrations...");for(let n of this.initializedPluginIds)await this.pluginLifecycle.finalizePluginRegistration(n);if(!this.shell)throw Error("Cannot validate projections before the shell is set");let e=this.shell.getEntityRegistry(),t=this.projectionRegistry.validate(e.getAllEntityTypes().map((n)=>{let r=e.getEntityTypeConfig(n);return{type:n,projectionSource:r.projectionSource!==!1&&r.projectionSourceRole!=="excluded"}}));this.projectionGraph=t;for(let n of t.unknownSourceTypes)this.logger.warn("Projection declares entity source types no installed plugin registers",{projectionId:n.projectionId,types:n.types});this.logger.debug("Validated projection graph",{projections:t.projections.length,edges:t.edges.length})}getProjectionGraphSnapshot(){if(!this.projectionGraph)throw Error("Projection graph has not been finalized");return this.projectionGraph}getProjectionRulesSnapshot(){if(!this.projectionGraph)throw Error("Projection graph has not been finalized");return Object.freeze(this.projectionRegistry.listRules())}async readyPlugins(){this.logger.debug("Dispatching plugin ready hooks...");try{await XG(this.initializedPluginIds.map((e)=>()=>this.pluginLifecycle.readyPlugin(e)))}catch(e){for(let t of this.initializedPluginIds){let n=this.plugins.get(t);if(n?.status===Wt.ERROR)await this.pluginLifecycle.failPluginInitialization(t,n.error??e)}throw e}}async startPluginDaemons(){this.logger.debug("Starting plugin daemons..."),await XG(this.initializedPluginIds.map((e)=>()=>this.pluginLifecycle.startPluginDaemons(e)))}getPlugin(e){return this.plugins.get(e)?.plugin}getPluginStatus(e){return this.plugins.get(e)?.status}hasPlugin(e){return this.plugins.has(e)}isPluginInitialized(e){return this.plugins.get(e)?.status===Wt.INITIALIZED}getAllPluginIds(){return Array.from(this.plugins.keys())}getAllPlugins(){return new Map(this.plugins)}getFailedPlugins(){return Array.from(this.plugins.entries()).filter((e)=>e[1].status===Wt.ERROR&&e[1].error!==void 0).map(([e,t])=>({id:e,error:t.error}))}getPluginPackageName(e){return this.plugins.get(e)?.plugin.packageName}async disablePlugin(e){await this.pluginLifecycle.disablePlugin(e)}async shutdownPlugins(){let e=new Set;for(let t of[...this.initializedPluginIds].reverse())await this.disablePlugin(t),e.add(t);for(let t of[...this.plugins.keys()].reverse())if(!e.has(t))await this.disablePlugin(t)}on(e,t){this.events.on(e,t)}once(e,t){this.events.once(e,t)}off(e,t){this.events.off(e,t)}getEventEmitter(){return this.events}}var e3={public:0,trusted:1,admin:2},Hxe=[{id:"dashboard",pluginId:"dashboard",label:"Dashboard",visibility:"public",requiresActiveSession:!1},{id:"web-chat",pluginId:"web-chat",label:"Chat",visibility:"trusted",requiresActiveSession:!0},{id:"studio",pluginId:"studio",label:"Studio",visibility:"public",requiresActiveSession:!0}];function Jxe(e,t){let n=e3[t.permissionLevel??"public"],r=[];for(let{id:o,pluginId:i,label:s,visibility:c,requiresActiveSession:l}of Hxe){let u=t.self?.id===o;if(!u&&(n<e3[c]||l&&t.hasActiveSession!==!0))continue;let d=e.filter((y)=>y.pluginId===i&&!(o==="studio"&&y.fullPath==="/chat")).map((y)=>y.fullPath).sort((y,S)=>y.length-S.length),m=o==="web-chat"&&d.length>0?e.find((y)=>y.pluginId==="studio"&&y.fullPath==="/chat")?.fullPath:void 0,g=u?t.self?.href:m??d[0];if(g!==void 0)r.push({id:o,label:s,href:g,isActive:o===t.activeId,...l?{requiresActiveSession:!0}:{}})}return r}export{Xs as ua,rg as va,EP as wa,wP as xa,B2 as ya,q2 as za,$2 as Aa,U2 as Ba,ame as Ca,cme as Da,_S as Ea,ume as Fa,Lp as Ga,Bp as Ha,vme as Ia,Tme as Ja,QP as Ka,Dme as La,jZ as Ma,_me as Na,sd as Oa,Zxe as Pa,Vxe as Qa,Kv as Ra,Kxe as Sa,Qxe as Ta,Gxe as Ua,Yxe as Va,Xxe as Wa,eSe as Xa,tSe as Ya,nSe as Za,qp as _a,JBe as $a,Ui as ab,Wme as bb,St as cb,uje as db,NS as eb,b as fb,E as gb,mS as hb,re as ib,ro as jb,Op as kb,rJ as lb,xr as mb,zt as nb,Wn as ob,cc as pb,Hm as qb,gS as rb,yn as sb,Zm as tb,Ie as ub,U as vb,Et as wb,uc as xb,xt as yb,Dk as zb,oo as Ab,e2 as Bb,kS as Cb,oi as Db,ii as Eb,p2 as Fb,yfe as Gb,bfe as Hb,P as Ib,et as Jb,dP as Kb,fP as Lb,$p as Mb,sA as Nb,ur as Ob,pt as Pb,fn as Qb,Ro as Rb,cl as Sb,Ft as Tb,ln as Ub,Di as Vb,oe as Wb,Ni as Xb,Al as Yb,Dm as Zb,ji as _b,sOe as $b,aA as ac,cA as bc,lA as cc,ug as dc,uA as ec,pA as fc,dA as gc,vt as hc,ar as ic,$l as jc,Ul as kc,eV as lc,tV as mc,pge as nc,zS as oc,Mm as pc,zde as qc,Lde as rc,nk as sc,rk as tc,fg as uc,BS as vc,gA as wc,hge as xc,yA as yc,US as zc,hA as Ac,bA as Bc,Sn as Cc,B as Dc,un as Ec,ht as Fc,io as Gc,Qs as Hc,ot as Ic,Mo as Jc,d2 as Kc,$i as Lc,sk as Mc,zi as Nc,aS as Oc,ic as Pc,ak as Qc,Ao as Rc,wH as Sc,yOe as Tc,bOe as Uc,Js as Vc,or as Wc,rS as Xc,Ol as Yc,TH as Zc,si as _c,bP as $c,xP as ad,D2 as bd,oc as cd,ck as dd,nme as ed,M2 as fd,_2 as gd,SP as hd,F2 as id,TP as jd,N2 as kd,WS as ld,Sge as md,ZS as nd,rv as od,vA as pd,mg as qd,EA as rd,Vye as sd,CA as td,Kye as ud,Qye as vd,Gye as wd,cye as xd,Xp as yd,IQ as zd,AQ as Ad,dO as Bd,Tr as Cd,bv as Dd,DQ as Ed,gO as Fd,zQ as Gd,Ag as Hd,LQ as Id,td as Jd,BQ as Kd,pbe as Ld,qQ as Md,$Q as Nd,Tbe as Od,WQ as Pd,Rbe as Qd,kbe as Rd,Pbe as Sd,Abe as Td,bO as Ud,oa as Vd,jbe as Wd,xO as Xd,jn as Yd,Rge as Zd,kge as _d,Pge as $d,Oge as ae,_V as be,jV as ce,OA as de,GS as ee,KV as fe,z1e as ge,DA as he,L1e as ie,B1e as je,q1e as ke,zA as le,LV as me,FK as ne,Yhe as oe,nye as pe,qV as qe,UV as re,AA as se,HV as te,aye as ue,UWe as ve,sv as we,XA as xe,eO as ye,rQ as ze,ed as Ae,lv as Be,uv as Ce,Ig as De,pv as Ee,pQ as Fe,Rg as Ge,vye as He,Tye as Ie,Eye as Je,wye as Ke,Cye as Le,kg as Me,Pg as Ne,Bbe as Oe,XQ as Pe,iG as Qe,Bye as Re,Wye as Se,hv as Te,vQ as Ue,TQ as Ve,Hye as We,sG as Xe,Jye as Ye,Zye as Ze,aG as _e,nd as $e,pG as af,dG as bf,fG as cf,mG as df,hG as ef,EO as ff,wO as gf,SG as hf,CO as if,Rv as jf,EG as kf,kv as lf,IO as mf,wG as nf,CG as of,RG as pf,kG as qf,Pv as rf,OG as sf,DG as tf,Ov as uf,Mg as vf,_g as wf,MG as xf,_G as yf,FG as zf,DO as Af,Fg as Bf,jG as Cf,zG as Df,LG as Ef,BG as Ff,qG as Gf,Oxe as Hf,jv as If,$G as Jf,zv as Kf,Lv as Lf,Bv as Mf,UG as Nf,Zl as Of,qv as Pf,zg as Qf,WG as Rf,NO as Sf,JG as Tf,jxe as Uf,No as Vf,Wv as Wf,Jxe as Xf};
|
|
134
134
|
|
|
135
|
-
//# debugId=
|
|
136
|
-
//# sourceMappingURL=index-
|
|
135
|
+
//# debugId=F343ED3885E06DBF64756E2164756E21
|
|
136
|
+
//# sourceMappingURL=index-w5e9n75h.js.map
|