@rizom/brain 0.2.0-alpha.750 → 0.2.0-alpha.751
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 +5 -5
- package/dist/chunks/{app-7e5m9g6k.js → app-jm9fxx6s.js} +2 -2
- package/dist/chunks/{index-18gtvkxj.js → index-0fazt43h.js} +2 -2
- package/dist/chunks/{index-68ge01gj.js → index-1t7tc0yr.js} +3 -3
- package/dist/chunks/{index-68ge01gj.js.map → index-1t7tc0yr.js.map} +3 -3
- package/dist/chunks/{index-dv5k8aft.js → index-wkw27cn1.js} +3 -3
- package/dist/chunks/{index-dv5k8aft.js.map → index-wkw27cn1.js.map} +1 -1
- package/dist/chunks/{package-6203jv7y.js → package-j9vzvhv1.js} +3 -3
- package/dist/chunks/{package-6203jv7y.js.map → package-j9vzvhv1.js.map} +1 -1
- package/dist/model.js +4 -4
- package/dist/model.js.map +1 -1
- package/dist/testing.js +1 -1
- package/package.json +1 -1
- /package/dist/chunks/{app-7e5m9g6k.js.map → app-jm9fxx6s.js.map} +0 -0
- /package/dist/chunks/{index-18gtvkxj.js.map → index-0fazt43h.js.map} +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{B as a}from"./index-
|
|
2
|
+
import{B as a}from"./index-0fazt43h.js";import"./index-4mffgwx9.js";import"./index-1t7tc0yr.js";import"./index-wpzfnffx.js";import"./index-q6pcp7gc.js";import"./index-9881eck9.js";import"./index-nwdvz1vw.js";import"./index-6gqg29bj.js";import"./index-7ne5672k.js";import"./index-amf6s7a5.js";import"./index-p39p7p8h.js";export{a as App};
|
|
3
3
|
|
|
4
4
|
//# debugId=B0224EA8233B0C3764756E2164756E21
|
|
5
|
-
//# sourceMappingURL=app-
|
|
5
|
+
//# sourceMappingURL=app-jm9fxx6s.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{L as p}from"./index-4mffgwx9.js";import{Ga as m,La as d,Oa as v,Pa as S}from"./index-
|
|
2
|
+
import{L as p}from"./index-4mffgwx9.js";import{Ga as m,La as d,Oa as v,Pa as S}from"./index-1t7tc0yr.js";import{Tg as h}from"./index-q6pcp7gc.js";import{Ao as a,yo as n}from"./index-nwdvz1vw.js";import{Ts as f,fw as s,gt as l}from"./index-6gqg29bj.js";import{ay as g}from"./index-p39p7p8h.js";async function u(i){let[{default:e},{default:t}]=await Promise.all([import("./index-ppg0xa7k.js"),import("./package-j9vzvhv1.js")]);return h(e,i??{},{name:t.name,version:t.version},{pluginId:"cli"})}class c{shell=null;config;signalScope=null;signalShutdownFiber=null;stopPromise=null;migrationPromise=null;hasCLI=!1;static create(i,e){return new c(v(i),e)}constructor(i,e){if(this.config=i,this.hasCLI=process.argv.slice(2).includes("--cli"),e)this.shell=e}async migrate(){let i=a.getInstance();await new d(i).runAllMigrations({database:this.config.shellConfig?.database?.url??this.config.database,jobQueueDatabase:this.config.shellConfig?.jobQueueDatabase?.url,conversationDatabase:this.config.shellConfig?.conversationDatabase?.url,runtimeStateDatabase:this.config.shellConfig?.runtimeStateDatabase?.url})}createShell(i,e){this.shell=m.createFresh(S(this.config,i),void 0,{...e?.processRole&&{processRole:e.processRole},...e?.peerChannel&&{peerChannel:e.peerChannel}})}wantsCLI(i){return this.hasCLI||i?.cli===!0}async registerCLIInterface(i){if(!this.wantsCLI(i))return;let e=this.getShell().getPluginManager();for(let t of await u(this.config.cliConfig))e.registerPlugin(t)}async initialize(i,e){if(!this.shell){if(!e?.migrationsCompleted){this.migrationPromise=this.migrate();try{await this.migrationPromise}finally{this.migrationPromise=null}}if(this.stopPromise)return;this.createShell(i,e)}if(await this.registerCLIInterface(e),this.stopPromise)return;await this.getShell().initialize(i)}async start(){if(this.stopPromise)return;this.setupSignalHandlers()}stop(){return this.stopPromise??=this.stopApp(),this.stopPromise}async stopApp(){if(await this.closeSignalScope(),this.migrationPromise)await this.migrationPromise.catch(()=>{return});await this.shell?.shutdown()}async run(i){let t={debug:n.DEBUG,info:n.INFO,warn:n.WARN,error:n.ERROR}[this.config.logLevel??"info"]??n.INFO,o=this.wantsCLI(i),r=a.createFresh({level:t,context:this.config.name,useStderr:o});if(o)a.getInstance().setUseStderr(!0);r.info(`\uD83D\uDE80 Starting ${this.config.name} v${this.config.version}...`),this.setupSignalHandlers();try{if(await this.initialize(void 0,i),this.stopPromise)return;await this.start(),i?.onRuntimeReady?.(),r.info(`\u2705 ${this.config.name} v${this.config.version} ready`),process.stdin.resume()}catch(C){r.error(`\u274C Failed to start ${this.config.name}:`,C),process.exit(1)}}static async run(i,e,t){await c.create(i,e).run(t)}setupSignalHandlers(){if(this.signalScope)return;let i=s.runSync(l.make()),e=()=>{this.requestGracefulShutdown("SIGINT")},t=()=>{this.requestGracefulShutdown("SIGTERM")},o=p(["SIGINT"],e),r=p(["SIGTERM"],t);s.runSync(l.addFinalizer(i,s.sync(()=>{r(),o()}))),this.signalScope=i}requestGracefulShutdown(i){if(this.signalShutdownFiber)return;let e=a.getInstance();e.info(`
|
|
3
3
|
Received ${i}, shutting down gracefully...`);let t=s.tryPromise({try:()=>this.stop(),catch:(o)=>o}).pipe(s.match({onFailure:(o)=>{e.error("Error during shutdown:",o),process.exit(1)},onSuccess:()=>{process.exit(0)}}));this.signalShutdownFiber=s.runFork(t)}async closeSignalScope(){let i=this.signalScope;if(this.signalScope=null,i)await s.runPromise(l.close(i,f.void))}getShell(){if(!this.shell)throw Error("Shell not initialized. Call initialize() first.");return this.shell}}
|
|
4
4
|
export{c as B};
|
|
5
5
|
|
|
6
6
|
//# debugId=CF51F25172A3214964756E2164756E21
|
|
7
|
-
//# sourceMappingURL=index-
|
|
7
|
+
//# sourceMappingURL=index-0fazt43h.js.map
|
|
@@ -108,10 +108,10 @@ ${qc(i)}`:a,args:t.buildArgs((d)=>({...l,confirmed:!0,confirmationToken:d}))}}as
|
|
|
108
108
|
`).trim()).filter((n)=>n.length>0).map((n,o)=>({index:o,heading:Xl.test(n)?n.split(`
|
|
109
109
|
`)[0]??"":"",text:n}))}function Rh(e,t){let r=cn(t.heading),i=cn(t.text);return Array.from(e).reduce((n,o)=>n+(i.has(o)?1:0)+(r.has(o)?1:0),0)}function ed(e,t){if(e.length<=t)return e;let r=e.slice(0,t-1);return`${r.slice(0,Math.max(r.lastIndexOf(" "),1)).trimEnd()}\u2026`}function id(e,t,r=td){if(e.length<=r)return e;let i=cn(t),n=Sh(e).map((a)=>({section:a,score:Rh(i,a)})).filter(({score:a})=>a>0).sort((a,l)=>l.score-a.score||a.section.index-l.section.index).map(({section:a})=>a),[o]=n;if(!o)return ed(e.trim(),r);if(o.text.length>r)return ed(o.text,r);let{kept:s}=n.reduce((a,l)=>{let d=l.text.length+(a.kept.length>0?Yl.length:0);return a.used+d<=r?{used:a.used+d,kept:[...a.kept,l]}:a},{used:0,kept:[]});return s.sort((a,l)=>a.index-l.index).map((a,l,d)=>{let u=d[l-1];if(!u)return a.text;return`${a.index===u.index+1?`
|
|
110
110
|
|
|
111
|
-
`:Yl}${a.text}`}).join("")}var wh=0.5;function nd(e,t){let r=e??t.limit;return t.maxLimit===void 0?r:Math.min(r,t.maxLimit)}function od(e,t,r,i){let n=Li(e.entity,r);if(n!==e.entity)return{...e,entity:n,excerpt:n.content};let o=Le(n.content);if(o.length<=i)return{...e,entity:n};let{content:s,...a}=n;return{...e,entity:a,excerpt:id(o,t,i),excerpted:!0}}var wr=(e)=>e==="public"?{publishedOnly:!0}:{};function Ih(e,t){if(e.length===0)return;let r=Math.round(Math.max(...e.map((i)=>i.score))*100)/100;return{minScore:t,weakerMatches:e.length,bestScore:r,hint:`No result reached minScore ${t}, but ${e.length} weaker match${e.length===1?"":"es"} exist (best score ${r}). Broad or abstract questions match content weakly: search again with a lower minScore, such as 0.3, before concluding that nothing relevant exists.`}}function sd(e){let{entityService:t,logger:r}=e;return[de("system","search","Search entities using semantic search. For broad search, make one system_search call with scope.kind all. Use scope.kind type only when the user asks for a specific entity type. When the user names entity types, search each with scope.kind type in the same step, without a broad search first. Applies a default minScore of 0.5 to reduce weak matches; lower minScore only for exploratory or loose recall. An empty result with belowThreshold means weaker matches exist: search again with a lower minScore before concluding that nothing relevant exists. When the question is in a different language from the saved content, also search with the query translated into the content's language before concluding that little exists; the content's language is the language of the search results and of the brain's profile, and matches across languages score lower. Search results include each matched entity's content; a long one's is excerpted to its best-matching sections, which system_get reads whole. When relevant results already contain the complete evidence needed, answer from those results instead of redundantly listing or getting the same entities. When a typed search's results hold that type's entities but not a detail the user asked about, the detail is not saved there: answer from what the results say and name what is missing, rather than searching the same type again with added words or a lower minScore. Search results are candidates; do not present weak or unrelated candidates as exact matches. For each new user question about what they have written, mentioned, discussed, or saved, run a fresh search for that turn instead of answering from prior-turn results or memory, including analysis phrasing such as 'How do I discuss X in my writing?'.",Cc,async(i,n)=>{Rr(n);let o=A(n.userPermissionLevel);if(i.scope.kind==="type"&&e.entityRegistry.getEntityTypeConfig(i.scope.entityType).embeddable===!1){let{entityType:u}=i.scope;return{success:!0,data:{results:(await t.listEntities({entityType:u,options:{limit:nd(i.limit,e.searchBudget),filter:{visibilityScope:o},...wr(o)}})).map((m)=>od({entity:m},i.query,e.entityRegistry,e.searchBudget.excerptChars)),notSearchable:{entityType:u,hint:`${u} is not in the search index, so the results are its entries, unranked.`}}}}let s=i.minScore??wh,a=await t.search({query:i.query,options:{limit:nd(i.limit,e.searchBudget),...i.scope.kind==="type"&&{types:[i.scope.entityType]},...i.includeUngenerated!==void 0&&{includeUngenerated:i.includeUngenerated},visibilityScope:o,...wr(o)}}),l=a.filter((u)=>u.score>=s),d=l.length===0?Ih(a,s):void 0;return{success:!0,data:{results:l.map((u)=>od(u,i.query,e.entityRegistry,e.searchBudget.excerptChars)),...d&&{belowThreshold:d}}}},{visibility:"public",sideEffects:"none",cli:{name:"search"}}),de("system","get","Retrieve a specific entity by type and identifier (ID, slug, or title). When the user asks to read, show or verify an entity, call system_get in that turn instead of answering from earlier results in this conversation: stored content can change outside this conversation. If retrieval fails, report the entity as not found rather than describing related generation work as pending.",Tc,async(i,n)=>{if(Rr(n),!t.getEntityTypes().includes(i.entityType))return{success:!1,error:`Unknown entity type: ${i.entityType}. Available: ${t.getEntityTypes().join(", ")}`};let o=A(n.userPermissionLevel),s=await _(t,{entityType:i.entityType,identifier:i.id},{visibilityScope:o,logger:r,read:{...wr(o),source:!0}});if(!s.ok)return{success:!1,error:s.error};let a=Li(s.entity,e.entityRegistry);return{success:!0,data:{entity:i.part==="body"?{...a,content:Le(a.content)}:a}}},{visibility:"public",sideEffects:"none",cli:{name:"get"}}),de("system","list","List entities by a known entity type. Returns metadata only; it answers a request to show or list items of a type, such as titles, dates and descriptions, so answer from it and use system_get only when the user asks about an item's full content. Use system_search, not system_list, for broad or vague lookup requests. For list/show-all requests that name or browse a known type or synonym (essays/articles/blog posts => post), list that type instead of searching; for a whole-type summary such as 'summarize my blog posts', list it first, then summarize the returned entities. Use system_list to inspect metadata dates such as publishedAt when the user asks for the latest item of a known type, such as latest blog post.",Ec,async(i,n)=>{if(Rr(n),!t.getEntityTypes().includes(i.entityType))return{success:!1,error:`Unknown entity type: ${i.entityType}. Available: ${t.getEntityTypes().join(", ")}`};let o=A(n.userPermissionLevel),s={visibilityScope:o};if(i.status&&i.status!=="any")s.metadata={status:i.status};let{defaultSort:a}=e.entityRegistry.getEntityTypeConfig(i.entityType),d=(await t.listEntities({entityType:i.entityType,options:{limit:i.limit??20,filter:s,...wr(o),...a?{sortFields:a}:{}}})).map(({content:u,contentHash:p,...m})=>m);return{success:!0,data:{entities:d,count:d.length}}},{visibility:"public",sideEffects:"none",cli:{name:"list"}})]}function xh(e){let t=Object.fromEntries(Object.entries(e.params.shape).map(([r,i])=>{let n=i instanceof c.ZodDefault?i.unwrap():i,o=i.description?n.describe(i.description):n;return[r,o.optional()]}));return c.looseObject(t).describe(`Params for ${e.type}`)}function Ph(e){let[t,...r]=e.map((o)=>o.type);if(t===void 0)throw Error("No analytics reports registered");let i=e.filter((o)=>Object.keys(o.params.shape).length>0).map(xh),n=c.union([...i,c.looseObject({})]);return c.object({type:c.enum([t,...r]).describe("The report to run"),params:n.optional().describe("The report's params; each report lists its own")})}function ad(e){let{entityService:t,analytics:r}=e,i=r.getDefinitions(),n=i.map((o)=>`${o.type} (${o.description})`).join("; ");return[de("system","analytics",`Aggregate metrics and reports over the brain, not its content: for actual content use system_list, system_get or system_search. Reports: ${n}.`,Ph(i),async(o,s)=>({success:!0,data:await r.run({type:o.type,params:o.params,entityService:t,permission:s.userPermissionLevel??"public"})}),{visibility:"public",sideEffects:"none"})]}function cd(e){let{jobs:t}=e;return[W("job_status","Inspect runtime job status for ready checks only when the prior operation created a job, or for status disputes. With a known batch ID, pass batchId. Without an ID, call this tool with no arguments to list active jobs and batches; do not ask the user for an ID first. Do not argue from the transcript alone.",zc,async(r,i)=>{let n=e.permissionService.hasPermission(i.userPermissionLevel??"public","trusted");if(r.batchId){let a=await t.getBatchStatus(r.batchId);if(!a)return{success:!1,error:`No batch found with ID: ${r.batchId}`};let l=a.totalOperations>0?Math.round(a.completedOperations/a.totalOperations*100):0;return{success:!0,data:{batchId:r.batchId,status:a.status,progress:{total:a.totalOperations,completed:a.completedOperations,failed:a.failedOperations,percentComplete:l},currentOperation:a.currentOperation,...n&&{errors:a.errors}}}}let o=await t.getActiveJobs(r.jobTypes),s=await t.getActiveBatches();return{success:!0,data:{summary:{activeJobs:o.length,activeBatches:s.length},jobs:o.map((a)=>({id:a.id,type:a.type,status:a.status,priority:a.priority,retryCount:a.retryCount,createdAt:new Date(a.createdAt).toISOString(),startedAt:a.startedAt?new Date(a.startedAt).toISOString():null})),batches:s.map((a)=>({batchId:a.batchId,status:a.status.status,totalOperations:a.status.totalOperations,completedOperations:a.status.completedOperations,failedOperations:a.status.failedOperations,currentOperation:a.status.currentOperation,pluginId:a.metadata.metadata.pluginId,...n&&{errors:a.status.errors}}))}}},{visibility:"public",sideEffects:"none"})]}function Ch(e,t){let{entityCounts:r,daemons:i,endpoints:n,interactions:o,...s}=e,a=n.filter((l)=>t(l.visibility)).sort((l,d)=>l.priority-d.priority).map(({label:l,url:d})=>({label:l,url:d}));if(!t("trusted"))return{...{version:e.version,uptime:e.uptime,backgroundWork:e.backgroundWork},endpoints:a};return{...s,endpoints:a}}function ld(e){return[de("system","status","Get system status including version, background work, and the web surfaces
|
|
111
|
+
`:Yl}${a.text}`}).join("")}var wh=0.5;function nd(e,t){let r=e??t.limit;return t.maxLimit===void 0?r:Math.min(r,t.maxLimit)}function od(e,t,r,i){let n=Li(e.entity,r);if(n!==e.entity)return{...e,entity:n,excerpt:n.content};let o=Le(n.content);if(o.length<=i)return{...e,entity:n};let{content:s,...a}=n;return{...e,entity:a,excerpt:id(o,t,i),excerpted:!0}}var wr=(e)=>e==="public"?{publishedOnly:!0}:{};function Ih(e,t){if(e.length===0)return;let r=Math.round(Math.max(...e.map((i)=>i.score))*100)/100;return{minScore:t,weakerMatches:e.length,bestScore:r,hint:`No result reached minScore ${t}, but ${e.length} weaker match${e.length===1?"":"es"} exist (best score ${r}). Broad or abstract questions match content weakly: search again with a lower minScore, such as 0.3, before concluding that nothing relevant exists.`}}function sd(e){let{entityService:t,logger:r}=e;return[de("system","search","Search entities using semantic search. For broad search, make one system_search call with scope.kind all. Use scope.kind type only when the user asks for a specific entity type. When the user names entity types, search each with scope.kind type in the same step, without a broad search first. Applies a default minScore of 0.5 to reduce weak matches; lower minScore only for exploratory or loose recall. An empty result with belowThreshold means weaker matches exist: search again with a lower minScore before concluding that nothing relevant exists. When the question is in a different language from the saved content, also search with the query translated into the content's language before concluding that little exists; the content's language is the language of the search results and of the brain's profile, and matches across languages score lower. Search results include each matched entity's content; a long one's is excerpted to its best-matching sections, which system_get reads whole. When relevant results already contain the complete evidence needed, answer from those results instead of redundantly listing or getting the same entities. When a typed search's results hold that type's entities but not a detail the user asked about, the detail is not saved there: answer from what the results say and name what is missing, rather than searching the same type again with added words or a lower minScore. Search results are candidates; do not present weak or unrelated candidates as exact matches. For each new user question about what they have written, mentioned, discussed, or saved, run a fresh search for that turn instead of answering from prior-turn results or memory, including analysis phrasing such as 'How do I discuss X in my writing?'.",Cc,async(i,n)=>{Rr(n);let o=A(n.userPermissionLevel);if(i.scope.kind==="type"&&e.entityRegistry.getEntityTypeConfig(i.scope.entityType).embeddable===!1){let{entityType:u}=i.scope;return{success:!0,data:{results:(await t.listEntities({entityType:u,options:{limit:nd(i.limit,e.searchBudget),filter:{visibilityScope:o},...wr(o)}})).map((m)=>od({entity:m},i.query,e.entityRegistry,e.searchBudget.excerptChars)),notSearchable:{entityType:u,hint:`${u} is not in the search index, so the results are its entries, unranked.`}}}}let s=i.minScore??wh,a=await t.search({query:i.query,options:{limit:nd(i.limit,e.searchBudget),...i.scope.kind==="type"&&{types:[i.scope.entityType]},...i.includeUngenerated!==void 0&&{includeUngenerated:i.includeUngenerated},visibilityScope:o,...wr(o)}}),l=a.filter((u)=>u.score>=s),d=l.length===0?Ih(a,s):void 0;return{success:!0,data:{results:l.map((u)=>od(u,i.query,e.entityRegistry,e.searchBudget.excerptChars)),...d&&{belowThreshold:d}}}},{visibility:"public",sideEffects:"none",cli:{name:"search"}}),de("system","get","Retrieve a specific entity by type and identifier (ID, slug, or title). When the user asks to read, show or verify an entity, call system_get in that turn instead of answering from earlier results in this conversation: stored content can change outside this conversation. If retrieval fails, report the entity as not found rather than describing related generation work as pending.",Tc,async(i,n)=>{if(Rr(n),!t.getEntityTypes().includes(i.entityType))return{success:!1,error:`Unknown entity type: ${i.entityType}. Available: ${t.getEntityTypes().join(", ")}`};let o=A(n.userPermissionLevel),s=await _(t,{entityType:i.entityType,identifier:i.id},{visibilityScope:o,logger:r,read:{...wr(o),source:!0}});if(!s.ok)return{success:!1,error:s.error};let a=Li(s.entity,e.entityRegistry);return{success:!0,data:{entity:i.part==="body"?{...a,content:Le(a.content)}:a}}},{visibility:"public",sideEffects:"none",cli:{name:"get"}}),de("system","list","List entities by a known entity type. Returns metadata only; it answers a request to show or list items of a type, such as titles, dates and descriptions, so answer from it and use system_get only when the user asks about an item's full content. Use system_search, not system_list, for broad or vague lookup requests. For list/show-all requests that name or browse a known type or synonym (essays/articles/blog posts => post), list that type instead of searching; for a whole-type summary such as 'summarize my blog posts', list it first, then summarize the returned entities. Use system_list to inspect metadata dates such as publishedAt when the user asks for the latest item of a known type, such as latest blog post.",Ec,async(i,n)=>{if(Rr(n),!t.getEntityTypes().includes(i.entityType))return{success:!1,error:`Unknown entity type: ${i.entityType}. Available: ${t.getEntityTypes().join(", ")}`};let o=A(n.userPermissionLevel),s={visibilityScope:o};if(i.status&&i.status!=="any")s.metadata={status:i.status};let{defaultSort:a}=e.entityRegistry.getEntityTypeConfig(i.entityType),d=(await t.listEntities({entityType:i.entityType,options:{limit:i.limit??20,filter:s,...wr(o),...a?{sortFields:a}:{}}})).map(({content:u,contentHash:p,...m})=>m);return{success:!0,data:{entities:d,count:d.length}}},{visibility:"public",sideEffects:"none",cli:{name:"list"}})]}function xh(e){let t=Object.fromEntries(Object.entries(e.params.shape).map(([r,i])=>{let n=i instanceof c.ZodDefault?i.unwrap():i,o=i.description?n.describe(i.description):n;return[r,o.optional()]}));return c.looseObject(t).describe(`Params for ${e.type}`)}function Ph(e){let[t,...r]=e.map((o)=>o.type);if(t===void 0)throw Error("No analytics reports registered");let i=e.filter((o)=>Object.keys(o.params.shape).length>0).map(xh),n=c.union([...i,c.looseObject({})]);return c.object({type:c.enum([t,...r]).describe("The report to run"),params:n.optional().describe("The report's params; each report lists its own")})}function ad(e){let{entityService:t,analytics:r}=e,i=r.getDefinitions(),n=i.map((o)=>`${o.type} (${o.description})`).join("; ");return[de("system","analytics",`Aggregate metrics and reports over the brain, not its content: for actual content use system_list, system_get or system_search. Reports: ${n}.`,Ph(i),async(o,s)=>({success:!0,data:await r.run({type:o.type,params:o.params,entityService:t,permission:s.userPermissionLevel??"public"})}),{visibility:"public",sideEffects:"none"})]}function cd(e){let{jobs:t}=e;return[W("job_status","Inspect runtime job status for ready checks only when the prior operation created a job, or for status disputes. With a known batch ID, pass batchId. Without an ID, call this tool with no arguments to list active jobs and batches; do not ask the user for an ID first. Do not argue from the transcript alone.",zc,async(r,i)=>{let n=e.permissionService.hasPermission(i.userPermissionLevel??"public","trusted");if(r.batchId){let a=await t.getBatchStatus(r.batchId);if(!a)return{success:!1,error:`No batch found with ID: ${r.batchId}`};let l=a.totalOperations>0?Math.round(a.completedOperations/a.totalOperations*100):0;return{success:!0,data:{batchId:r.batchId,status:a.status,progress:{total:a.totalOperations,completed:a.completedOperations,failed:a.failedOperations,percentComplete:l},currentOperation:a.currentOperation,...n&&{errors:a.errors}}}}let o=await t.getActiveJobs(r.jobTypes),s=await t.getActiveBatches();return{success:!0,data:{summary:{activeJobs:o.length,activeBatches:s.length},jobs:o.map((a)=>({id:a.id,type:a.type,status:a.status,priority:a.priority,retryCount:a.retryCount,createdAt:new Date(a.createdAt).toISOString(),startedAt:a.startedAt?new Date(a.startedAt).toISOString():null})),batches:s.map((a)=>({batchId:a.batchId,status:a.status.status,totalOperations:a.status.totalOperations,completedOperations:a.status.completedOperations,failedOperations:a.status.failedOperations,currentOperation:a.status.currentOperation,pluginId:a.metadata.metadata.pluginId,...n&&{errors:a.status.errors}}))}}},{visibility:"public",sideEffects:"none"})]}function Ch(e,t){let{entityCounts:r,daemons:i,endpoints:n,interactions:o,...s}=e,a=n.filter((l)=>t(l.visibility)).sort((l,d)=>l.priority-d.priority).map(({label:l,url:d})=>({label:l,url:d}));if(!t("trusted"))return{...{version:e.version,uptime:e.uptime,backgroundWork:e.backgroundWork},endpoints:a};return{...s,endpoints:a}}function ld(e){return[de("system","status","Get system status including version, background work, and the web surfaces the caller can open, with their paths; trusted callers also get the model and entity totals. Report only the paths it lists; when a surface the user asks about is not listed, say its path was not reported.",c.object({}),async(t,r)=>({success:!0,data:Ch(await e.getAppInfo(),(i)=>e.permissionService.hasPermission(r.userPermissionLevel??"public",i))}),{visibility:"public",sideEffects:"none",cli:{name:"status"}})]}function dd(e){return[...sd(e),...cd(e),...ld(e),...Kl(e),...ad(e)]}function ud(e){return[{uri:"entity://types",name:"Entity Types",description:"List of registered entity types",mimeType:"text/plain",handler:async()=>({contents:[{uri:"entity://types",mimeType:"text/plain",text:e.entityService.getEntityTypes().join(`
|
|
112
112
|
`)}]})},{uri:"brain://identity",name:"Brain Identity",description:"Brain character \u2014 name, role, purpose, values",mimeType:"application/json",handler:async()=>({contents:[{uri:"brain://identity",mimeType:"application/json",text:JSON.stringify(e.getIdentity(),null,2)}]})},{uri:"brain://profile",name:"Anchor Profile",description:"Brain owner profile \u2014 name, bio, expertise",mimeType:"application/json",handler:async()=>({contents:[{uri:"brain://profile",mimeType:"application/json",text:JSON.stringify(e.getProfile(),null,2)}]})},{uri:"brain://status",name:"Brain Status",description:"System status \u2014 version, model, interfaces, tools",mimeType:"application/json",handler:async()=>({contents:[{uri:"brain://status",mimeType:"application/json",text:JSON.stringify(await e.getAppInfo(),null,2)}]})}]}function md(e){let{entityService:t}=e;return[{name:"entity-list",uriTemplate:"entity://{type}",description:"List entities of a given type",mimeType:"application/json",list:async()=>t.getEntityTypes().map((i)=>({uri:`entity://${i}`,name:`${i} entities`})),complete:{type:async()=>t.getEntityTypes()},handler:async({type:r})=>{let i=t.getEntityTypes();if(!i.includes(r))throw Error(`Unknown entity type: ${r}. Available: ${i.join(", ")}`);let o=(await t.listEntities({entityType:r})).map((s)=>({id:s.id,entityType:s.entityType,...s.metadata,updated:s.updated}));return{contents:[{uri:`entity://${r}`,mimeType:"application/json",text:JSON.stringify(o,null,2)}]}}},{name:"entity-detail",uriTemplate:"entity://{type}/{id}",description:"Read a single entity by type and ID",mimeType:"text/markdown",complete:{type:async(r)=>{let i=t.getEntityTypes();return r?i.filter((n)=>n.startsWith(r)):i},id:async()=>[]},handler:async({type:r,id:i})=>{let n=await t.getEntity({entityType:r,id:i});if(!n)throw Error(`Entity not found: ${r}/${i}`);let o=e.entityRegistry.getEntityTypeConfig(r).binaryStorage==="asset"?await pd(t,n.content,n.metadata):n.content;return{contents:[{uri:`entity://${r}/${i}`,mimeType:"text/markdown",text:o}]}}}]}function fd(e){return[{name:"create",description:"Create new content of any type",args:{type:{description:"Entity type (e.g. post, deck, note)",required:!0},topic:{description:"Topic or title for the content"}},handler:async({topic:r,type:i})=>({messages:[{role:"user",content:{type:"text",text:r?`Create a new ${i} about: ${r}`:`Create a new ${i}. Ask me what it should be about.`}}]})},{name:"generate",description:"AI-generate content with a prompt",args:{type:{description:`Entity type (${(()=>e.entityService.getEntityTypes().join(", "))()})`,required:!0},topic:{description:"What to generate",required:!0}},handler:async({type:r,topic:i})=>({messages:[{role:"user",content:{type:"text",text:`Generate a ${r} about: ${i}`}}]})},{name:"review",description:"Review and improve existing content",args:{type:{description:"Entity type",required:!0},id:{description:"Entity ID or slug",required:!0}},handler:async({type:r,id:i})=>({messages:[{role:"user",content:{type:"text",text:`Review my ${r} "${i}". Read it first, then give me specific feedback on structure, clarity, and impact. Suggest concrete improvements.`}}]})},{name:"publish",description:"Publish content \u2014 preview, confirm, and publish",args:{type:{description:"Entity type",required:!0},id:{description:"Entity ID or slug",required:!0}},handler:async({type:r,id:i})=>({messages:[{role:"user",content:{type:"text",text:`I want to publish my ${r} "${i}". Show me a preview first, then publish it.`}}]})},{name:"brainstorm",description:"Brainstorm ideas using brain context and expertise",args:{topic:{description:"Topic to brainstorm about",required:!0}},handler:async({topic:r})=>({messages:[{role:"user",content:{type:"text",text:`Let's brainstorm about: ${r}. Use my existing content and expertise as context. Give me fresh angles and concrete ideas.`}}]})}]}function Th(e,t){let r=De(e.permissionService),i=e.entityRegistry.getEntityTypeConfig(t);return["create","update","delete"].every((n)=>r(t,n))&&i.embeddable===!1&&i.fullTextSearchable===!1}function gd(e){return["## Entity CRUD","","Use the system tools for ALL entity operations; each tool's description is its contract.","","Treat explicit verbs such as save, create, capture, remember, import, add/connect an agent, approve/archive an agent, update, delete, generate, publish, or sync as mutation requests. Entity-specific instructions may require proactively recording the user's request itself for demand or workflow tracking; follow those instructions even when the user did not use a separate save/create verb. Ordinary status questions like 'what is the status', 'is it ready', 'did that finish', or 'what happened' are not capture requests; answer them by using the relevant status/read tool for the prior operation. Never call system_create for a status follow-up.","","Do not ask for prose confirmation instead of calling the applicable mutating tool; for create, update, delete, generate, publish, sync, and similar state-changing requests, the initial tool call without `confirmed` is how you create the pending confirmation. Never pass `confirmed: true` on the initial user request. Deletion is Admin-only: if system_delete is not available in the current tool surface, say deletion requires Admin access without calling any tool to find or read the target; do not imply a confirmation flow is available. Never claim a durable create/update/delete change was saved, created, done, or completed unless the relevant tool call succeeded or returned a pending confirmation. If a create/update/delete tool is unavailable, unauthorized, or intentionally not called, say you can't make that durable change from the current context; never say saved/created/done. For an explicit write request from an unauthorized/currently unwritable context, refuse directly; do not call system_status or system_search to check permission or look up related content. Entity type descriptions may mark projection-owned or system-maintained types read-only; refuse mutation requests for those types directly without calling read or write tools, searching for a target, or asking which record to mutate.","","Entity types \u2014 select `entityType` by what the type is for:",...e.entityService.getEntityTypes().filter((i)=>!Th(e,i)).map((i)=>`- ${i}: ${e.entityRegistry.getAdapter(i).purpose}`)].join(`
|
|
113
113
|
`)}var Eh=c.union([c.object({needsConfirmation:c.literal(!0),summary:c.string(),completionSummary:c.string().optional(),preview:c.string(),args:c.record(c.string(),c.unknown())}),c.object({success:c.literal(!0),data:c.object({entityId:c.string(),jobId:c.string().optional()})}),c.object({success:c.literal(!1),error:c.string(),code:c.string().optional()})]);function vd(e){let[t="",...r]=e.source.entityIds;return{kind:"prompt-from-source",entityType:e.entityType,source:{entityType:e.source.entityType,entityId:t},...r.length>0&&{additionalSourceIds:r},...e.prompt!==void 0&&{prompt:e.prompt}}}var Ah=c.object({operation:c.looseObject({kind:c.literal("prompt-from-source"),entityType:c.string(),source:c.looseObject({entityType:c.string(),entityId:c.string()}),additionalSourceIds:c.array(c.string()).optional(),prompt:c.string().optional()})});function kh(e,t){let r=Ah.safeParse(e);if(!r.success)return!1;let{operation:i}=r.data,n=vd(t),o=[n.source.entityId,...n.additionalSourceIds??[]],s=[i.source.entityId,...i.additionalSourceIds??[]];return i.entityType===n.entityType&&i.source.entityType===n.source.entityType&&i.prompt===n.prompt&&s.length===o.length&&s.every((a,l)=>a===o[l])}function bd(e,t,r){return yd(t,hd,async(i)=>{let n=e.find(({name:a})=>a==="system_generate");if(!n)return{status:"refused",error:"Generation is unavailable."};if(i.approval&&!kh(i.approval,i))return{status:"refused",error:"The approval is not for this generation."};let o={interfaceType:i.interfaceType,actor:i.actor,userPermissionLevel:i.userPermissionLevel},s=Eh.parse(await n.handler(i.approval??{operation:vd(i)},o));if("needsConfirmation"in s)return{status:"confirm",summary:s.summary,...s.completionSummary!==void 0&&{completionSummary:s.completionSummary},preview:s.preview,approval:s.args};if(s.success)return{status:"queued",entityId:s.data.entityId,...s.data.jobId!==void 0&&{jobId:s.data.jobId}};return{status:"refused",error:s.error,...s.code!==void 0&&{code:s.code}}},{owner:"system",logger:r})}var Fe="system",jh=c.object({toolName:c.string(),args:c.unknown(),...Sd.partial().shape});function Ir(e,t,r,i,n){for(let o of e)try{t(o)}catch{n.debug(`System ${i} ${r(o)} already registered, skipping`)}}function Rd(e,t,r,i){let n=dd(e);Ir(n,(p)=>t.registerTool(Fe,p),(p)=>p.name,"tool",i);let o=r.subscribe(Yt.toolExecute(Fe),async(p)=>{let m=jh.safeParse(p.payload);if(!m.success)return{success:!1,error:"Invalid system tool execute payload"};let{toolName:f,args:g,interfaceType:h,actor:v,conversationId:y,channelId:S,userPermissionLevel:b}=m.data,R=n.find((z)=>z.name===f);if(!R)return{success:!1,error:`System tool not found: ${f}`};let I={interfaceType:h??"system",actor:v??{kind:"service",serviceId:"system"}};if(y)I.conversationId=y;if(S)I.channelId=S;if(b)I.userPermissionLevel=b;return{success:!0,data:await R.handler(g,I)}});i.debug(`Registered ${n.length} system tools`);let s=ud(e);Ir(s,(p)=>t.registerResource(Fe,p),(p)=>p.uri,"resource",i),i.debug(`Registered ${s.length} system resources`);let a=md(e);Ir(a,(p)=>t.registerResourceTemplate(Fe,p),(p)=>p.uriTemplate,"resource template",i),i.debug(`Registered ${a.length} system resource templates`);let l=fd(e);Ir(l,(p)=>t.registerPrompt(Fe,p),(p)=>p.name,"prompt",i),i.debug(`Registered ${l.length} system prompts`);let d=gd(e);try{t.registerInstructions(Fe,d)}catch{i.debug("System instructions already registered, skipping")}i.debug("Registered system instructions");let u=bd(n,r,i);return()=>{o(),u()}}function Cd(e){let{services:t,jobs:r,analytics:i,query:n,getAppInfo:o}=e,s=t.jobQueueService,a=t.logger.child("system"),l=Rd({entityService:t.entityService,entityRegistry:t.entityRegistry,jobs:{...r,enqueue:wd(s,"system",!1),enqueueBatch:xd(r,"system"),registerHandler:Pd(s,"system"),has:Id(s)},conversationService:t.conversationService,runtimeUploads:t.runtimeUploadRegistry,attachments:xr(t.attachmentRegistry),logger:a,query:n,getIdentity:()=>t.identityService.getCharacter(),getProfile:()=>t.profileService.getProfile(),getAppInfo:o,searchBudget:rd(t.aiService.getConfig().model),analytics:i,permissionService:t.permissionService},t.mcpService,t.messageBus,a);t.disposables.push(l)}class ln{scope;closePromise=null;closed=!1;constructor(){this.scope=w.runSync(D.make())}buildLayer(e){this.assertOpen();let t=w.runSyncExit(Q.buildWithScope(e,this.scope));if(j.isFailure(t))throw oe.squash(t.cause);return t.value}addFinalizer(e){this.assertOpen(),w.runSync(D.addFinalizer(this.scope,w.promise(async()=>{await e()})))}addSyncFinalizer(e){this.assertOpen(),w.runSync(D.addFinalizer(this.scope,w.sync(()=>{e()})))}async fork(e){if(this.closed)throw Error("Cannot start background work after shell shutdown");await w.runPromise(w.forkIn(e,this.scope))}close(e=j.void){if(this.closePromise)return this.closePromise;if(this.closed)return Promise.resolve();return this.closed=!0,this.closePromise=w.runPromise(D.close(this.scope,e)),this.closePromise}closeSync(e){if(this.closed)return;this.closed=!0,w.runSync(D.close(this.scope,e))}assertOpen(){if(this.closed)throw Error("Cannot register cleanup after shell shutdown")}}class dn{config;services;lifecycle;bootloader;initialized=!1;lifecycleState="constructed";bootMode;bootPromise=null;shutdownPromise=null;analyticsRegistry;bootTime=Date.now();endpointRegistry=new Ai;interactionRegistry=new ki;httpRouteRegistry=tr.createFresh();httpServed;jobs;static createFresh(e,t,r){return new dn(gt(e),t,r)}constructor(e,t,r){this.config=e,this.httpServed=e.http.enabled&&Ce(r?.processRole).serves,this.lifecycle=new ln,zd(this,()=>this.httpRouteRegistry.getSnapshot());let i=t?.logger??Pe.getInstance(),n=Ut.createFresh(i,this.config,r?.processRole,r?.peerChannel);try{if(this.services=n.initializeServices(this.lifecycle,t),this.jobs=vc(this.services.batchJobManager,this.services.jobQueueService),this.analyticsRegistry=mc(this.services.entityRegistry),this.bootloader=new Ti(this.config,this.services,this.lifecycle,n,r?.processRole,{registerCoreDataSources:()=>Dn(this.services,this.config),finalizeHttpRoutes:()=>{this.httpRouteRegistry.finalize(Sc(this.services.pluginManager))},registerSystemCapabilities:()=>Cd({services:this.services,jobs:this.jobs,analytics:this.analyticsRegistry,query:(o,s)=>this.query(o,s),getAppInfo:()=>this.getAppInfo()}),createProjectionInputContext:()=>this.createProjectionInputContext(),createProjectionExecutionContext:()=>this.createProjectionExecutionContext(),...t?.projectionRuntime&&{projectionRuntime:t.projectionRuntime}}),n.wireShell(this.services,this),this.httpServed)this.registerHttpHost();Ic(this.lifecycle,this.services)}catch(o){try{this.lifecycle.closeSync(j.fail(o))}catch(s){i.error("Failed to roll back Shell service construction",s)}throw o}}createProjectionInputContext(){return{entities:this.services.entityService,resolvePrompt:(e,t)=>ht(this.services.entityService,e,t),appInfo:()=>this.getAppInfo(),identityInput:()=>{let e=this.getIdentity(),t=this.getProfile();return Ed.parse({brainName:e.name,role:e.role,purpose:e.purpose,values:e.values,profileName:t.name,...t.description!==void 0?{profileDescription:t.description}:{},...t.organization!==void 0?{profileOrganization:t.organization}:{}})}}}createProjectionExecutionContext(){return{ai:kd(this),logger:this.services.logger.child("ProjectionRuntime")}}async runProjectionRule(e,t={},r=new AbortController().signal){let i=this.services.pluginManager.getProjectionRulesSnapshot().find(({id:s})=>s===e);if(!i)throw Error(`Unknown projection rule "${e}"`);let n=await i.selectInput({waveId:"eval",inputs:t.inputs??[]},this.createProjectionInputContext(),r),o=await i.derive(n,this.createProjectionExecutionContext(),r);return Array.isArray(o)?o:[]}getAnalyticsRegistry(){return this.analyticsRegistry}async initialize(e){this.services.logger.debug("Shell.initialize() called");let t=e?.mode;if(this.lifecycleState==="running")return this.services.logger.warn("Shell already initialized"),Promise.resolve();if(this.lifecycleState==="booting"){if(this.bootMode!==t)return Promise.reject(Error(`Shell is already initializing in ${this.bootMode??"normal"} mode; cannot join ${t??"normal"} mode`));return this.bootPromise??Promise.resolve()}if(this.lifecycleState==="closing"||this.lifecycleState==="closed")return Promise.reject(Error("Cannot initialize a closing shell"));if(this.lifecycleState==="failed")return Promise.reject(Error("Cannot initialize a shell after boot failure"));return this.lifecycleState="booting",this.bootMode=t,this.bootPromise=this.boot(e),this.bootPromise}async boot(e){try{if(await this.bootloader.boot(e),this.lifecycleState==="booting"){if(this.lifecycleState="running",this.initialized=!0,e?.mode===void 0)await Ee(this.services.messageBus,jd,{timestamp:new Date().toISOString()},"shell"),this.services.logger.debug("Emitted shell ready event")}}catch(t){if(this.initialized=!1,this.services.logger.error("Failed to initialize Shell",t),this.lifecycleState!=="closing")this.lifecycleState="failed";try{await this.lifecycle.close(j.fail(t))}catch(r){this.services.logger.error("Failed to clean up Shell after initialization failure",r)}throw t}}registerTemplates(e,t){this.services.logger.debug("Registering templates",{pluginId:t,count:Object.keys(e).length});for(let[r,i]of Object.entries(e))this.registerTemplate(r,i,t)}shutdown(){return this.shutdownPromise??=this.shutdownShell(),this.shutdownPromise}async shutdownShell(){if(this.services.logger.debug("Shutting down Shell"),this.lifecycleState==="closed")return;let e=this.bootPromise;if(this.lifecycleState="closing",this.initialized=!1,e)try{await e}catch{}await this.lifecycle.close(),this.lifecycleState="closed",this.services.logger.debug("Shell shutdown complete")}async generateContent(e,t){return this.requireInitialized("Shell content generation"),On(this.services,e,t)}async query(e,t){this.requireInitialized("Shell query");let r=await this.getAppInfo(),i={...t,appInfo:r,timestamp:new Date().toISOString()},{conversationHistory:n,...o}=i;return Td.parse(await this.generateContent({prompt:e,templateName:qe.KNOWLEDGE_QUERY,...n&&{conversationHistory:n},data:o,interfacePermissionGrant:"public"}))}registerPlugin(e){this.requireInitialized("Plugin registration"),this.services.pluginManager.registerPlugin(e)}isInitialized(){return this.initialized}requireInitialized(e){if(!this.initialized)throw Error(`${e} attempted before initialization`)}getEntityService(){return this.services.entityService}getConversationService(){return this.services.conversationService}getEntityRegistry(){return this.services.entityRegistry}async generateObject(e,t,r){this.requireInitialized("Shell generateObject");let{object:i}=await this.services.aiService.generateObject("You are a helpful assistant. Respond with the requested structured data.",e,t,r);return{object:i}}async judge(e){return this.requireInitialized("Shell judge"),this.services.aiService.judge(e)}getAIService(){return this.services.aiService}generateImage(e,t){return this.services.aiService.generateImage(e,t)}canGenerateImages(){return this.services.aiService.canGenerateImages()}canDescribeImages(){return this.services.aiService.canDescribeImages?.()??!1}async describeImage(e,t){return this.services.aiService.describeImage?.(e,t)}getPluginManager(){return this.services.pluginManager}getContentService(){return this.services.contentService}getCallerAuthorizer(){return this.services.callerAuthorizer}getRenderService(){return this.services.renderService}getAttachmentRegistry(){return xr(this.services.attachmentRegistry)}getRuntimeUploadRegistry(){return Dd(this.services.runtimeUploadRegistry)}getRuntimeState(){return this.services.runtimeStateService}getRecurringChecks(e){return this.services.recurringCheckService.namespace(e)}isJobQueueWorkerRunning(){return this.services.jobQueueWorker.isWorkerRunning()}getMessageBus(){return this.services.messageBus}getLogger(){return this.services.logger}getJobQueueService(){return this.services.jobQueueService}getMCPService(){return this.services.mcpService}listToolsForPermissionLevel(e){return this.services.mcpService.listToolsForPermissionLevel(e).map(({pluginId:t,tool:r})=>({name:r.name,description:r.description,pluginId:t}))}getPermissionService(){return this.services.permissionService}getAgentService(){return this.services.agentService}registerTools(e,t){for(let r of t)this.services.mcpService.registerTool(e,r)}registerResources(e,t){for(let r of t)this.services.mcpService.registerResource(e,r)}registerResourceTemplate(e,t){this.services.mcpService.registerResourceTemplate(e,t)}registerPrompt(e,t){this.services.mcpService.registerPrompt(e,t)}registerInstructions(e,t){if(this.services.mcpService.registerInstructions(e,t),this.initialized)this.services.agentService.invalidateAgent()}async unregisterPluginCapabilities(e){this.services.mcpService.unregisterPlugin?.(e),this.services.jobQueueService.unregisterPluginHandlers(e),this.endpointRegistry.unregister(e),this.interactionRegistry.unregister(e);for(let r of this.services.templateRegistry.getNames())if(r.startsWith(`${e}:`))this.services.templateRegistry.unregister(r);let t=this.config.evalHandlerRegistry;if(t){for(let r of t.list())if(r.pluginId===e)t.unregister(e,r.handlerId)}this.services.agentService.invalidateAgent(),await this.services.recurringCheckService.unregisterPlugin(e)}getPluginPackageName(e){return this.services.pluginManager.getPluginPackageName(e)}hasPlugin(e){return this.services.pluginManager.hasPlugin(e)}getPluginHttpRouteManifest(){return this.httpRouteRegistry.getManifest()}getPluginApiRoutes(){return this.httpRouteRegistry.getApiRoutes()}getPluginWebRoutes(){return this.httpRouteRegistry.getWebRoutes()}registerDaemon(e,t,r){this.services.daemonRegistry.register(e,t,r)}registerEndpoint(e){this.endpointRegistry.register(e)}listEndpoints(){return this.endpointRegistry.list()}registerInteraction(e){this.interactionRegistry.register(e)}listInteractions(){return this.interactionRegistry.list()}registerTemplate(e,t,r){let i=r?`${r}:${e}`:`shell:${e}`;this.services.templateRegistry.register(i,t),this.services.logger.debug(`Registered template: ${i}`)}getTemplate(e){return this.services.templateRegistry.get(e)}getDataSourceRegistry(){return this.services.dataSourceRegistry}getIdentity(){return this.services.identityService.getCharacter()}getProfile(){return this.services.profileService.getProfile()}getProfileKindRegistry(){return this.services.profileKindRegistry}getChannelRegistry(){return this.services.channelRegistry}getInboxRegistry(){return this.services.inboxRegistry}getInboxFollowUpRegistry(){return this.services.inboxFollowUpRegistry}getOperationalHealthRegistry(){return this.services.operationalHealthRegistry}getAccountSettingsRegistry(){return this.services.accountSettingsRegistry}getAuthRegistry(){return this.services.authRegistry}getAtprotoProjectionRegistry(){return this.services.atprotoProjectionRegistry}getDomain(){return this.config.siteBaseUrl}getLocalSiteUrl(){return this.config.localSiteUrl}shouldPreferLocalUrls(){return this.config.preferLocalUrls}isProduction(){return this.config.production}servesHttp(){return this.httpServed}registerHttpHost(){let{daemonRegistry:e,logger:t,messageBus:r,pluginManager:i}=this.services;e.register(K,ec({config:this.config.http,domain:this.config.siteBaseUrl,logger:t.child(H),messageBus:r,getRoutes:()=>this.httpRouteRegistry.getSnapshot(),getPlugins:()=>[...i.getAllPlugins().values()].map(({plugin:s})=>s),getOperationalInfo:async()=>Od(Ad(await this.getAppInfo())),getReadinessData:()=>this.getRuntimeReadiness()}),H),this.lifecycle.addSyncFinalizer(()=>e.abandon(K));let{endpoints:n,interactions:o}=tc(this.config.http,this.config.siteBaseUrl);for(let s of n)this.endpointRegistry.register(s);for(let s of o)this.interactionRegistry.register(s)}getThemeCSS(){return this.config.themeCSS}getSpaces(){return this.config.spaces}getDataDir(){return this.config.dataDir}getGitBrokerSocket(){return this.config.gitBrokerSocket}getGitBrokerCheckout(){return this.config.gitBrokerCheckout}registerEvalHandler(e,t,r){this.config.evalHandlerRegistry?.register(e,t,r)}async getAppInfo(){return Rn({config:this.config,services:this.services,bootTime:this.bootTime,endpoints:()=>this.listEndpoints(),interactions:()=>this.listInteractions()})}getRuntimeReadiness(){return xn(this.services)}}async function Wd(e,t){await ue({label:"entity",config:e,schema:{assets:Ld,entities:Md,entityMutationReceipts:Ud,projectionDirtyInputs:Bd,projectionWaves:$d,projectionIncidents:_d,projectionWaveInputs:Fd,projectionWaveRules:Nd,projectionRuleMemos:Zd},migrationsFolder:pe(import.meta.url,"entity-service"),authTokenEnv:"DATABASE_AUTH_TOKEN",logger:t,afterMigrate:Hd})}async function Gd(e,t){await ue({label:"job-queue",config:e,schema:{jobQueue:qd,jobWorkerSessions:Jd},migrationsFolder:pe(import.meta.url,"job-queue"),authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",logger:t})}async function Yd(e,t){await ue({label:"conversation",config:e,schema:{conversations:Qd,messages:Kd,summaryTracking:Vd},migrationsFolder:pe(import.meta.url,"conversation-service"),authTokenEnv:"CONVERSATION_DATABASE_AUTH_TOKEN",logger:t})}async function Xd(e,t){await ue({label:"runtime-state",config:e,schema:{runtimeStateRecords:x},migrationsFolder:pe(import.meta.url,"runtime-state"),authTokenEnv:"RUNTIME_STATE_DATABASE_AUTH_TOKEN",logger:t})}import{mkdir as pn}from"fs/promises";import{isAbsolute as Dh}from"path";function eu(e=process.env){return{dataDir:e.XDG_DATA_HOME??"./data",cacheDir:e.XDG_CACHE_HOME??"./cache",distDir:"./dist"}}function tu(e=process.env){let t=e.BRAIN_GIT_BROKER_CHECKOUT;if(!t)return;if(!Dh(t))throw Error(`Git broker checkout path must be absolute: ${t}`);return t}function ru(e=process.env){let t=e.BRAIN_GIT_BROKER_SOCKET;if(!t)return;let r=107;if(Buffer.byteLength(t)>r)throw Error(`Git broker socket path is too long for a unix socket (${Buffer.byteLength(t)} > ${r} bytes): ${t}`);return t}function iu(e=process.env){return fe(eu(e))}async function nu(e=process.env){let t=eu(e);try{await pn(t.dataDir,{recursive:!0}),await pn(t.cacheDir,{recursive:!0}),await pn(t.distDir,{recursive:!0})}catch(r){let i=r instanceof Error&&r.message.includes("EACCES")?`Cannot create data directories \u2014 permission denied. Run from a writable directory or check permissions on ${t.dataDir}`:`Cannot create data directories: ${P(r)}`;throw Error(i,{cause:r})}return fe(t)}class Oh{logger;migrations;constructor(e,t){this.logger=e,this.migrations=t??{getStandardConfigWithDirectories:()=>nu(),migrateEntities:Wd,migrateJobQueue:Gd,migrateConversations:Yd,migrateRuntimeState:Xd}}async runAllMigrations(e){this.logger.debug("Running database migrations...");let t=await this.migrations.getStandardConfigWithDirectories();if(e?.database)t.database.url=e.database;if(e?.jobQueueDatabase)t.jobQueueDatabase.url=e.jobQueueDatabase;if(e?.conversationDatabase)t.conversationDatabase.url=e.conversationDatabase;if(e?.runtimeStateDatabase)t.runtimeStateDatabase.url=e.runtimeStateDatabase;await this.migrateEntityDatabase(t),await this.migrateJobQueueDatabase(t),await this.migrateConversationDatabase(t),await this.migrateRuntimeStateDatabase(t),this.logger.debug("All database migrations completed successfully")}async migrateEntityDatabase(e){this.logger.debug("Running entity database migrations..."),await this.migrations.migrateEntities({url:e.database.url,...e.database.authToken&&{authToken:e.database.authToken}},this.logger)}async migrateJobQueueDatabase(e){this.logger.debug("Running job queue database migrations..."),await this.migrations.migrateJobQueue({url:e.jobQueueDatabase.url,...e.jobQueueDatabase.authToken&&{authToken:e.jobQueueDatabase.authToken}},this.logger)}async migrateConversationDatabase(e){this.logger.debug("Running conversation database migrations..."),await this.migrations.migrateConversations({url:e.conversationDatabase.url,...e.conversationDatabase.authToken&&{authToken:e.conversationDatabase.authToken}},this.logger)}async migrateRuntimeStateDatabase(e){this.logger.debug("Running runtime state database migrations..."),await this.migrations.migrateRuntimeState({url:e.runtimeStateDatabase.url,...e.runtimeStateDatabase.authToken&&{authToken:e.runtimeStateDatabase.authToken}},this.logger)}}var mn={kind:"service",serviceId:"brain-cli"},fn=`${mn.kind}:${mn.serviceId}`;function Pj(e="admin"){return{interfaceType:"cli",actor:mn,userPermissionLevel:e}}var Ej=c.enum(["eval"]),Aj=c.enum(["person","team","organization"]),gn=c.object({provider:c.enum(["hetzner","docker"]).default("hetzner"),serverSize:c.string().default("cx33"),location:c.string().default("fsn1"),domain:c.string().optional(),docker:c.object({enabled:c.boolean().default(!0),image:c.string().optional()}).prefault({}),ports:c.object({default:c.number().default(3333),preview:c.number().default(4321),production:c.number().default(8080)}).prefault({}),cdn:c.object({enabled:c.boolean().default(!1),provider:c.enum(["bunny","none"]).default("none")}).prefault({}),dns:c.object({enabled:c.boolean().default(!1),provider:c.enum(["bunny","none"]).default("none")}).prefault({}),paths:c.object({install:c.string().optional(),data:c.string().optional()}).prefault({})});var zh=c.object({providerKeys:We.optional(),model:c.string().optional(),embeddingModel:c.string().optional(),modelRuntimeUrl:c.string().optional(),answerModel:c.string().optional(),visionModel:c.string().optional(),imageModel:c.string().optional(),reasoningEffort:re.optional()}),su=c.object({name:c.string().default("brain-app"),version:c.string().default("1.0.0"),database:c.string().optional(),ai:zh.optional(),logLevel:xe.optional(),logFile:c.string().optional(),profileKind:c.string().trim().min(1).optional(),plugins:c.array(ft).default([]),spaces:c.array(c.string()).default([]),identity:ou.optional(),agentInstructions:c.array(c.string()).optional(),deployment:gn.prefault({}),http:He.prefault({})});var Mh="NODE_ENV";function Lh(){return process.env[Mh]}function hn(){return Lh()==="production"}function au(){return!hn()}var Uh="startup-check";function Bh(){return Object.fromEntries(un.map((e)=>[e,Uh]))}function qj(e){let r={...su.parse(e??{}),plugins:e?.plugins??[]};if(e?.permissions)r.permissions=e.permissions;if(e?.spaces)r.spaces=e.spaces;if(e?.cliConfig)r.cliConfig=e.cliConfig;if(e?.shellConfig)r.shellConfig=e.shellConfig;return r}function Jj(e,t){let r={plugins:e.plugins??[],...e.shellConfig};return $h(r),_h(e,r),Fh(e,r,t),Nh(e,r),Zh(e,r),Hh(e,r),Wh(e,r),qh(e,r),Gh(e,r),Jh(e,r),r}function $h(e){let t=iu();e.database??=t.database,e.jobQueueDatabase??=t.jobQueueDatabase,e.conversationDatabase??=t.conversationDatabase,e.runtimeStateDatabase??=t.runtimeStateDatabase,e.embeddingDatabase??=t.embeddingDatabase,e.embedding??=t.embedding,e.gitBrokerSocket??=ru(),e.gitBrokerCheckout??=tu()}function _h(e,t){if(e.database)t.database={url:e.database};if(e.profileKind)t.profileKind=e.profileKind;t.features={}}function Fh(e,t,r){let i=r?.mode==="startup-check",{providerKeys:n,...o}=F(e.ai??{});if(!n&&Object.keys(o).length===0&&!i)return;t.ai={...t.ai,providerKeys:{...i&&Bh(),...t.ai?.providerKeys,...n},...o}}function Nh(e,t){if(!e.logLevel&&!e.logFile)return;t.logging={level:e.logLevel??"info",format:"text",context:e.name,...e.logFile&&{file:e.logFile}}}function Zh(e,t){let r=e.permissions?.rules??[];t.permissions={...e.permissions,rules:r.some((i)=>i.pattern===fn)?r:[{pattern:fn,level:"admin"},...r]}}function Hh(e,t){if(e.spaces)t.spaces=e.spaces}function Wh(e,t){if(e.identity)t.identity=e.identity}function qh(e,t){if(e.agentInstructions)t.agentInstructions=e.agentInstructions}function Jh(e,t){t.http??={...F(e.http),port:e.deployment.ports.production}}function Gh(e,t){if(t.name=e.name,t.version=e.version,e.deployment.domain)t.siteBaseUrl=e.deployment.domain;t.localSiteUrl=`http://localhost:${e.deployment.ports.production}`,t.preferLocalUrls=au(),t.production=hn()}
|
|
114
114
|
export{fe as P,He as Q,xe as R,gt as S,O as T,rp as U,ip as V,np as W,dp as X,eo as Y,pp as Z,mp as _,fp as $,gp as aa,hp as ba,yp as ca,vp as da,Yr as ea,oa as fa,Si as ga,xc as ha,Og as ia,Sl as ja,Ug as ka,wl as la,at as ma,Bg as na,Se as oa,Gi as pa,Qi as qa,Ki as ra,_g as sa,Hg as ta,Wg as ua,KT as va,kl as wa,jl as xa,Gg as ya,Qg as za,Kg as Aa,Vg as Ba,on as Ca,Yg as Da,Xg as Ea,ih as Fa,dn as Ga,Wd as Ha,Gd as Ia,Yd as Ja,Xd as Ka,Oh as La,Pj as Ma,Aj as Na,qj as Oa,Jj as Pa};
|
|
115
115
|
|
|
116
|
-
//# debugId=
|
|
117
|
-
//# sourceMappingURL=index-
|
|
116
|
+
//# debugId=81E3B6DAA7E8C9F964756E2164756E21
|
|
117
|
+
//# sourceMappingURL=index-1t7tc0yr.js.map
|