@rizom/brain 0.2.0-alpha.722 → 0.2.0-alpha.723

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{B as a}from"./index-p87spzs9.js";import"./index-66v76w4h.js";import"./index-362h9qny.js";import"./index-cpg3s6b6.js";import"./index-r6mr3e4f.js";import"./index-2tdttvw4.js";import"./index-vb4gsj32.js";import"./index-126267mh.js";import"./index-p6bnaf8r.js";import"./index-ahe7gn4n.js";import"./index-f709exx1.js";export{a as App};
2
+ import{B as a}from"./index-2e3bsp1c.js";import"./index-66v76w4h.js";import"./index-vjz32ya5.js";import"./index-cpg3s6b6.js";import"./index-r6mr3e4f.js";import"./index-2tdttvw4.js";import"./index-vb4gsj32.js";import"./index-126267mh.js";import"./index-p6bnaf8r.js";import"./index-ahe7gn4n.js";import"./index-f709exx1.js";export{a as App};
3
3
 
4
4
  //# debugId=B0224EA8233B0C3764756E2164756E21
5
- //# sourceMappingURL=app-6606e1qd.js.map
5
+ //# sourceMappingURL=app-83k1da79.js.map
@@ -1,7 +1,7 @@
1
1
  // @bun
2
- import{N as p}from"./index-66v76w4h.js";import{Ga as m,La as d,Oa as v,Pa as S}from"./index-362h9qny.js";import{Og as h}from"./index-r6mr3e4f.js";import{eo as n,go as a}from"./index-vb4gsj32.js";import{Nv as s,Os as l,zs as f}from"./index-126267mh.js";import{Ix as g}from"./index-f709exx1.js";async function u(e){let[{default:i},{default:t}]=await Promise.all([import("./index-2tdcfe0c.js"),import("./package-z39gzvrz.js")]);return h(i,e??{},{name:t.name,version:t.version},{pluginId:"cli"})}class c{shell=null;config;signalScope=null;signalShutdownFiber=null;stopPromise=null;hasCLI=!1;static create(e,i){return new c(v(e),i)}constructor(e,i){if(this.config=e,this.hasCLI=process.argv.slice(2).includes("--cli"),i)this.shell=i}async migrate(){let e=a.getInstance();await new d(e).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(e,i){this.shell=m.createFresh(S(this.config,e),void 0,{...i?.processRole&&{processRole:i.processRole},...i?.peerChannel&&{peerChannel:i.peerChannel}})}wantsCLI(e){return this.hasCLI||e?.cli===!0}async registerCLIInterface(e){if(!this.wantsCLI(e))return;let i=this.getShell().getPluginManager();for(let t of await u(this.config.cliConfig))i.registerPlugin(t)}async initialize(e,i){if(!this.shell){if(!i?.migrationsCompleted)await this.migrate();this.createShell(e,i)}await this.registerCLIInterface(i),await this.getShell().initialize(e)}async start(){if(this.stopPromise)return;this.setupSignalHandlers()}stop(){return this.stopPromise??=this.stopApp(),this.stopPromise}async stopApp(){await this.closeSignalScope(),await this.shell?.shutdown()}async run(e){let t={debug:n.DEBUG,info:n.INFO,warn:n.WARN,error:n.ERROR}[this.config.logLevel??"info"]??n.INFO,o=this.wantsCLI(e),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}...`);try{await this.initialize(void 0,e),await this.start(),e?.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(e,i,t){await c.create(e,i).run(t)}setupSignalHandlers(){if(this.signalScope)return;let e=s.runSync(l.make()),i=()=>{this.requestGracefulShutdown("SIGINT")},t=()=>{this.requestGracefulShutdown("SIGTERM")},o=p(["SIGINT"],i),r=p(["SIGTERM"],t);s.runSync(l.addFinalizer(e,s.sync(()=>{r(),o()}))),this.signalScope=e}requestGracefulShutdown(e){if(this.signalShutdownFiber)return;let i=a.getInstance();i.info(`
2
+ import{N as p}from"./index-66v76w4h.js";import{Ga as m,La as d,Oa as v,Pa as S}from"./index-vjz32ya5.js";import{Og as h}from"./index-r6mr3e4f.js";import{eo as n,go as a}from"./index-vb4gsj32.js";import{Nv as s,Os as l,zs as f}from"./index-126267mh.js";import{Ix as g}from"./index-f709exx1.js";async function u(e){let[{default:i},{default:t}]=await Promise.all([import("./index-2tdcfe0c.js"),import("./package-z028b1sx.js")]);return h(i,e??{},{name:t.name,version:t.version},{pluginId:"cli"})}class c{shell=null;config;signalScope=null;signalShutdownFiber=null;stopPromise=null;hasCLI=!1;static create(e,i){return new c(v(e),i)}constructor(e,i){if(this.config=e,this.hasCLI=process.argv.slice(2).includes("--cli"),i)this.shell=i}async migrate(){let e=a.getInstance();await new d(e).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(e,i){this.shell=m.createFresh(S(this.config,e),void 0,{...i?.processRole&&{processRole:i.processRole},...i?.peerChannel&&{peerChannel:i.peerChannel}})}wantsCLI(e){return this.hasCLI||e?.cli===!0}async registerCLIInterface(e){if(!this.wantsCLI(e))return;let i=this.getShell().getPluginManager();for(let t of await u(this.config.cliConfig))i.registerPlugin(t)}async initialize(e,i){if(!this.shell){if(!i?.migrationsCompleted)await this.migrate();this.createShell(e,i)}await this.registerCLIInterface(i),await this.getShell().initialize(e)}async start(){if(this.stopPromise)return;this.setupSignalHandlers()}stop(){return this.stopPromise??=this.stopApp(),this.stopPromise}async stopApp(){await this.closeSignalScope(),await this.shell?.shutdown()}async run(e){let t={debug:n.DEBUG,info:n.INFO,warn:n.WARN,error:n.ERROR}[this.config.logLevel??"info"]??n.INFO,o=this.wantsCLI(e),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}...`);try{await this.initialize(void 0,e),await this.start(),e?.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(e,i,t){await c.create(e,i).run(t)}setupSignalHandlers(){if(this.signalScope)return;let e=s.runSync(l.make()),i=()=>{this.requestGracefulShutdown("SIGINT")},t=()=>{this.requestGracefulShutdown("SIGTERM")},o=p(["SIGINT"],i),r=p(["SIGTERM"],t);s.runSync(l.addFinalizer(e,s.sync(()=>{r(),o()}))),this.signalScope=e}requestGracefulShutdown(e){if(this.signalShutdownFiber)return;let i=a.getInstance();i.info(`
3
3
  Received ${e}, shutting down gracefully...`);let t=s.tryPromise({try:()=>this.stop(),catch:(o)=>o}).pipe(s.match({onFailure:(o)=>{i.error("Error during shutdown:",o),process.exit(1)},onSuccess:()=>{process.exit(0)}}));this.signalShutdownFiber=s.runFork(t)}async closeSignalScope(){let e=this.signalScope;if(this.signalScope=null,e)await s.runPromise(l.close(e,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=244D91762A713C4E64756E2164756E21
7
- //# sourceMappingURL=index-p87spzs9.js.map
7
+ //# sourceMappingURL=index-2e3bsp1c.js.map
@@ -1,6 +1,6 @@
1
1
  // @bun
2
- import{zx as t}from"./index-p6bnaf8r.js";var g={name:"@rizom/brain",version:"0.2.0-alpha.722",description:"Brain runtime + CLI \u2014 scaffold, run, and manage AI brain instances",keywords:["brain","ai","cli","mcp","agent","personal-ai","knowledge-management"],license:"AGPL-3.0-only",author:"Yeehaa <yeehaa@rizom.ai> (https://rizom.ai)",bin:{brain:"./dist/brain.js"},bugs:"https://github.com/rizom-ai/brains/issues",dependencies:{"@clack/prompts":"^1.5.1","@modelcontextprotocol/client":"^2.3.1","@modelcontextprotocol/server":"^2.3.1","@tailwindcss/postcss":"^4.3.1","@tailwindcss/typography":"^0.5.20","@types/react":"^19.2.17",postcss:"^8.5.29",react:"^19.2.7","react-dom":"^19.2.7",tailwindcss:"^4.3.1",yaml:"^2.9.0",zod:"^4.2.0"},devDependencies:{"@brains/a2a":"workspace:*","@brains/action-board":"workspace:*","@brains/action-items":"workspace:*","@brains/admin":"workspace:*","@brains/agent-discovery":"workspace:*","@brains/ai-evaluation":"workspace:*","@brains/ai-service":"workspace:*","@brains/analytics":"workspace:*","@brains/app":"workspace:*","@brains/ask-content":"workspace:*","@brains/assessment":"workspace:*","@brains/atproto":"workspace:*","@brains/atproto-registry":"workspace:*","@brains/auth-service":"workspace:*","@brains/blog":"workspace:*","@brains/book":"workspace:*","@brains/build-tools":"workspace:*","@brains/chat":"workspace:*","@brains/contact":"workspace:*","@brains/content-formatters":"workspace:*","@brains/content-pipeline":"workspace:*","@brains/contracts":"workspace:*","@brains/conversation-memory":"workspace:*","@brains/core":"workspace:*","@brains/dashboard":"workspace:*","@brains/decks":"workspace:*","@brains/deploy-support":"workspace:*","@brains/directory-sync":"workspace:*","@brains/doc":"workspace:*","@brains/document-plugin":"workspace:*","@brains/email":"workspace:*","@brains/email-workflows":"workspace:*","@brains/entity-service":"workspace:*","@brains/eslint-config":"workspace:*","@brains/faq":"workspace:*","@brains/form":"workspace:*","@brains/forms":"workspace:*","@brains/guide":"workspace:*","@brains/http-host":"workspace:*","@brains/image":"workspace:*","@brains/image-plugin":"workspace:*","@brains/knowledge-map":"workspace:*","@brains/link":"workspace:*","@brains/linkedin-import":"workspace:*","@brains/mcp":"workspace:*","@brains/mcp-service":"workspace:*","@brains/newsletter":"workspace:*","@brains/note":"workspace:*","@brains/notifications":"workspace:*","@brains/oauth-broker":"workspace:*","@brains/obsidian-vault":"workspace:*","@brains/onboarding":"workspace:*","@brains/operation-context":"workspace:*","@brains/playbooks":"workspace:*","@brains/plugins":"workspace:*","@brains/portfolio":"workspace:*","@brains/profile":"workspace:*","@brains/prompt":"workspace:*","@brains/quiz":"workspace:*","@brains/sdk":"workspace:*","@brains/series":"workspace:*","@brains/site-builder-plugin":"workspace:*","@brains/site-composition":"workspace:*","@brains/site-content":"workspace:*","@brains/site-default":"workspace:*","@brains/site-info":"workspace:*","@brains/site-organization":"workspace:*","@brains/site-personal":"workspace:*","@brains/site-professional":"workspace:*","@brains/social-media":"workspace:*","@brains/stock-photo":"workspace:*","@brains/studio":"workspace:*","@brains/style-guide":"workspace:*","@brains/templates":"workspace:*","@brains/test-utils":"workspace:*","@brains/theme-rizom":"workspace:*","@brains/topics":"workspace:*","@brains/typescript-config":"workspace:*","@brains/unified-inbox":"workspace:*","@brains/utils":"workspace:*","@brains/web-chat":"workspace:*","@brains/wishlist":"workspace:*","@libsql/client":"^0.17.4","@manypkg/get-packages":"^3.1.0","@rizom/theme-default":"workspace:*","@types/bun":"^1.4.0","@types/react-dom":"^19.0.3",rolldown:"^1.0.0","rolldown-plugin-dts":"^0.27.4",typescript:"^7.0.2"},engines:{bun:">=1.4.0"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./chat":{types:"./dist/chat.d.ts",import:"./dist/chat.js"},"./cli":"./dist/brain.js","./model":{types:"./dist/model.d.ts",import:"./dist/model.js"},"./entities":{types:"./dist/entities.d.ts",import:"./dist/entities.js"},"./services":{types:"./dist/services.d.ts",import:"./dist/services.js"},"./interfaces":{types:"./dist/interfaces.d.ts",import:"./dist/interfaces.js"},"./testing":{types:"./dist/testing.d.ts",import:"./dist/testing.js"},"./deploy":{types:"./dist/deploy.d.ts",import:"./dist/deploy.js"},"./tsconfig.instance.json":"./tsconfig.instance.json"},files:["dist","templates","tsconfig.instance.json"],homepage:"https://github.com/rizom-ai/brains/tree/main/packages/brain-cli#readme",optionalDependencies:{"@bitwarden/sdk-napi":"^1.0.0","@libsql/client":"^0.17.4","@tailwindcss/oxide":"^4.1.4",lightningcss:"^1.29.2","react-devtools-core":"^7.0.1"},publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/rizom-ai/brains.git",directory:"packages/brain-cli"},scripts:{build:"bun scripts/build.ts","build:ui":"turbo run build --filter=@brains/web-chat --filter=@brains/studio",eval:"bun run build && brain-eval","eval:headless":"bun run eval --suite headless","eval:personal":"bun run eval --suite personal","eval:professional":"bun run eval --suite professional","eval:team":"bun run eval --suite team","eval:git":"bun run eval --suite professional --tags requires-supervised-git --mcp-basic --url http://localhost:8080 --token $MCP_AUTH_TOKEN",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",prepublishOnly:"bun scripts/build.ts","start:minimal":"sh scripts/start-test-app.sh minimal","start:unified-inbox":"sh scripts/start-test-app.sh unified-inbox","start:personal":"sh scripts/start-test-app.sh personal","start:publishing":"sh scripts/start-test-app.sh publishing","start:team":"sh scripts/start-test-app.sh team",test:"bun test --parallel=4 --path-ignore-patterns='**/{boot-smoke,served-surface,canonical-eval-suites,public-plugin-api,public-authoring-golden,public-authoring-docs,public-chat-contract,package-metadata}.test.ts'","test:boot-smoke":"bun run build && bun run test:boot-smoke:prebuilt","test:boot-smoke:prebuilt":"bun test test/boot-smoke.test.ts test/served-surface.test.ts","test:evals":"bun test test/canonical-eval-suites.test.ts","test:surface":"bun test test/public-plugin-api.test.ts test/public-authoring-golden.test.ts test/public-authoring-docs.test.ts test/public-chat-contract.test.ts test/package-metadata.test.ts && bun run test:boot-smoke:prebuilt","test:packed:compat":"bun scripts/run-packed-compatibility.ts",typecheck:"tsc --noEmit && tsc --noEmit -p tsconfig.model.json"},type:"module"};import{existsSync as d,readFileSync as b}from"fs";import{dirname as u,join as a}from"path";var k=t.looseObject({name:t.string().min(1),version:t.string().min(1),dependencies:t.record(t.string(),t.string()).optional(),peerDependencies:t.record(t.string(),t.string()).optional()});class r extends Error{constructor(e,s,i){super(i?`Package "${e.name}@${e.version}" requires @rizom/brain "${i}", but "${s}" is installed; install a compatible Brain version or update the peer range only after testing that release`:`Package "${e.name}@${e.version}" must declare a @rizom/brain peer dependency; add the tested range under peerDependencies in its package.json`);this.name="PackagePeerCompatibilityError"}}function o(e){let s=u(e);return s===e?[e]:[e,...o(s)]}function m(e,s){return Object.freeze({name:e.name,version:e.version,dependencies:Object.freeze({...e.dependencies??{}}),peerDependencies:Object.freeze({...e.peerDependencies??{}}),directory:s})}function v(e){let s=o(e).find((p)=>d(a(p,"package.json")));if(s===void 0)throw Error(`No package.json at or above "${e}"; run from the package's own directory`);let i=a(s,"package.json"),c=JSON.parse(b(i,"utf8")),n=k.safeParse(c);if(!n.success)throw Error(`"${i}" must declare non-empty name and version fields`);return m(n.data,s)}function j(e,s){let i=e.peerDependencies["@rizom/brain"];if(!i||!Bun.semver.satisfies(s,i))throw new r(e,s,i)}
2
+ import{zx as t}from"./index-p6bnaf8r.js";var g={name:"@rizom/brain",version:"0.2.0-alpha.723",description:"Brain runtime + CLI \u2014 scaffold, run, and manage AI brain instances",keywords:["brain","ai","cli","mcp","agent","personal-ai","knowledge-management"],license:"AGPL-3.0-only",author:"Yeehaa <yeehaa@rizom.ai> (https://rizom.ai)",bin:{brain:"./dist/brain.js"},bugs:"https://github.com/rizom-ai/brains/issues",dependencies:{"@clack/prompts":"^1.5.1","@modelcontextprotocol/client":"^2.3.1","@modelcontextprotocol/server":"^2.3.1","@tailwindcss/postcss":"^4.3.1","@tailwindcss/typography":"^0.5.20","@types/react":"^19.2.17",postcss:"^8.5.29",react:"^19.2.7","react-dom":"^19.2.7",tailwindcss:"^4.3.1",yaml:"^2.9.0",zod:"^4.2.0"},devDependencies:{"@brains/a2a":"workspace:*","@brains/action-board":"workspace:*","@brains/action-items":"workspace:*","@brains/admin":"workspace:*","@brains/agent-discovery":"workspace:*","@brains/ai-evaluation":"workspace:*","@brains/ai-service":"workspace:*","@brains/analytics":"workspace:*","@brains/app":"workspace:*","@brains/ask-content":"workspace:*","@brains/assessment":"workspace:*","@brains/atproto":"workspace:*","@brains/atproto-registry":"workspace:*","@brains/auth-service":"workspace:*","@brains/blog":"workspace:*","@brains/book":"workspace:*","@brains/build-tools":"workspace:*","@brains/chat":"workspace:*","@brains/contact":"workspace:*","@brains/content-formatters":"workspace:*","@brains/content-pipeline":"workspace:*","@brains/contracts":"workspace:*","@brains/conversation-memory":"workspace:*","@brains/core":"workspace:*","@brains/dashboard":"workspace:*","@brains/decks":"workspace:*","@brains/deploy-support":"workspace:*","@brains/directory-sync":"workspace:*","@brains/doc":"workspace:*","@brains/document-plugin":"workspace:*","@brains/email":"workspace:*","@brains/email-workflows":"workspace:*","@brains/entity-service":"workspace:*","@brains/eslint-config":"workspace:*","@brains/faq":"workspace:*","@brains/form":"workspace:*","@brains/forms":"workspace:*","@brains/guide":"workspace:*","@brains/http-host":"workspace:*","@brains/image":"workspace:*","@brains/image-plugin":"workspace:*","@brains/knowledge-map":"workspace:*","@brains/link":"workspace:*","@brains/linkedin-import":"workspace:*","@brains/mcp":"workspace:*","@brains/mcp-service":"workspace:*","@brains/newsletter":"workspace:*","@brains/note":"workspace:*","@brains/notifications":"workspace:*","@brains/oauth-broker":"workspace:*","@brains/obsidian-vault":"workspace:*","@brains/onboarding":"workspace:*","@brains/operation-context":"workspace:*","@brains/playbooks":"workspace:*","@brains/plugins":"workspace:*","@brains/portfolio":"workspace:*","@brains/profile":"workspace:*","@brains/prompt":"workspace:*","@brains/quiz":"workspace:*","@brains/sdk":"workspace:*","@brains/series":"workspace:*","@brains/site-builder-plugin":"workspace:*","@brains/site-composition":"workspace:*","@brains/site-content":"workspace:*","@brains/site-default":"workspace:*","@brains/site-info":"workspace:*","@brains/site-organization":"workspace:*","@brains/site-personal":"workspace:*","@brains/site-professional":"workspace:*","@brains/social-media":"workspace:*","@brains/stock-photo":"workspace:*","@brains/studio":"workspace:*","@brains/style-guide":"workspace:*","@brains/templates":"workspace:*","@brains/test-utils":"workspace:*","@brains/theme-rizom":"workspace:*","@brains/topics":"workspace:*","@brains/typescript-config":"workspace:*","@brains/unified-inbox":"workspace:*","@brains/utils":"workspace:*","@brains/web-chat":"workspace:*","@brains/wishlist":"workspace:*","@libsql/client":"^0.17.4","@manypkg/get-packages":"^3.1.0","@rizom/theme-default":"workspace:*","@types/bun":"^1.4.0","@types/react-dom":"^19.0.3",rolldown:"^1.0.0","rolldown-plugin-dts":"^0.27.4",typescript:"^7.0.2"},engines:{bun:">=1.4.0"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./chat":{types:"./dist/chat.d.ts",import:"./dist/chat.js"},"./cli":"./dist/brain.js","./model":{types:"./dist/model.d.ts",import:"./dist/model.js"},"./entities":{types:"./dist/entities.d.ts",import:"./dist/entities.js"},"./services":{types:"./dist/services.d.ts",import:"./dist/services.js"},"./interfaces":{types:"./dist/interfaces.d.ts",import:"./dist/interfaces.js"},"./testing":{types:"./dist/testing.d.ts",import:"./dist/testing.js"},"./deploy":{types:"./dist/deploy.d.ts",import:"./dist/deploy.js"},"./tsconfig.instance.json":"./tsconfig.instance.json"},files:["dist","templates","tsconfig.instance.json"],homepage:"https://github.com/rizom-ai/brains/tree/main/packages/brain-cli#readme",optionalDependencies:{"@bitwarden/sdk-napi":"^1.0.0","@libsql/client":"^0.17.4","@tailwindcss/oxide":"^4.1.4",lightningcss:"^1.29.2","react-devtools-core":"^7.0.1"},publishConfig:{access:"public"},repository:{type:"git",url:"https://github.com/rizom-ai/brains.git",directory:"packages/brain-cli"},scripts:{build:"bun scripts/build.ts","build:ui":"turbo run build --filter=@brains/web-chat --filter=@brains/studio",eval:"bun run build && brain-eval","eval:headless":"bun run eval --suite headless","eval:personal":"bun run eval --suite personal","eval:professional":"bun run eval --suite professional","eval:team":"bun run eval --suite team","eval:git":"bun run eval --suite professional --tags requires-supervised-git --mcp-basic --url http://localhost:8080 --token $MCP_AUTH_TOKEN",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",prepublishOnly:"bun scripts/build.ts","start:minimal":"sh scripts/start-test-app.sh minimal","start:unified-inbox":"sh scripts/start-test-app.sh unified-inbox","start:personal":"sh scripts/start-test-app.sh personal","start:publishing":"sh scripts/start-test-app.sh publishing","start:team":"sh scripts/start-test-app.sh team",test:"bun test --parallel=4 --path-ignore-patterns='**/{boot-smoke,served-surface,canonical-eval-suites,public-plugin-api,public-authoring-golden,public-authoring-docs,public-chat-contract,package-metadata}.test.ts'","test:boot-smoke":"bun run build && bun run test:boot-smoke:prebuilt","test:boot-smoke:prebuilt":"bun test test/boot-smoke.test.ts test/served-surface.test.ts","test:evals":"bun test test/canonical-eval-suites.test.ts","test:surface":"bun test test/public-plugin-api.test.ts test/public-authoring-golden.test.ts test/public-authoring-docs.test.ts test/public-chat-contract.test.ts test/package-metadata.test.ts && bun run test:boot-smoke:prebuilt","test:packed:compat":"bun scripts/run-packed-compatibility.ts",typecheck:"tsc --noEmit && tsc --noEmit -p tsconfig.model.json"},type:"module"};import{existsSync as d,readFileSync as b}from"fs";import{dirname as u,join as a}from"path";var k=t.looseObject({name:t.string().min(1),version:t.string().min(1),dependencies:t.record(t.string(),t.string()).optional(),peerDependencies:t.record(t.string(),t.string()).optional()});class r extends Error{constructor(e,s,i){super(i?`Package "${e.name}@${e.version}" requires @rizom/brain "${i}", but "${s}" is installed; install a compatible Brain version or update the peer range only after testing that release`:`Package "${e.name}@${e.version}" must declare a @rizom/brain peer dependency; add the tested range under peerDependencies in its package.json`);this.name="PackagePeerCompatibilityError"}}function o(e){let s=u(e);return s===e?[e]:[e,...o(s)]}function m(e,s){return Object.freeze({name:e.name,version:e.version,dependencies:Object.freeze({...e.dependencies??{}}),peerDependencies:Object.freeze({...e.peerDependencies??{}}),directory:s})}function v(e){let s=o(e).find((p)=>d(a(p,"package.json")));if(s===void 0)throw Error(`No package.json at or above "${e}"; run from the package's own directory`);let i=a(s,"package.json"),c=JSON.parse(b(i,"utf8")),n=k.safeParse(c);if(!n.success)throw Error(`"${i}" must declare non-empty name and version fields`);return m(n.data,s)}function j(e,s){let i=e.peerDependencies["@rizom/brain"];if(!i||!Bun.semver.satisfies(s,i))throw new r(e,s,i)}
3
3
  export{v as O,j as P,g as Q};
4
4
 
5
- //# debugId=0AE41FD09FE9F6C364756E2164756E21
6
- //# sourceMappingURL=index-ggsekr5v.js.map
5
+ //# debugId=16BE822A254DD51864756E2164756E21
6
+ //# sourceMappingURL=index-e28fkvmr.js.map
@@ -5,6 +5,6 @@
5
5
  "import { existsSync, readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { z } from \"@brains/utils/zod\";\n\nconst packageManifestSchema = z.looseObject({\n name: z.string().min(1),\n version: z.string().min(1),\n dependencies: z.record(z.string(), z.string()).optional(),\n peerDependencies: z.record(z.string(), z.string()).optional(),\n});\n\nexport interface InstalledPackageManifest {\n readonly name: string;\n readonly version: string;\n readonly dependencies: Readonly<Record<string, string>>;\n readonly peerDependencies: Readonly<Record<string, string>>;\n readonly directory: string;\n}\n\nexport class PackagePeerCompatibilityError extends Error {\n constructor(\n packageMetadata: InstalledPackageManifest,\n brainVersion: string,\n peerRange: string | undefined,\n ) {\n super(\n peerRange\n ? `Package \"${packageMetadata.name}@${packageMetadata.version}\" requires @rizom/brain \"${peerRange}\", but \"${brainVersion}\" is installed; install a compatible Brain version or update the peer range only after testing that release`\n : `Package \"${packageMetadata.name}@${packageMetadata.version}\" must declare a @rizom/brain peer dependency; add the tested range under peerDependencies in its package.json`,\n );\n this.name = \"PackagePeerCompatibilityError\";\n }\n}\n\nfunction matchesPackageRef(packageRef: string, packageName: string): boolean {\n return packageRef === packageName || packageRef.startsWith(`${packageName}/`);\n}\n\nfunction ancestorDirectories(directory: string): string[] {\n const parent = dirname(directory);\n return parent === directory\n ? [directory]\n : [directory, ...ancestorDirectories(parent)];\n}\n\nfunction installedManifest(\n manifest: z.output<typeof packageManifestSchema>,\n directory: string,\n): InstalledPackageManifest {\n return Object.freeze({\n name: manifest.name,\n version: manifest.version,\n dependencies: Object.freeze({ ...(manifest.dependencies ?? {}) }),\n peerDependencies: Object.freeze({ ...(manifest.peerDependencies ?? {}) }),\n directory,\n });\n}\n\n/**\n * The package a directory belongs to: the nearest `package.json` at or above\n * it, the way an installed module's package is found.\n */\nexport function findPackageManifest(\n fromDirectory: string,\n): InstalledPackageManifest {\n const directory = ancestorDirectories(fromDirectory).find((candidate) =>\n existsSync(join(candidate, \"package.json\")),\n );\n if (directory === undefined) {\n throw new Error(\n `No package.json at or above \"${fromDirectory}\"; run from the package's own directory`,\n );\n }\n const manifestPath = join(directory, \"package.json\");\n const rawManifest: unknown = JSON.parse(readFileSync(manifestPath, \"utf8\"));\n const parsed = packageManifestSchema.safeParse(rawManifest);\n if (!parsed.success) {\n throw new Error(\n `\"${manifestPath}\" must declare non-empty name and version fields`,\n );\n }\n return installedManifest(parsed.data, directory);\n}\n\nexport function resolveInstalledPackageManifest(\n packageRef: string,\n fromDirectory: string,\n): InstalledPackageManifest {\n let resolved: string;\n try {\n resolved = Bun.resolveSync(packageRef, fromDirectory);\n } catch (error) {\n throw new Error(\n `Could not resolve installed package \"${packageRef}\" from \"${fromDirectory}\"; install it in the Brain application or correct the package reference`,\n { cause: error },\n );\n }\n\n for (const directory of ancestorDirectories(dirname(resolved))) {\n const manifestPath = join(directory, \"package.json\");\n if (!existsSync(manifestPath)) continue;\n\n const rawManifest: unknown = JSON.parse(readFileSync(manifestPath, \"utf8\"));\n const parsed = packageManifestSchema.safeParse(rawManifest);\n if (parsed.success && matchesPackageRef(packageRef, parsed.data.name)) {\n return installedManifest(parsed.data, directory);\n }\n }\n\n throw new Error(\n `Resolved package \"${packageRef}\" from \"${fromDirectory}\" but could not find valid package metadata; ensure its package.json declares matching non-empty name and version fields`,\n );\n}\n\n/** A package runs only on a Brain its `@rizom/brain` peer range admits. */\nexport function assertBrainPeerCompatibility(\n packageMetadata: InstalledPackageManifest,\n brainVersion: string,\n): void {\n const peerRange = packageMetadata.peerDependencies[\"@rizom/brain\"];\n if (!peerRange || !Bun.semver.satisfies(brainVersion, peerRange)) {\n throw new PackagePeerCompatibilityError(\n packageMetadata,\n brainVersion,\n peerRange,\n );\n }\n}\n\nexport function resolveBrainDefinitionDependencies(\n brainPackageRef: string,\n fromDirectory: string,\n): InstalledPackageManifest[] {\n const brain = resolveInstalledPackageManifest(brainPackageRef, fromDirectory);\n if (brain.name === \"@rizom/brain\") return [];\n\n const runtime = resolveInstalledPackageManifest(\n \"@rizom/brain\",\n fromDirectory,\n );\n assertBrainPeerCompatibility(brain, runtime.version);\n\n const definitionDependencies = Object.keys(brain.dependencies)\n .map((dependency) =>\n resolveInstalledPackageManifest(dependency, brain.directory),\n )\n .filter(\n (dependency) => dependency.peerDependencies[\"@rizom/brain\"] !== undefined,\n );\n for (const dependency of definitionDependencies) {\n assertBrainPeerCompatibility(dependency, runtime.version);\n }\n return definitionDependencies;\n}\n"
6
6
  ],
7
7
  "mappings": ";88MAAA,qBAAS,kBAAY,WACrB,kBAAS,UAAS,aAGlB,IAAM,EAAwB,EAAE,YAAY,CAC1C,KAAM,EAAE,OAAO,EAAE,IAAI,CAAC,EACtB,QAAS,EAAE,OAAO,EAAE,IAAI,CAAC,EACzB,aAAc,EAAE,OAAO,EAAE,OAAO,EAAG,EAAE,OAAO,CAAC,EAAE,SAAS,EACxD,iBAAkB,EAAE,OAAO,EAAE,OAAO,EAAG,EAAE,OAAO,CAAC,EAAE,SAAS,CAC9D,CAAC,EAUM,MAAM,UAAsC,KAAM,CACvD,WAAW,CACT,EACA,EACA,EACA,CACA,MACE,EACI,YAAY,EAAgB,QAAQ,EAAgB,mCAAmC,YAAoB,+GAC3G,YAAY,EAAgB,QAAQ,EAAgB,uHAC1D,EACA,KAAK,KAAO,gCAEhB,CAMA,SAAS,CAAmB,CAAC,EAA6B,CACxD,IAAM,EAAS,EAAQ,CAAS,EAChC,OAAO,IAAW,EACd,CAAC,CAAS,EACV,CAAC,EAAW,GAAG,EAAoB,CAAM,CAAC,EAGhD,SAAS,CAAiB,CACxB,EACA,EAC0B,CAC1B,OAAO,OAAO,OAAO,CACnB,KAAM,EAAS,KACf,QAAS,EAAS,QAClB,aAAc,OAAO,OAAO,IAAM,EAAS,cAAgB,CAAC,CAAG,CAAC,EAChE,iBAAkB,OAAO,OAAO,IAAM,EAAS,kBAAoB,CAAC,CAAG,CAAC,EACxE,WACF,CAAC,EAOI,SAAS,CAAmB,CACjC,EAC0B,CAC1B,IAAM,EAAY,EAAoB,CAAa,EAAE,KAAK,CAAC,IACzD,EAAW,EAAK,EAAW,cAAc,CAAC,CAC5C,EACA,GAAI,IAAc,OAChB,MAAU,MACR,gCAAgC,0CAClC,EAEF,IAAM,EAAe,EAAK,EAAW,cAAc,EAC7C,EAAuB,KAAK,MAAM,EAAa,EAAc,MAAM,CAAC,EACpE,EAAS,EAAsB,UAAU,CAAW,EAC1D,GAAI,CAAC,EAAO,QACV,MAAU,MACR,IAAI,mDACN,EAEF,OAAO,EAAkB,EAAO,KAAM,CAAS,EAkC1C,SAAS,CAA4B,CAC1C,EACA,EACM,CACN,IAAM,EAAY,EAAgB,iBAAiB,gBACnD,GAAI,CAAC,GAAa,CAAC,IAAI,OAAO,UAAU,EAAc,CAAS,EAC7D,MAAM,IAAI,EACR,EACA,EACA,CACF",
8
- "debugId": "0AE41FD09FE9F6C364756E2164756E21",
8
+ "debugId": "16BE822A254DD51864756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -97,9 +97,9 @@ ${Nc(i)}`:a,args:t.buildArgs((d)=>({...l,confirmed:!0,confirmationToken:d}))}}as
97
97
  `)[0]??"":"",text:n}))}function Vf(e,t){let r=on(t.heading),i=on(t.text);return Array.from(e).reduce((n,o)=>n+(i.has(o)?1:0)+(r.has(o)?1:0),0)}function Wl(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 Gl(e,t,r=ql){if(e.length<=r)return e;let i=on(t),n=Kf(e).map((a)=>({section:a,score:Vf(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 Wl(e.trim(),r);if(o.text.length>r)return Wl(o.text,r);let{kept:s}=n.reduce((a,l)=>{let d=l.text.length+(a.kept.length>0?Nl.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?`
98
98
 
99
99
  `:Nl}${a.text}`}).join("")}var Yf=0.5;function Ql(e,t){let r=e??t.limit;return t.maxLimit===void 0?r:Math.min(r,t.maxLimit)}function Kl(e,t,r,i){let n=Li(e.entity,r);if(n!==e.entity)return{...e,entity:n,excerpt:n.content};let o=ze(n.content);if(o.length<=i)return{...e,entity:n};let{content:s,...a}=n;return{...e,entity:a,excerpt:Gl(o,t,i),excerpted:!0}}var Rr=(e)=>e==="public"?{publishedOnly:!0}:{};function Xf(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 Vl(e){let{entityService:t,logger:r}=e;return[ce("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. 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?'.",Ic,async(i,n)=>{Sr(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:Ql(i.limit,e.searchBudget),filter:{visibilityScope:o},...Rr(o)}})).map((m)=>Kl({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??Yf,a=await t.search({query:i.query,options:{limit:Ql(i.limit,e.searchBudget),...i.scope.kind==="type"&&{types:[i.scope.entityType]},...i.includeUngenerated!==void 0&&{includeUngenerated:i.includeUngenerated},visibilityScope:o,...Rr(o)}}),l=a.filter((u)=>u.score>=s),d=l.length===0?Xf(a,s):void 0;return{success:!0,data:{results:l.map((u)=>Kl(u,i.query,e.entityRegistry,e.searchBudget.excerptChars)),...d&&{belowThreshold:d}}}},{visibility:"public",sideEffects:"none",cli:{name:"search"}}),ce("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.",Pc,async(i,n)=>{if(Sr(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 H(t,{entityType:i.entityType,identifier:i.id},{visibilityScope:o,logger:r,read:{...Rr(o),source:!0,binaryContent:"reference"}});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:ze(a.content)}:a}}},{visibility:"public",sideEffects:"none",cli:{name:"get"}}),ce("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.",Cc,async(i,n)=>{if(Sr(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,binaryContent:"reference",...Rr(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 eh(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 th(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(eh),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 Yl(e){let{entityService:t,analytics:r}=e,i=r.getDefinitions(),n=i.map((o)=>`${o.type} (${o.description})`).join("; ");return[ce("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}.`,th(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 Xl(e){let{jobs:t}=e;return[N("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.",Dc,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 rh(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 ed(e){return[ce("system","status","Get system status including version, background work, and the web surfaces (such as the dashboard and Studio) the caller can open, with their paths; trusted callers also get the model and entity totals",c.object({}),async(t,r)=>({success:!0,data:rh(await e.getAppInfo(),(i)=>e.permissionService.hasPermission(r.userPermissionLevel??"public",i))}),{visibility:"public",sideEffects:"none",cli:{name:"status"}})]}function td(e){return[...Vl(e),...Xl(e),...ed(e),...Zl(e),...Yl(e)]}function rd(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(`
100
- `)}]})},{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 id(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,options:{binaryContent:"reference"}})).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}`);return{contents:[{uri:`entity://${r}/${i}`,mimeType:"text/markdown",text:n.content}]}}}]}function nd(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 od(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; 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().map((i)=>`- ${i}: ${e.entityRegistry.getAdapter(i).purpose}`)].join(`
100
+ `)}]})},{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 id(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,options:{binaryContent:"reference"}})).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}`);return{contents:[{uri:`entity://${r}/${i}`,mimeType:"text/markdown",text:n.content}]}}}]}function nd(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 od(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().map((i)=>`- ${i}: ${e.entityRegistry.getAdapter(i).purpose}`)].join(`
101
101
  `)}var Le="system",ih=c.object({toolName:c.string(),args:c.unknown(),...sd.partial().shape});function wr(e,t,r,i,n){for(let o of e)try{t(o)}catch{n.debug(`System ${i} ${r(o)} already registered, skipping`)}}function ad(e,t,r,i){let n=td(e);wr(n,(u)=>t.registerTool(Le,u),(u)=>u.name,"tool",i);let o=r.subscribe(Qt.toolExecute(Le),async(u)=>{let p=ih.safeParse(u.payload);if(!p.success)return{success:!1,error:"Invalid system tool execute payload"};let{toolName:m,args:g,interfaceType:f,actor:h,conversationId:v,channelId:y,userPermissionLevel:S}=p.data,R=n.find((E)=>E.name===m);if(!R)return{success:!1,error:`System tool not found: ${m}`};let w={interfaceType:f??"system",actor:h??{kind:"service",serviceId:"system"}};if(v)w.conversationId=v;if(y)w.channelId=y;if(S)w.userPermissionLevel=S;return{success:!0,data:await R.handler(g,w)}});i.debug(`Registered ${n.length} system tools`);let s=rd(e);wr(s,(u)=>t.registerResource(Le,u),(u)=>u.uri,"resource",i),i.debug(`Registered ${s.length} system resources`);let a=id(e);wr(a,(u)=>t.registerResourceTemplate(Le,u),(u)=>u.uriTemplate,"resource template",i),i.debug(`Registered ${a.length} system resource templates`);let l=nd(e);wr(l,(u)=>t.registerPrompt(Le,u),(u)=>u.name,"prompt",i),i.debug(`Registered ${l.length} system prompts`);let d=od(e);try{t.registerInstructions(Le,d)}catch{i.debug("System instructions already registered, skipping")}return i.debug("Registered system instructions"),o}function pd(e){let{services:t,jobs:r,analytics:i,query:n,getAppInfo:o}=e,s=t.jobQueueService,a=t.logger.child("system"),l=ad({entityService:t.entityService,entityRegistry:t.entityRegistry,jobs:{...r,enqueue:cd(s,"system",!1),enqueueBatch:dd(r,"system"),registerHandler:ud(s,"system"),has:ld(s)},conversationService:t.conversationService,runtimeUploads:t.runtimeUploadRegistry,attachments:Ir(t.attachmentRegistry),logger:a,query:n,getIdentity:()=>t.identityService.getCharacter(),getProfile:()=>t.profileService.getProfile(),getAppInfo:o,searchBudget:Jl(t.aiService.getConfig().model),analytics:i,permissionService:t.permissionService},t.mcpService,t.messageBus,a);t.disposables.push(l)}class sn{scope;closePromise=null;closed=!1;constructor(){this.scope=b.runSync(j.make())}buildLayer(e){this.assertOpen();let t=b.runSyncExit(G.buildWithScope(e,this.scope));if(D.isFailure(t))throw ne.squash(t.cause);return t.value}addFinalizer(e){this.assertOpen(),b.runSync(j.addFinalizer(this.scope,b.promise(async()=>{await e()})))}addSyncFinalizer(e){this.assertOpen(),b.runSync(j.addFinalizer(this.scope,b.sync(()=>{e()})))}async fork(e){if(this.closed)throw Error("Cannot start background work after shell shutdown");await b.runPromise(b.forkIn(e,this.scope))}close(e=D.void){if(this.closePromise)return this.closePromise;if(this.closed)return Promise.resolve();return this.closed=!0,this.closePromise=b.runPromise(j.close(this.scope,e)),this.closePromise}closeSync(e){if(this.closed)return;this.closed=!0,b.runSync(j.close(this.scope,e))}assertOpen(){if(this.closed)throw Error("Cannot register cleanup after shell shutdown")}}class an{config;services;lifecycle;bootloader;initialized=!1;lifecycleState="constructed";bootMode;bootPromise=null;shutdownPromise=null;analyticsRegistry;bootTime=Date.now();endpointRegistry=new Ei;interactionRegistry=new Ai;httpRouteRegistry=Yt.createFresh();httpServed;jobs;static createFresh(e,t,r){return new an(pt(e),t,r)}constructor(e,t,r){this.config=e,this.httpServed=e.http.enabled&&Ce(r?.processRole).serves,this.lifecycle=new sn,Sd(this,()=>this.httpRouteRegistry.getSnapshot());let i=t?.logger??Pe.getInstance(),n=Ot.createFresh(i,this.config,r?.processRole,r?.peerChannel);try{if(this.services=n.initializeServices(this.lifecycle,t),this.jobs=hc(this.services.batchJobManager,this.services.jobQueueService),this.analyticsRegistry=uc(this.services.entityRegistry),this.bootloader=new xi(this.config,this.services,this.lifecycle,n,r?.processRole,{registerCoreDataSources:()=>An(this.services,this.config),finalizeHttpRoutes:()=>{this.httpRouteRegistry.finalize(vc(this.services.pluginManager))},registerSystemCapabilities:()=>pd({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();Rc(this.lifecycle,this.services)}catch(o){try{this.lifecycle.closeSync(D.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)=>mt(this.services.entityService,e,t),appInfo:()=>this.getAppInfo(),identityInput:()=>{let e=this.getIdentity(),t=this.getProfile();return gd.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:hd(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 Te(this.services.messageBus,yd,{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(D.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"),kn(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 md.parse(await this.generateContent({prompt:e,templateName:Ze.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()}getPluginManager(){return this.services.pluginManager}getContentService(){return this.services.contentService}getCallerAuthorizer(){return this.services.callerAuthorizer}getRenderService(){return this.services.renderService}getAttachmentRegistry(){return Ir(this.services.attachmentRegistry)}getRuntimeUploadRegistry(){return vd(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(Q,Xa({config:this.config.http,domain:this.config.siteBaseUrl,logger:t.child(F),messageBus:r,getRoutes:()=>this.httpRouteRegistry.getSnapshot(),getPlugins:()=>[...i.getAllPlugins().values()].map(({plugin:s})=>s),getOperationalInfo:async()=>bd(fd(await this.getAppInfo())),getReadinessData:()=>this.getRuntimeReadiness()}),F),this.lifecycle.addSyncFinalizer(()=>e.abandon(Q));let{endpoints:n,interactions:o}=ec(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 vn({config:this.config,services:this.services,bootTime:this.bootTime,endpoints:()=>this.listEndpoints(),interactions:()=>this.listInteractions()})}getRuntimeReadiness(){return Rn(this.services)}}async function Dd(e,t){await le({label:"entity",config:e,schema:{assets:wd,entities:Rd,entityMutationReceipts:Id,projectionDirtyInputs:Pd,projectionWaves:Cd,projectionIncidents:xd,projectionWaveInputs:Td,projectionWaveRules:Ed,projectionRuleMemos:Ad},migrationsFolder:de(import.meta.url,"entity-service"),authTokenEnv:"DATABASE_AUTH_TOKEN",logger:t,afterMigrate:kd})}async function Od(e,t){await le({label:"job-queue",config:e,schema:{jobQueue:jd,jobWorkerSessions:zd},migrationsFolder:de(import.meta.url,"job-queue"),authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",logger:t})}async function Bd(e,t){await le({label:"conversation",config:e,schema:{conversations:Md,messages:Ld,summaryTracking:Ud},migrationsFolder:de(import.meta.url,"conversation-service"),authTokenEnv:"CONVERSATION_DATABASE_AUTH_TOKEN",logger:t})}async function $d(e,t){await le({label:"runtime-state",config:e,schema:{runtimeStateRecords:I},migrationsFolder:de(import.meta.url,"runtime-state"),authTokenEnv:"RUNTIME_STATE_DATABASE_AUTH_TOKEN",logger:t})}import{mkdir as ln}from"fs/promises";import{isAbsolute as nh}from"path";function _d(e=process.env){return{dataDir:e.XDG_DATA_HOME??"./data",cacheDir:e.XDG_CACHE_HOME??"./cache",distDir:"./dist"}}function Zd(e=process.env){let t=e.BRAIN_GIT_BROKER_CHECKOUT;if(!t)return;if(!nh(t))throw Error(`Git broker checkout path must be absolute: ${t}`);return t}function Fd(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 Nd(e=process.env){return pe(_d(e))}async function Hd(e=process.env){let t=_d(e);try{await ln(t.dataDir,{recursive:!0}),await ln(t.cacheDir,{recursive:!0}),await ln(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 pe(t)}class oh{logger;migrations;constructor(e,t){this.logger=e,this.migrations=t??{getStandardConfigWithDirectories:()=>Hd(),migrateEntities:Dd,migrateJobQueue:Od,migrateConversations:Bd,migrateRuntimeState:$d}}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 dn={kind:"service",serviceId:"brain-cli"},un=`${dn.kind}:${dn.serviceId}`;function Lk(e="admin"){return{interfaceType:"cli",actor:dn,userPermissionLevel:e}}var $k=c.enum(["eval"]),_k=c.enum(["person","team","organization"]),pn=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 qd=c.object({name:c.string().default("brain-app"),version:c.string().default("1.0.0"),database:c.string().optional(),aiProviderKeys:_e.optional(),aiModel:c.string().optional(),aiEmbeddingModel:c.string().optional(),aiModelRuntimeUrl:c.string().optional(),aiAnswerModel:c.string().optional(),aiVisionModel:c.string().optional(),aiImageModel:c.string().optional(),aiReasoningEffort:te.optional(),logLevel:Ie.optional(),logFile:c.string().optional(),profileKind:c.string().trim().min(1).optional(),plugins:c.array(ut).default([]),spaces:c.array(c.string()).default([]),identity:Wd.optional(),agentInstructions:c.array(c.string()).optional(),deployment:pn.prefault({}),http:$e.prefault({})});var sh="NODE_ENV";function ah(){return process.env[sh]}function mn(){return ah()==="production"}function Jd(){return!mn()}var ch="startup-check";function lh(){return Object.fromEntries(cn.map((e)=>[e,ch]))}function iD(e){let r={...qd.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 nD(e,t){let r={plugins:e.plugins??[],...e.shellConfig};return dh(r),uh(e,r),ph(e,r,t),mh(e,r),gh(e,r),fh(e,r),hh(e,r),yh(e,r),bh(e,r),vh(e,r),r}function dh(e){let t=Nd();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??=Fd(),e.gitBrokerCheckout??=Zd()}function uh(e,t){if(e.database)t.database={url:e.database};if(e.profileKind)t.profileKind=e.profileKind;t.features={}}function ph(e,t,r){let i=r?.mode==="startup-check";if(!e.aiProviderKeys&&!e.aiModel&&!e.aiEmbeddingModel&&!e.aiModelRuntimeUrl&&!e.aiAnswerModel&&!e.aiVisionModel&&!e.aiImageModel&&!e.aiReasoningEffort&&!i)return;t.ai={...t.ai,providerKeys:{...i&&lh(),...t.ai?.providerKeys,...e.aiProviderKeys},...e.aiModel&&{model:e.aiModel},...e.aiEmbeddingModel&&{embeddingModel:e.aiEmbeddingModel},...e.aiModelRuntimeUrl&&{modelRuntimeUrl:e.aiModelRuntimeUrl},...e.aiAnswerModel&&{answerModel:e.aiAnswerModel},...e.aiVisionModel&&{visionModel:e.aiVisionModel},...e.aiImageModel&&{imageModel:e.aiImageModel},...e.aiReasoningEffort&&{reasoningEffort:e.aiReasoningEffort}}}function mh(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 gh(e,t){let r=e.permissions?.rules??[];t.permissions={...e.permissions,rules:r.some((i)=>i.pattern===un)?r:[{pattern:un,level:"admin"},...r]}}function fh(e,t){if(e.spaces)t.spaces=e.spaces}function hh(e,t){if(e.identity)t.identity=e.identity}function yh(e,t){if(e.agentInstructions)t.agentInstructions=e.agentInstructions}function vh(e,t){t.http??={...W(e.http),port:e.deployment.ports.production}}function bh(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=Jd(),t.production=mn()}
102
102
  export{pe as R,$e as S,Ie as T,pt as U,z as V,Fu as W,Nu as X,Hu as Y,Ku as Z,Vn as _,Yu as $,Xu as aa,ep as ba,tp as ca,rp as da,ip as ea,np as fa,Vr as ga,ra as ha,ia,na as ja,bi as ka,Di as la,XP as ma,ul as na,ml as oa,rt as pa,hf as qa,Wi as ra,Ji as sa,vf as ta,wf as ua,If as va,fT as wa,Rl as xa,wl as ya,xf as za,Tf as Aa,Ef as Ba,Af as Ca,tn as Da,kf as Ea,Df as Fa,an as Ga,Dd as Ha,Od as Ia,Bd as Ja,$d as Ka,oh as La,Lk as Ma,_k as Na,iD as Oa,nD as Pa};
103
103
 
104
- //# debugId=78504057A4F406AA64756E2164756E21
105
- //# sourceMappingURL=index-362h9qny.js.map
104
+ //# debugId=B3D178AE39272B7964756E2164756E21
105
+ //# sourceMappingURL=index-vjz32ya5.js.map