@rizom/brain 0.2.0-alpha.750 → 0.2.0-alpha.752

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.
Files changed (27) hide show
  1. package/dist/brain.js +6 -6
  2. package/dist/chunks/app-033f61ma.js +5 -0
  3. package/dist/chunks/{index-g3c3c3y0.js → index-0pd4ssrx.js} +2 -2
  4. package/dist/chunks/{index-18gtvkxj.js → index-0x5jaf16.js} +2 -2
  5. package/dist/chunks/{index-q6pcp7gc.js → index-3j40xbgd.js} +3 -3
  6. package/dist/chunks/{index-q6pcp7gc.js.map → index-3j40xbgd.js.map} +3 -3
  7. package/dist/chunks/{index-dv5k8aft.js → index-fa0nn18g.js} +3 -3
  8. package/dist/chunks/{index-dv5k8aft.js.map → index-fa0nn18g.js.map} +1 -1
  9. package/dist/chunks/{index-ppg0xa7k.js → index-xqx1w0pm.js} +2 -2
  10. package/dist/chunks/{index-68ge01gj.js → index-y57zfnpa.js} +4 -4
  11. package/dist/chunks/{index-68ge01gj.js.map → index-y57zfnpa.js.map} +3 -3
  12. package/dist/chunks/{package-6203jv7y.js → package-rjd3grn1.js} +3 -3
  13. package/dist/chunks/{package-6203jv7y.js.map → package-rjd3grn1.js.map} +1 -1
  14. package/dist/entities.js +1 -1
  15. package/dist/index.js +1 -1
  16. package/dist/interfaces.js +1 -1
  17. package/dist/model.js +4 -4
  18. package/dist/model.js.map +1 -1
  19. package/dist/services.js +1 -1
  20. package/dist/testing.js +1 -1
  21. package/dist/ui/studio-chunks/main-5ndk80hz.js.map +1 -1
  22. package/package.json +1 -1
  23. package/dist/chunks/app-7e5m9g6k.js +0 -5
  24. /package/dist/chunks/{app-7e5m9g6k.js.map → app-033f61ma.js.map} +0 -0
  25. /package/dist/chunks/{index-g3c3c3y0.js.map → index-0pd4ssrx.js.map} +0 -0
  26. /package/dist/chunks/{index-18gtvkxj.js.map → index-0x5jaf16.js.map} +0 -0
  27. /package/dist/chunks/{index-ppg0xa7k.js.map → index-xqx1w0pm.js.map} +0 -0
@@ -1,6 +1,6 @@
1
1
  // @bun
2
- import{Tx as t}from"./index-7ne5672k.js";var g={name:"@rizom/brain",version:"0.2.0-alpha.750",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/conflict":"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":"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/refined-note":"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/webdav":"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{Tx as t}from"./index-7ne5672k.js";var g={name:"@rizom/brain",version:"0.2.0-alpha.752",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/conflict":"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":"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/refined-note":"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/webdav":"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 M,j as N,g as O};
4
4
 
5
- //# debugId=C787F2C37D59403F64756E2164756E21
6
- //# sourceMappingURL=index-dv5k8aft.js.map
5
+ //# debugId=97C253F965D774F064756E2164756E21
6
+ //# sourceMappingURL=index-fa0nn18g.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": ";olNAAA,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": "C787F2C37D59403F64756E2164756E21",
8
+ "debugId": "97C253F965D774F064756E2164756E21",
9
9
  "names": []
10
10
  }
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{a as j,b as T}from"./index-ckdf9ghv.js";import{d as g,e as m}from"./index-pjejyeqk.js";import"./index-e84v85w3.js";import{L as Z}from"./index-4mffgwx9.js";import"./index-x8e40qwv.js";import"./index-wpzfnffx.js";import{Bj as E,Nh as N,Oh as F,Si as H,Th as I,Uh as P,Vh as R,Wh as L,Xh as B,cj as w,dj as M,gj as D,nj as O}from"./index-q6pcp7gc.js";import{jm as A,nl as S}from"./index-9881eck9.js";import"./index-nwdvz1vw.js";import"./index-6gqg29bj.js";import{Tx as v}from"./index-7ne5672k.js";import"./index-amf6s7a5.js";import{ay as b}from"./index-p39p7p8h.js";var x=v.object({theme:v.object({primaryColor:v.string().describe("Primary color for the CLI theme").default("#0066cc"),accentColor:v.string().describe("Accent color for the CLI theme").default("#ff6600")}).describe("Theme configuration for the CLI interface").default({primaryColor:"#0066cc",accentColor:"#ff6600"})});var V={completed:"\u2713",declined:"\u25CB",failed:"\u2717"},q={deniedCardIds:void 0,resolveUrl:(r)=>r,isHiddenUrl:()=>!1,eventActionUnavailableLabel:void 0},y="cli",k={identity:{kind:"external",externalActorId:S("cli","operator")},interfaceType:"cli",role:"user"};function _(){return{inkApp:null,removeSignalHandlers:void 0,responseCallback:void 0,systemMessageCallback:void 0}}function z(r,e){let{logger:t}=r,o=new D({loadMessages:async(i)=>r.conversations.getMessages(i,{limit:50}),onRestoreError:(i,s)=>{t.debug("Failed to restore pending CLI approvals",{error:i,conversationId:s})}}),n=(i)=>{e.responseCallback?.(i)},a=()=>r.permissions.isAnchor("cli","local"),u=async(i,s)=>{let l=new Set(s);if(!M(i,l))return!1;let c=w({message:Y(i,s),approvalIds:l});if(c.kind==="not-confirmation")return!1;if(c.kind==="notice")return n(`_${c.message}_`),!0;o.removeApproval(y,c.approvalId);let C=await r.agent.confirmPendingAction(y,c.confirmed,c.approvalId,{userPermissionLevel:"admin",isAnchor:a(),interfaceType:"cli",actor:k});return o.syncFromResponse(y,C,c.approvalId),n(K(C.text,C.cards)),!0};return{async processInput(i){r.messages.startProcessingInput();try{let s=[...await o.getApprovalIds(y)];if(s.length>0){if(await u(i,s))return}let l=await r.agent.chat(i,y,{userPermissionLevel:"admin",isAnchor:a(),interfaceType:"cli",channelId:"cli",channelName:"CLI Terminal",actor:k}),c=P(l.cards),C=c.length>0?c.map((p)=>p.id):l.pendingConfirmations?.map((p)=>p.id)??[];o.replaceApprovals(y,C);let h=G(l);t.debug("Agent response received",{textLength:l.text.length,toolResultsCount:l.toolResults?.length??0,toolResults:l.toolResults?.map((p)=>({toolName:p.toolName,hasData:p.data!==void 0}))}),n(h)}catch(s){t.error("Error processing input",{error:s,input:i});let l=A(s,"An unknown error occurred");n(`**Error:** ${l}`)}finally{r.messages.endProcessingInput()}}}}function G(r){let e=O(r,{deniedCardIds:void 0}),t=[],o=[],n="";for(let a of e.directives)switch(a.kind){case"text":n=a.text;break;case"approvals":t.push(...a.cards);break;default:if(a.card.kind==="tool-approval"&&a.card.state==="approval-requested"){t.push(a.card);break}o.push(E(a.card,q))}return[J(n,t),...o].filter((a)=>a.trim().length>0).join(`
2
+ import{a as j,b as T}from"./index-ckdf9ghv.js";import{d as g,e as m}from"./index-pjejyeqk.js";import"./index-e84v85w3.js";import{L as Z}from"./index-4mffgwx9.js";import"./index-x8e40qwv.js";import"./index-wpzfnffx.js";import{Bj as E,Nh as N,Oh as F,Si as H,Th as I,Uh as P,Vh as R,Wh as L,Xh as B,cj as w,dj as M,gj as D,nj as O}from"./index-3j40xbgd.js";import{jm as A,nl as S}from"./index-9881eck9.js";import"./index-nwdvz1vw.js";import"./index-6gqg29bj.js";import{Tx as v}from"./index-7ne5672k.js";import"./index-amf6s7a5.js";import{ay as b}from"./index-p39p7p8h.js";var x=v.object({theme:v.object({primaryColor:v.string().describe("Primary color for the CLI theme").default("#0066cc"),accentColor:v.string().describe("Accent color for the CLI theme").default("#ff6600")}).describe("Theme configuration for the CLI interface").default({primaryColor:"#0066cc",accentColor:"#ff6600"})});var V={completed:"\u2713",declined:"\u25CB",failed:"\u2717"},q={deniedCardIds:void 0,resolveUrl:(r)=>r,isHiddenUrl:()=>!1,eventActionUnavailableLabel:void 0},y="cli",k={identity:{kind:"external",externalActorId:S("cli","operator")},interfaceType:"cli",role:"user"};function _(){return{inkApp:null,removeSignalHandlers:void 0,responseCallback:void 0,systemMessageCallback:void 0}}function z(r,e){let{logger:t}=r,o=new D({loadMessages:async(i)=>r.conversations.getMessages(i,{limit:50}),onRestoreError:(i,s)=>{t.debug("Failed to restore pending CLI approvals",{error:i,conversationId:s})}}),n=(i)=>{e.responseCallback?.(i)},a=()=>r.permissions.isAnchor("cli","local"),u=async(i,s)=>{let l=new Set(s);if(!M(i,l))return!1;let c=w({message:Y(i,s),approvalIds:l});if(c.kind==="not-confirmation")return!1;if(c.kind==="notice")return n(`_${c.message}_`),!0;o.removeApproval(y,c.approvalId);let C=await r.agent.confirmPendingAction(y,c.confirmed,c.approvalId,{userPermissionLevel:"admin",isAnchor:a(),interfaceType:"cli",actor:k});return o.syncFromResponse(y,C,c.approvalId),n(K(C.text,C.cards)),!0};return{async processInput(i){r.messages.startProcessingInput();try{let s=[...await o.getApprovalIds(y)];if(s.length>0){if(await u(i,s))return}let l=await r.agent.chat(i,y,{userPermissionLevel:"admin",isAnchor:a(),interfaceType:"cli",channelId:"cli",channelName:"CLI Terminal",actor:k}),c=P(l.cards),C=c.length>0?c.map((p)=>p.id):l.pendingConfirmations?.map((p)=>p.id)??[];o.replaceApprovals(y,C);let h=G(l);t.debug("Agent response received",{textLength:l.text.length,toolResultsCount:l.toolResults?.length??0,toolResults:l.toolResults?.map((p)=>({toolName:p.toolName,hasData:p.data!==void 0}))}),n(h)}catch(s){t.error("Error processing input",{error:s,input:i});let l=A(s,"An unknown error occurred");n(`**Error:** ${l}`)}finally{r.messages.endProcessingInput()}}}}function G(r){let e=O(r,{deniedCardIds:void 0}),t=[],o=[],n="";for(let a of e.directives)switch(a.kind){case"text":n=a.text;break;case"approvals":t.push(...a.cards);break;default:if(a.card.kind==="tool-approval"&&a.card.state==="approval-requested"){t.push(a.card);break}o.push(E(a.card,q))}return[J(n,t),...o].filter((a)=>a.trim().length>0).join(`
3
3
 
4
4
  `)}function J(r,e){if(e.length===0)return r;let t=L(r,e);if(e.length===1){let n=e[0];if(!n)return r;let a=n.preview?`
5
5
 
@@ -16,4 +16,4 @@ _Please reply with **yes 1** / **no 1** for the matching action._`}function K(r,
16
16
  ${o.error}`:`${n} ${o.summary}`}function Y(r,e){let t=/^(.*?)\s+#?(\d+)$/.exec(r.trim());if(!t?.[1]||!t[2])return r;let o=e[Number(t[2])-1];return o?`${t[1]} ${o}`:r}var Q=H({id:"cli",config:x,setup:(r)=>(I(r).logger.debug("CLI interface registered with AgentService"),_())}),W=N(Q,(r)=>{let{state:e}=r,t=I(r),{logger:o,messages:n}=t,a=z(t,e),u=()=>{e.responseCallback=void 0,e.systemMessageCallback=void 0},i=()=>{if(n.unregisterProgressCallback(),u(),e.removeSignalHandlers?.(),e.removeSignalHandlers=void 0,e.inkApp)e.inkApp.unmount(),e.inkApp=null};return{id:"cli",start:async()=>{o.debug("Starting CLI interface");try{let[s,l,c]=await Promise.all([import("./index-9s1yc539.js"),import("react"),import("./EnhancedApp-85bb86z6.js")]),h=l.default.createElement(c.default,{interface:a,registerProgressCallback:(p)=>{n.registerProgressCallback(p)},unregisterProgressCallback:()=>{n.unregisterProgressCallback()},registerResponseCallback:(p)=>{e.responseCallback=p},registerSystemMessageCallback:(p)=>{e.systemMessageCallback=p},unregisterMessageCallbacks:u});e.inkApp=s.render(h),e.removeSignalHandlers=Z(["SIGINT","SIGTERM"],()=>{o.debug("Received termination signal, stopping CLI"),i()})}catch(s){throw o.error("Failed to start CLI interface",{error:s}),s}},stop:async()=>{o.debug("Stopping CLI interface"),i()},healthCheck:async()=>{let s=e.inkApp!==null;return{status:s?"healthy":"error",message:s?"CLI interface is running":"CLI interface not running",lastCheck:new Date,details:{hasInkApp:e.inkApp!==null,hasCallbacks:n.hasProgressCallback()}}}}}),X=F(W,({state:r})=>({send:({message:e})=>{let t=typeof e==="string"?e:e.fallbackText??"";if(!t)return;(r.systemMessageCallback??r.responseCallback)?.(t)}})),ee=X;import{jsx as d,jsxs as f}from"react/jsx-runtime";function re({batchStatus:r,showDetails:e=!0}){let{batchId:t,totalOperations:o,completedOperations:n,failedOperations:a,currentOperation:u,errors:i,status:s}=r,l=s==="processing",c=s==="completed",C=s==="failed",h=n-a;return f(g,{flexDirection:"column",marginY:1,children:[d(g,{marginBottom:1,children:f(m,{bold:!0,color:"cyan",children:["Batch Operation: ",t.slice(0,8),"..."]})}),d(g,{marginBottom:1,children:d(T,{current:n,total:o,message:"Overall Progress:",color:C?"red":c?"green":"yellow"})}),l&&u&&f(g,{marginBottom:1,children:[d(m,{color:"green",children:d(j,{type:"dots"})}),f(m,{color:"gray",children:[" ",u]})]}),e&&f(g,{flexDirection:"column",marginLeft:2,children:[h>0&&f(g,{children:[d(m,{color:"green",children:"\u2713 "}),f(m,{color:"gray",children:[h," successful"]})]}),a>0&&f(g,{children:[d(m,{color:"red",children:"\u2717 "}),f(m,{color:"gray",children:[a," failed"]})]}),i.length>0&&f(g,{flexDirection:"column",marginTop:1,children:[d(m,{color:"red",bold:!0,children:"Errors:"}),i.slice(0,3).map((p,U)=>f(g,{marginLeft:2,children:[d(m,{color:"red",children:"\u2022 "}),d(m,{color:"gray",children:p})]},U)),i.length>3&&d(g,{marginLeft:2,children:f(m,{color:"gray",children:["... and ",i.length-3," more"]})})]})]}),c&&d(g,{marginTop:1,children:d(m,{color:"green",bold:!0,children:"\u2713 Batch completed successfully"})}),C&&d(g,{marginTop:1,children:d(m,{color:"red",bold:!0,children:"\u2717 Batch failed"})})]})}export{re as BatchProgress,T as ProgressBar,x as cliConfigSchema,ee as default};
17
17
 
18
18
  //# debugId=C81A70DDFACF001064756E2164756E21
19
- //# sourceMappingURL=index-ppg0xa7k.js.map
19
+ //# sourceMappingURL=index-xqx1w0pm.js.map
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Qa as Ls,Ra as Us}from"./index-wpzfnffx.js";import{$a as mt,$b as Bl,$d as _,Ad as _s,Af as Qd,Bd as al,Bf as Kd,Bg as cc,Cb as Ro,Cf as Vd,Cg as jd,Ci as zo,Db as Eo,Dd as $l,De as so,Dg as No,Di as Ho,Ed as fs,Ee as vs,Ei as Wo,Fb as ue,Fe as kn,Fi as qo,Gb as pe,Gc as Ed,Gd as ee,Ge as bs,Gg as xr,Gi as Jo,Hb as Ld,Hc as Ys,Hd as Hi,Hf as or,Hg as Ps,Ib as Ud,Ic as ho,Ie as Vs,If as Qc,Ig as Te,Jb as Bd,Je as Xr,Jf as co,Kb as $d,Kf as ou,Kg as Dd,Lb as _d,Lc as pd,Lg as Cs,Mb as Fd,Mc as uo,Me as qd,Mg as bc,Nb as Nd,Ne as Jd,Ng as Ga,Ob as Zd,Oe as Xo,Og as xi,Oi as Go,Oj as Fs,Pb as Hd,Pe as es,Pj as Qo,Qb as mo,Qe as ts,Rb as fo,Sb as go,Se as rs,Sj as Ns,Te as wd,Tj as Ko,Ub as Lt,Ue as Id,Uj as zs,Vb as ps,Vc as ms,Ve as xd,Vi as hc,Vj as Vo,Wa as Al,Wb as Rt,Wd as Gc,We as Pd,Wi as yc,Xa as lt,Xb as Qe,Xe as Ad,Xf as jn,Xi as ft,Yb as Ee,Ye as Vl,Yf as ht,Zb as yd,Zf as oc,Zi as Od,_a as nn,_b as Pc,_f as kd,_i as Os,ab as ve,ae as Xs,ak as Zs,bb as xo,bc as A,bi as We,bk as zd,cb as M,cc as fr,cg as Ni,ci as un,dc as ei,dg as tl,dk as Ms,eb as se,ec as yl,eg as rl,ei as Cn,ek as uc,fc as $o,fg as Ss,fi as ge,fk as er,gb as Po,gc as _o,gg as Rs,gi as Tn,hc as Fo,hg as ws,hi as En,ii as Or,jc as Br,ji as Es,kc as $r,ki as An,ob as Co,qc as gr,sd as br,tb as Jr,ub as Ct,ug as Is,ui as As,vb as vo,vi as ks,wb as bo,wd as Ol,wg as xs,wi as Lc,xg as Ke,xi as js,yb as So,yd as $s,ye as Ya,yg as sc,yi as Zo,zb as Md,ze as bt,zg as ac,zi as Ds}from"./index-q6pcp7gc.js";import{Dm as he,Fm as jt,Km as Ks,Lm as Yt,Ln as qa,Ml as Uo,Nn as Ja,Tl as Bo,Um as ic,Un as re,Vn as V,Wl as no,Xm as Kt,ao as gs,go as hs,hm as Ie,ho as ys,io as Sd,jl as G,jm as P,km as Ge,nk as Cl,nl as Qa,nn as hd,ok as Tl,ol as F,on as Td,oo as Ts,pk as ie,qo as Ha,rk as $e,rm as oo,sk as Le,sn as ss,tk as Ue,to as de,uk as mr,vk as dt,xo as Y}from"./index-9881eck9.js";import{Ao as Pe,yo as Ye}from"./index-nwdvz1vw.js";import{Bq as C,Bw as lc,Fs as oe,Hs as us,Ts as j,fw as w,gt as D,ot as Q,vw as ne,xw as Xt,yw as nc}from"./index-6gqg29bj.js";import{Tx as c}from"./index-7ne5672k.js";function jr(e,t){let r=new Set(t.map((i)=>i.type));return e.byType.filter((i)=>(i.status==="pending"||i.status==="processing")&&!r.has(i.type))}function Ze(e,t){let r=e.workerSessions,i=r.active===0?"missing":r.stale>0?"stale":"active",n=e.duePending>0&&(e.oldestDuePendingAgeMs??0)>=120000&&e.totals.processing===0&&(e.latestClaimAgeMs===null||e.latestClaimAgeMs>=120000),o=[];if(i==="missing")o.push("No live worker session");else if(i==="stale")o.push(`${r.stale} stale worker session(s)`);if(n)o.push(`${e.duePending} due job(s) have remained unclaimed for at least 120000ms`);if(t){let s=jr(e,t).reduce((a,l)=>a+l.count,0);if(s>0)o.push(`${s} active job(s) have no declared executor`)}return{status:o.length===0?"operational":"degraded",reasons:o,worker:{state:i,activeSessions:r.active,staleSessions:r.stale,latestHeartbeatAgeMs:r.latestHeartbeatAgeMs},queue:{duePending:e.duePending,processing:e.totals.processing,oldestDuePendingAgeMs:e.oldestDuePendingAgeMs,latestClaimAgeMs:e.latestClaimAgeMs,stalled:n}}}async function Rn(e){let{config:t,services:r,bootTime:i,endpoints:n,interactions:o}=e,[s,a,l,d]=await Promise.all([r.entityService.getEntityCounts(mt("runtime app info reports operator-facing aggregate status")),r.entityService.countEmbeddings(),r.daemonRegistry.getStatuses(),r.jobQueueService.getDiagnostics()]),u=s.reduce((p,m)=>p+m.count,0);return{model:t.name||"brain-app",version:t.version||"1.0.0",uptime:Math.floor((Date.now()-i)/1000),entities:u,entityCounts:s,embeddings:a,backgroundWork:Ze(d,r.jobQueueService.getExecutionRegistrations()),ai:{model:t.ai.model,embeddingModel:r.embeddingService.identity.model},daemons:l,endpoints:n(),interactions:o()}}import{readdir as wn,readFile as Pu}from"fs/promises";var Cu=10;async function Tu(e="/proc"){let t=null;try{t=(await wn(`${e}/self/fd`)).length}catch{}try{let i=(await wn(e,{withFileTypes:!0})).filter((s)=>s.isDirectory()&&/^\d+$/.test(s.name)).map((s)=>s.name),n=0,o=0;return await Promise.all(i.map(async(s)=>{try{let a=await Pu(`${e}/${s}/status`,"utf8");if(o++,/^State:\s+Z\b/m.test(a))n++}catch{}})),{fileDescriptors:t,processCount:o,zombieCount:n}}catch{return{fileDescriptors:t,processCount:null,zombieCount:null}}}function In(e,t,r){return t.status==="fulfilled"?{name:e,status:"healthy",message:r}:{name:e,status:"unhealthy",message:P(t.reason)}}function Eu(e){if(!e)return{name:"job-worker",status:"degraded",message:"Worker session state is unavailable"};let t=e.workerSessions,r=Ze(e).worker;if(r.state==="missing")return{name:"job-worker",status:"degraded",message:"No live worker session",details:{sessions:t}};if(r.state==="stale")return{name:"job-worker",status:"degraded",message:`${t.stale} stale worker session(s)`,details:{sessions:t}};return{name:"job-worker",status:"healthy",message:`${t.active} live worker session(s)`,details:{sessions:t}}}function Au(e){if(!e)return{name:"job-queue-progress",status:"degraded",message:"Queue progress state is unavailable"};let t=Ze(e).queue;return t.stalled?{name:"job-queue-progress",status:"degraded",message:`${t.duePending} due job(s) are not being claimed`,details:{queue:t}}:{name:"job-queue-progress",status:"healthy",message:"Due jobs are being claimed",details:{queue:t}}}function ku(e,t){if(!e||!t)return{name:"job-execution-inventory",status:"degraded",message:"Job execution inventory is unavailable"};let r=jr(e,t),i=r.reduce((n,o)=>n+o.count,0);return i===0?{name:"job-execution-inventory",status:"healthy",message:"Every active job type has a declared executor"}:{name:"job-execution-inventory",status:"degraded",message:`${i} active job(s) have no declared executor`,details:{jobs:r}}}function ju(e){if(!e)return{name:"attempt-leases",status:"degraded",message:"Lease state is unavailable"};return e.staleLeaseCount===0?{name:"attempt-leases",status:"healthy",message:"No stale processing leases"}:{name:"attempt-leases",status:"degraded",message:`${e.staleLeaseCount} processing lease(s) are stale`,details:{staleLeaseCount:e.staleLeaseCount}}}function Du(e){if(!e.initialized)return{name:"projection-circuits",status:"degraded",message:"Projection runtime supervisor is not initialized"};if(e.openCircuits.length===0)return{name:"projection-circuits",status:"healthy",message:"No projection circuits are open"};return{name:"projection-circuits",status:"degraded",message:`${e.openCircuits.length} projection circuit(s) open`,details:{circuits:e.openCircuits}}}async function Ou(e){let t=e.entityService.getProjectionStore(),[r,i,n]=await Promise.all([t.getActiveWave(),t.getUnresolvedProjectionIncidentDiagnostics(Cu),t.getProjectionBatchDiagnostics?.()??Promise.resolve({preparing:0,open:0,abandoned:0,expiredCallbackLeases:0,oldestActiveAgeMs:null,oldestProgressAgeMs:null})]);if(!r)return{waveId:null,batches:n,strandedRules:[],incidentCount:i.total,incidents:i.incidents};let s=(await t.listWaveRules(r.id)).filter((l)=>l.status==="queued"||l.status==="failed"),a=(await Promise.all(s.map(async(l)=>{let d=l.jobId?await e.jobQueueService.getStatus(l.jobId):null;if(l.status!=="failed"&&d&&(d.status==="pending"||d.status==="processing"))return null;return{ruleId:l.ruleId,jobId:l.jobId,jobStatus:d?.status??"missing"}}))).filter((l)=>l!==null);return{waveId:r.id,batches:n,strandedRules:a,incidentCount:i.total,incidents:i.incidents}}function zu(e){if(e.batches.abandoned>0)return{name:"projection-waves",status:"degraded",message:`${e.batches.abandoned} projection batch(es) await recovery`,details:{batches:e.batches}};if(e.batches.expiredCallbackLeases>0)return{name:"projection-waves",status:"degraded",message:"A callback projection batch lease has expired",details:{batches:e.batches}};if(e.incidentCount>0)return{name:"projection-waves",status:"degraded",message:`${e.incidentCount} unresolved terminal projection incident(s)`,details:{incidentCount:e.incidentCount,incidentsTruncated:e.incidentCount>e.incidents.length,incidents:e.incidents.map((t)=>({waveId:t.waveId,ruleId:t.ruleId,jobId:t.jobId,failureReason:t.failureReason,createdAt:t.createdAt}))}};if(!e.waveId)return{name:"projection-waves",status:"healthy",message:e.batches.open+e.batches.preparing>0?`${e.batches.open+e.batches.preparing} projection batch(es) active`:"No active projection wave",...e.batches.open+e.batches.preparing>0&&{details:{batches:e.batches}}};if(e.strandedRules.length===0)return{name:"projection-waves",status:"healthy",message:`Projection wave ${e.waveId} is progressing`};return{name:"projection-waves",status:"degraded",message:`Projection wave ${e.waveId} has ${e.strandedRules.length} stranded rule job(s)`,details:{waveId:e.waveId,strandedRules:e.strandedRules}}}function Mu(e){let t=e.filter((r)=>r.status!=="running"||r.health?.status==="error");return t.length===0?{name:"daemons",status:"healthy",message:`${e.length} daemon(s) healthy`}:{name:"daemons",status:"degraded",message:`${t.length} daemon(s) unhealthy`,details:{daemons:t.map((r)=>({name:r.name,status:r.status,health:r.health?.status,message:r.health?.message}))}}}async function xn(e){let t=e.now?.()??Date.now(),r=(e.memoryUsage??process.memoryUsage)(),[i,n,o,s,a,l,d,u]=await Promise.allSettled([e.entityService.getEntityCounts(mt("runtime readiness database probe")),e.jobQueueService.getDiagnostics(t),Promise.resolve(e.jobQueueService.getExecutionRegistrations()),e.daemonRegistry.getStatuses(),(e.readProcessSignals??Tu)(),e.projectionRuntimeSupervisor.getDiagnostics(),Ou(e),e.operationalHealthRegistry.getChecks()]),p=n.status==="fulfilled"?n.value:null,m=o.status==="fulfilled"?o.value??null:null,f=s.status==="fulfilled"?s.value:[],g=a.status==="fulfilled"?a.value:{fileDescriptors:null,processCount:null,zombieCount:null},h=l.status==="fulfilled"?l.value:{status:"unhealthy",initialized:!1,trackedRoots:0,openCircuits:[]},v=[In("entity-database",i,"Entity database is accessible"),In("job-queue-database",n,"Job queue database is accessible"),Eu(p),Au(p),ku(p,m),ju(p),l.status==="fulfilled"?Du(h):{name:"projection-circuits",status:"degraded",message:P(l.reason)},d.status==="fulfilled"?zu(d.value):{name:"projection-waves",status:"degraded",message:P(d.reason)},s.status==="fulfilled"?Mu(f):{name:"daemons",status:"degraded",message:P(s.reason)}],y=u.status==="fulfilled"?u.value:[{name:"plugin-operational-health",status:"degraded",message:"Plugin operational health is unavailable"}],S=[...v,...y];return{status:v.some((b)=>b.status==="unhealthy")?"not_ready":"ready",operationalStatus:S.some((b)=>b.status!=="healthy")?"degraded":"operational",checkedAt:new Date(t).toISOString(),checks:S,resources:{memory:{rssBytes:r.rss,heapUsedBytes:r.heapUsed,heapTotalBytes:r.heapTotal},fileDescriptors:g.fileDescriptors,processes:{total:g.processCount,zombies:g.zombieCount},queue:p,projection:{initialized:h.initialized,trackedRoots:h.trackedRoots,openCircuits:h.openCircuits},worker:p?.workerSessions??{total:0,active:0,stale:0,latestHeartbeatAgeMs:null}}}}function Pn(){return{dataDir:"./data",cacheDir:"./cache",distDir:"./dist"}}function fe(e){return{database:{url:`file:${e.dataDir}/brain.db`},jobQueueDatabase:{url:`file:${e.dataDir}/brain-jobs.db`},conversationDatabase:{url:`file:${e.dataDir}/conversations.db`},runtimeStateDatabase:{url:`file:${e.dataDir}/runtime-state.db`},embeddingDatabase:{url:`file:${e.dataDir}/embeddings.db`},embedding:{enabled:!0}}}var He=c.strictObject({enabled:c.boolean().optional().describe("Serve HTTP; defaults to whether the selected bundles host the web surface"),preview:c.boolean().optional().describe("Serve the preview site; defaults to whether a site builder runs"),hostname:c.string().trim().min(1).optional().describe("Bind address; use 127.0.0.1 for isolated local tests"),productionDistDir:c.string().min(1).optional().describe("Directory of the production site, when no site builder writes it"),previewDistDir:c.string().min(1).optional().describe("Directory of the preview site, when no site builder writes it"),sharedImagesDir:c.string().min(1).optional().describe("Directory of shared optimized images")}),Dr=He.extend({enabled:c.boolean().default(!1),preview:c.boolean().default(!0),port:c.number().default(8080).describe("Port of the production listener")});var zr=Pn(),Lu=c.looseObject({label:c.string().min(1),pluralName:c.string().optional(),layout:c.string().optional(),paginate:c.boolean().optional(),pageSize:c.number().optional(),navigation:c.object({show:c.boolean().optional(),slot:c.enum(["primary","secondary"]).optional(),priority:c.number().optional()}).optional()});function Mr(){return fe(zr)}var xe=c.enum(["debug","info","warn","error"]);var Lr=c.object({name:c.string().default("brain-app"),version:c.string().default("1.0.0"),database:Ie,jobQueueDatabase:Ie,jobQueue:c.object({workerConcurrency:c.number().int().min(1).max(32).default(4)}).prefault({}),conversationDatabase:Ie,runtimeStateDatabase:Ie,embeddingDatabase:Ie,ai:c.object({providerKeys:We.default({}),model:c.string().refine(Cn,{error:(e)=>`Unsupported model "${String(e.input)}"`}),embeddingModel:c.string().refine((e)=>Or(e)!==void 0,{error:(e)=>An(String(e.input))}).default(En),modelRuntimeUrl:c.string().url().optional(),answerModel:c.string().optional(),visionModel:c.string().optional(),imageModel:c.string().optional(),temperature:c.number().min(0).max(2).default(0.7),webSearch:c.boolean().default(!0),reasoningEffort:re.optional()}).superRefine((e,t)=>{if(e.answerModel&&ge(e.answerModel)!=="local")t.addIssue({code:"custom",path:["answerModel"],message:`answerModel must be a local: model, not ${e.answerModel}`});if(e.visionModel&&ge(e.visionModel)!=="local")t.addIssue({code:"custom",path:["visionModel"],message:`visionModel must be a local: model, not ${e.visionModel}`});if(e.modelRuntimeUrl)return;let r=[...ge(e.model)==="local"?[e.model]:[],...[e.answerModel,e.visionModel].filter((i)=>i!==void 0&&ge(i)==="local"),...e.imageModel&&Tn(e.imageModel).provider==="local"?[e.imageModel]:[],...Or(e.embeddingModel)?.provider==="local"?[e.embeddingModel]:[]];for(let i of r)t.addIssue({code:"custom",path:["modelRuntimeUrl"],message:`${i} needs modelRuntime.url`})}),embedding:c.object({enabled:c.boolean().default(!0)}),logging:c.object({level:xe.default("info"),format:c.enum(["text","json"]).default("text"),file:c.string().optional(),context:c.string().default("shell")}).prefault({level:"info",context:"shell"}),features:c.object({}).default({}),plugins:c.array(ft).default([]),dataDir:c.string().default("./brain-data"),gitBrokerSocket:c.string().min(1).optional(),gitBrokerCheckout:c.string().min(1).optional(),spaces:c.array(c.string()).default([]),siteBaseUrl:c.string().optional(),localSiteUrl:c.string().optional(),preferLocalUrls:c.boolean().default(!1),production:c.boolean().default(!1),themeCSS:c.string().default(""),entityDisplay:c.record(c.string(),Lu).optional(),profileKind:c.string().trim().min(1).optional(),http:Dr.prefault({})});function gt(e={}){let{plugins:t=[],permissions:r={},identity:i,profile:n,agentInstructions:o,evalHandlerRegistry:s,ai:a,logging:l,embedding:d,jobQueue:u,...p}=e,{entityDisplay:m,...f}=Lr.parse({...Mr(),...F(p),ai:F({...a}),logging:F({...l}),embedding:F({...d}),jobQueue:F({...u}),plugins:[]});return{...f,plugins:t,permissions:r,...F({entityDisplay:m,identity:i,profile:n,agentInstructions:o,evalHandlerRegistry:s})}}var L={NOTE:"note",BRAIN_CHARACTER:"brain-character",ANCHOR_PROFILE:"anchor-profile"},qe={KNOWLEDGE_QUERY:"shell:knowledge-query",BASE_ENTITY_DISPLAY:"shell:base-entity-display",CONTENT_GENERATION:"shell:content-generation"},Ur={ENTITIES:"shell:entities"};var Uu=kn.extend({templateName:c.string()}),Bu=c.object({slug:c.string()}),$u="The style guide governs voice, tone, wording and form: paragraphing, sentence rhythm, hooks, rhetorical questions and calls to action. The instructions below and any additional instructions in the request govern the task, required content, length limits, platform constraints and output format. When either conflicts with the style guide on voice or form, follow the style guide.",_u="Generate the content described in your instructions.";function Fu(e){return e instanceof c.ZodType}function Nu(e){if(!e)return;return e.replace(/^https?:\/\//,"").replace(/\/$/,"")}class yt{aiService;entityService;templateRegistry;getIdentityContent;getProfileContent;entityUrls;id="ai-content";name="AI Content Generator";description="Generates content using AI based on templates and prompts";constructor(e,t,r,i,n,o,s){this.aiService=e,this.entityService=t,this.templateRegistry=r,this.getIdentityContent=i,this.getProfileContent=n,this.entityUrls=o,this.siteBaseUrl=Nu(s)}siteBaseUrl;async generate(e,t,r){return this.generateWithContext(e,t,r)}async generateScoped(e,t,r){return this.generateWithContext(e,t,r.signal,r)}async generateWithContext(e,t,r,i){r?.throwIfAborted();let n=Uu.parse(e),o=this.templateRegistry.get(n.templateName);if(!o)throw Error(`Template not found: ${n.templateName}`);if(!o.basePrompt)throw Error(`Template ${n.templateName} must have basePrompt for content generation`);let s=i?await jn((v,y)=>i.getEntity(v,y),n.templateName,o.basePrompt):await ht(this.entityService,n.templateName,o.basePrompt);r?.throwIfAborted();let a=[s,n.prompt].filter(Boolean).join(" "),l=a.length>0&&o.useKnowledgeContext===!0,d=this.entityService.getWeightMap(),u=Object.keys(d).length>0,p=l?i?await i.search(a,{limit:5,...u&&{weight:d}}):await this.entityService.search({query:a,options:{limit:5,...u&&{weight:d},...r&&{signal:r}}}):[];r?.throwIfAborted();let m=this.buildPrompt(n,p),f=i?await this.readIdentities(i,n.representedIdentity):void 0,g=this.buildSystemPrompt(s,n,f);if(!Fu(o.schema))throw Error(`Template ${o.name} cannot be used for AI generation: schema is not an AI generation schema`);r?.throwIfAborted();let h=await this.aiService.generateObject(g,m,o.schema,r);return r?.throwIfAborted(),t.parse(h.object)}async readIdentities(e,t){let r=async(o)=>(await e.getEntity(o,o))?.content??"",[i,n]=await Promise.all([t!=="none"?r(L.BRAIN_CHARACTER):"",t===void 0||t==="anchor"?r(L.ANCHOR_PROFILE):""]);return{brain:i,anchor:n}}buildSystemPrompt(e,t,r){let i=[];if(t.representedIdentity===void 0||t.representedIdentity==="brain"||t.representedIdentity==="anchor")i.push("# Brain Identity",r?.brain??this.getIdentityContent(),"");if(t.representedIdentity===void 0||t.representedIdentity==="anchor")i.push("# Represented Anchor",r?.anchor??this.getProfileContent(),"");let n=this.selectStyleGuidance(t);if(n)i.push("# Style Guide",n,"","# Precedence",$u,"");return i.push("# Instructions",e),i.join(`
2
+ import{Qa as Ls,Ra as Us}from"./index-wpzfnffx.js";import{$a as mt,$b as Bl,$d as _,Ad as _s,Af as Qd,Bd as al,Bf as Kd,Bg as cc,Cb as Ro,Cf as Vd,Cg as jd,Ci as zo,Db as Eo,Dd as $l,De as so,Dg as No,Di as Ho,Ed as fs,Ee as vs,Ei as Wo,Fb as ue,Fe as kn,Fi as qo,Gb as pe,Gc as Ed,Gd as ee,Ge as bs,Gg as xr,Gi as Jo,Hb as Ld,Hc as Ys,Hd as Hi,Hf as or,Hg as Ps,Ib as Ud,Ic as ho,Ie as Vs,If as Qc,Ig as Te,Jb as Bd,Je as Xr,Jf as co,Kb as $d,Kf as ou,Kg as Dd,Lb as _d,Lc as pd,Lg as Cs,Mb as Fd,Mc as uo,Me as qd,Mg as bc,Nb as Nd,Ne as Jd,Ng as Ga,Ob as Zd,Oe as Xo,Og as xi,Oi as Go,Oj as Fs,Pb as Hd,Pe as es,Pj as Qo,Qb as mo,Qe as ts,Rb as fo,Sb as go,Se as rs,Sj as Ns,Te as wd,Tj as Ko,Ub as Lt,Ue as Id,Uj as zs,Vb as ps,Vc as ms,Ve as xd,Vi as hc,Vj as Vo,Wa as Al,Wb as Rt,Wd as Gc,We as Pd,Wi as yc,Xa as lt,Xb as Qe,Xe as Ad,Xf as jn,Xi as ft,Yb as Ee,Ye as Vl,Yf as ht,Zb as yd,Zf as oc,Zi as Od,_a as nn,_b as Pc,_f as kd,_i as Os,ab as ve,ae as Xs,ak as Zs,bb as xo,bc as A,bi as We,bk as zd,cb as M,cc as fr,cg as Ni,ci as un,dc as ei,dg as tl,dk as Ms,eb as se,ec as yl,eg as rl,ei as Cn,ek as uc,fc as $o,fg as Ss,fi as ge,fk as er,gb as Po,gc as _o,gg as Rs,gi as Tn,hc as Fo,hg as ws,hi as En,ii as Or,jc as Br,ji as Es,kc as $r,ki as An,ob as Co,qc as gr,sd as br,tb as Jr,ub as Ct,ug as Is,ui as As,vb as vo,vi as ks,wb as bo,wd as Ol,wg as xs,wi as Lc,xg as Ke,xi as js,yb as So,yd as $s,ye as Ya,yg as sc,yi as Zo,zb as Md,ze as bt,zg as ac,zi as Ds}from"./index-3j40xbgd.js";import{Dm as he,Fm as jt,Km as Ks,Lm as Yt,Ln as qa,Ml as Uo,Nn as Ja,Tl as Bo,Um as ic,Un as re,Vn as V,Wl as no,Xm as Kt,ao as gs,go as hs,hm as Ie,ho as ys,io as Sd,jl as G,jm as P,km as Ge,nk as Cl,nl as Qa,nn as hd,ok as Tl,ol as F,on as Td,oo as Ts,pk as ie,qo as Ha,rk as $e,rm as oo,sk as Le,sn as ss,tk as Ue,to as de,uk as mr,vk as dt,xo as Y}from"./index-9881eck9.js";import{Ao as Pe,yo as Ye}from"./index-nwdvz1vw.js";import{Bq as C,Bw as lc,Fs as oe,Hs as us,Ts as j,fw as w,gt as D,ot as Q,vw as ne,xw as Xt,yw as nc}from"./index-6gqg29bj.js";import{Tx as c}from"./index-7ne5672k.js";function jr(e,t){let r=new Set(t.map((i)=>i.type));return e.byType.filter((i)=>(i.status==="pending"||i.status==="processing")&&!r.has(i.type))}function Ze(e,t){let r=e.workerSessions,i=r.active===0?"missing":r.stale>0?"stale":"active",n=e.duePending>0&&(e.oldestDuePendingAgeMs??0)>=120000&&e.totals.processing===0&&(e.latestClaimAgeMs===null||e.latestClaimAgeMs>=120000),o=[];if(i==="missing")o.push("No live worker session");else if(i==="stale")o.push(`${r.stale} stale worker session(s)`);if(n)o.push(`${e.duePending} due job(s) have remained unclaimed for at least 120000ms`);if(t){let s=jr(e,t).reduce((a,l)=>a+l.count,0);if(s>0)o.push(`${s} active job(s) have no declared executor`)}return{status:o.length===0?"operational":"degraded",reasons:o,worker:{state:i,activeSessions:r.active,staleSessions:r.stale,latestHeartbeatAgeMs:r.latestHeartbeatAgeMs},queue:{duePending:e.duePending,processing:e.totals.processing,oldestDuePendingAgeMs:e.oldestDuePendingAgeMs,latestClaimAgeMs:e.latestClaimAgeMs,stalled:n}}}async function Rn(e){let{config:t,services:r,bootTime:i,endpoints:n,interactions:o}=e,[s,a,l,d]=await Promise.all([r.entityService.getEntityCounts(mt("runtime app info reports operator-facing aggregate status")),r.entityService.countEmbeddings(),r.daemonRegistry.getStatuses(),r.jobQueueService.getDiagnostics()]),u=s.reduce((p,m)=>p+m.count,0);return{model:t.name||"brain-app",version:t.version||"1.0.0",uptime:Math.floor((Date.now()-i)/1000),entities:u,entityCounts:s,embeddings:a,backgroundWork:Ze(d,r.jobQueueService.getExecutionRegistrations()),ai:{model:t.ai.model,embeddingModel:r.embeddingService.identity.model},daemons:l,endpoints:n(),interactions:o()}}import{readdir as wn,readFile as Pu}from"fs/promises";var Cu=10;async function Tu(e="/proc"){let t=null;try{t=(await wn(`${e}/self/fd`)).length}catch{}try{let i=(await wn(e,{withFileTypes:!0})).filter((s)=>s.isDirectory()&&/^\d+$/.test(s.name)).map((s)=>s.name),n=0,o=0;return await Promise.all(i.map(async(s)=>{try{let a=await Pu(`${e}/${s}/status`,"utf8");if(o++,/^State:\s+Z\b/m.test(a))n++}catch{}})),{fileDescriptors:t,processCount:o,zombieCount:n}}catch{return{fileDescriptors:t,processCount:null,zombieCount:null}}}function In(e,t,r){return t.status==="fulfilled"?{name:e,status:"healthy",message:r}:{name:e,status:"unhealthy",message:P(t.reason)}}function Eu(e){if(!e)return{name:"job-worker",status:"degraded",message:"Worker session state is unavailable"};let t=e.workerSessions,r=Ze(e).worker;if(r.state==="missing")return{name:"job-worker",status:"degraded",message:"No live worker session",details:{sessions:t}};if(r.state==="stale")return{name:"job-worker",status:"degraded",message:`${t.stale} stale worker session(s)`,details:{sessions:t}};return{name:"job-worker",status:"healthy",message:`${t.active} live worker session(s)`,details:{sessions:t}}}function Au(e){if(!e)return{name:"job-queue-progress",status:"degraded",message:"Queue progress state is unavailable"};let t=Ze(e).queue;return t.stalled?{name:"job-queue-progress",status:"degraded",message:`${t.duePending} due job(s) are not being claimed`,details:{queue:t}}:{name:"job-queue-progress",status:"healthy",message:"Due jobs are being claimed",details:{queue:t}}}function ku(e,t){if(!e||!t)return{name:"job-execution-inventory",status:"degraded",message:"Job execution inventory is unavailable"};let r=jr(e,t),i=r.reduce((n,o)=>n+o.count,0);return i===0?{name:"job-execution-inventory",status:"healthy",message:"Every active job type has a declared executor"}:{name:"job-execution-inventory",status:"degraded",message:`${i} active job(s) have no declared executor`,details:{jobs:r}}}function ju(e){if(!e)return{name:"attempt-leases",status:"degraded",message:"Lease state is unavailable"};return e.staleLeaseCount===0?{name:"attempt-leases",status:"healthy",message:"No stale processing leases"}:{name:"attempt-leases",status:"degraded",message:`${e.staleLeaseCount} processing lease(s) are stale`,details:{staleLeaseCount:e.staleLeaseCount}}}function Du(e){if(!e.initialized)return{name:"projection-circuits",status:"degraded",message:"Projection runtime supervisor is not initialized"};if(e.openCircuits.length===0)return{name:"projection-circuits",status:"healthy",message:"No projection circuits are open"};return{name:"projection-circuits",status:"degraded",message:`${e.openCircuits.length} projection circuit(s) open`,details:{circuits:e.openCircuits}}}async function Ou(e){let t=e.entityService.getProjectionStore(),[r,i,n]=await Promise.all([t.getActiveWave(),t.getUnresolvedProjectionIncidentDiagnostics(Cu),t.getProjectionBatchDiagnostics?.()??Promise.resolve({preparing:0,open:0,abandoned:0,expiredCallbackLeases:0,oldestActiveAgeMs:null,oldestProgressAgeMs:null})]);if(!r)return{waveId:null,batches:n,strandedRules:[],incidentCount:i.total,incidents:i.incidents};let s=(await t.listWaveRules(r.id)).filter((l)=>l.status==="queued"||l.status==="failed"),a=(await Promise.all(s.map(async(l)=>{let d=l.jobId?await e.jobQueueService.getStatus(l.jobId):null;if(l.status!=="failed"&&d&&(d.status==="pending"||d.status==="processing"))return null;return{ruleId:l.ruleId,jobId:l.jobId,jobStatus:d?.status??"missing"}}))).filter((l)=>l!==null);return{waveId:r.id,batches:n,strandedRules:a,incidentCount:i.total,incidents:i.incidents}}function zu(e){if(e.batches.abandoned>0)return{name:"projection-waves",status:"degraded",message:`${e.batches.abandoned} projection batch(es) await recovery`,details:{batches:e.batches}};if(e.batches.expiredCallbackLeases>0)return{name:"projection-waves",status:"degraded",message:"A callback projection batch lease has expired",details:{batches:e.batches}};if(e.incidentCount>0)return{name:"projection-waves",status:"degraded",message:`${e.incidentCount} unresolved terminal projection incident(s)`,details:{incidentCount:e.incidentCount,incidentsTruncated:e.incidentCount>e.incidents.length,incidents:e.incidents.map((t)=>({waveId:t.waveId,ruleId:t.ruleId,jobId:t.jobId,failureReason:t.failureReason,createdAt:t.createdAt}))}};if(!e.waveId)return{name:"projection-waves",status:"healthy",message:e.batches.open+e.batches.preparing>0?`${e.batches.open+e.batches.preparing} projection batch(es) active`:"No active projection wave",...e.batches.open+e.batches.preparing>0&&{details:{batches:e.batches}}};if(e.strandedRules.length===0)return{name:"projection-waves",status:"healthy",message:`Projection wave ${e.waveId} is progressing`};return{name:"projection-waves",status:"degraded",message:`Projection wave ${e.waveId} has ${e.strandedRules.length} stranded rule job(s)`,details:{waveId:e.waveId,strandedRules:e.strandedRules}}}function Mu(e){let t=e.filter((r)=>r.status!=="running"||r.health?.status==="error");return t.length===0?{name:"daemons",status:"healthy",message:`${e.length} daemon(s) healthy`}:{name:"daemons",status:"degraded",message:`${t.length} daemon(s) unhealthy`,details:{daemons:t.map((r)=>({name:r.name,status:r.status,health:r.health?.status,message:r.health?.message}))}}}async function xn(e){let t=e.now?.()??Date.now(),r=(e.memoryUsage??process.memoryUsage)(),[i,n,o,s,a,l,d,u]=await Promise.allSettled([e.entityService.getEntityCounts(mt("runtime readiness database probe")),e.jobQueueService.getDiagnostics(t),Promise.resolve(e.jobQueueService.getExecutionRegistrations()),e.daemonRegistry.getStatuses(),(e.readProcessSignals??Tu)(),e.projectionRuntimeSupervisor.getDiagnostics(),Ou(e),e.operationalHealthRegistry.getChecks()]),p=n.status==="fulfilled"?n.value:null,m=o.status==="fulfilled"?o.value??null:null,f=s.status==="fulfilled"?s.value:[],g=a.status==="fulfilled"?a.value:{fileDescriptors:null,processCount:null,zombieCount:null},h=l.status==="fulfilled"?l.value:{status:"unhealthy",initialized:!1,trackedRoots:0,openCircuits:[]},v=[In("entity-database",i,"Entity database is accessible"),In("job-queue-database",n,"Job queue database is accessible"),Eu(p),Au(p),ku(p,m),ju(p),l.status==="fulfilled"?Du(h):{name:"projection-circuits",status:"degraded",message:P(l.reason)},d.status==="fulfilled"?zu(d.value):{name:"projection-waves",status:"degraded",message:P(d.reason)},s.status==="fulfilled"?Mu(f):{name:"daemons",status:"degraded",message:P(s.reason)}],y=u.status==="fulfilled"?u.value:[{name:"plugin-operational-health",status:"degraded",message:"Plugin operational health is unavailable"}],S=[...v,...y];return{status:v.some((b)=>b.status==="unhealthy")?"not_ready":"ready",operationalStatus:S.some((b)=>b.status!=="healthy")?"degraded":"operational",checkedAt:new Date(t).toISOString(),checks:S,resources:{memory:{rssBytes:r.rss,heapUsedBytes:r.heapUsed,heapTotalBytes:r.heapTotal},fileDescriptors:g.fileDescriptors,processes:{total:g.processCount,zombies:g.zombieCount},queue:p,projection:{initialized:h.initialized,trackedRoots:h.trackedRoots,openCircuits:h.openCircuits},worker:p?.workerSessions??{total:0,active:0,stale:0,latestHeartbeatAgeMs:null}}}}function Pn(){return{dataDir:"./data",cacheDir:"./cache",distDir:"./dist"}}function fe(e){return{database:{url:`file:${e.dataDir}/brain.db`},jobQueueDatabase:{url:`file:${e.dataDir}/brain-jobs.db`},conversationDatabase:{url:`file:${e.dataDir}/conversations.db`},runtimeStateDatabase:{url:`file:${e.dataDir}/runtime-state.db`},embeddingDatabase:{url:`file:${e.dataDir}/embeddings.db`},embedding:{enabled:!0}}}var He=c.strictObject({enabled:c.boolean().optional().describe("Serve HTTP; defaults to whether the selected bundles host the web surface"),preview:c.boolean().optional().describe("Serve the preview site; defaults to whether a site builder runs"),hostname:c.string().trim().min(1).optional().describe("Bind address; use 127.0.0.1 for isolated local tests"),productionDistDir:c.string().min(1).optional().describe("Directory of the production site, when no site builder writes it"),previewDistDir:c.string().min(1).optional().describe("Directory of the preview site, when no site builder writes it"),sharedImagesDir:c.string().min(1).optional().describe("Directory of shared optimized images")}),Dr=He.extend({enabled:c.boolean().default(!1),preview:c.boolean().default(!0),port:c.number().default(8080).describe("Port of the production listener")});var zr=Pn(),Lu=c.looseObject({label:c.string().min(1),pluralName:c.string().optional(),layout:c.string().optional(),paginate:c.boolean().optional(),pageSize:c.number().optional(),navigation:c.object({show:c.boolean().optional(),slot:c.enum(["primary","secondary"]).optional(),priority:c.number().optional()}).optional()});function Mr(){return fe(zr)}var xe=c.enum(["debug","info","warn","error"]);var Lr=c.object({name:c.string().default("brain-app"),version:c.string().default("1.0.0"),database:Ie,jobQueueDatabase:Ie,jobQueue:c.object({workerConcurrency:c.number().int().min(1).max(32).default(4)}).prefault({}),conversationDatabase:Ie,runtimeStateDatabase:Ie,embeddingDatabase:Ie,ai:c.object({providerKeys:We.default({}),model:c.string().refine(Cn,{error:(e)=>`Unsupported model "${String(e.input)}"`}),embeddingModel:c.string().refine((e)=>Or(e)!==void 0,{error:(e)=>An(String(e.input))}).default(En),modelRuntimeUrl:c.string().url().optional(),answerModel:c.string().optional(),visionModel:c.string().optional(),imageModel:c.string().optional(),temperature:c.number().min(0).max(2).default(0.7),webSearch:c.boolean().default(!0),reasoningEffort:re.optional()}).superRefine((e,t)=>{if(e.answerModel&&ge(e.answerModel)!=="local")t.addIssue({code:"custom",path:["answerModel"],message:`answerModel must be a local: model, not ${e.answerModel}`});if(e.visionModel&&ge(e.visionModel)!=="local")t.addIssue({code:"custom",path:["visionModel"],message:`visionModel must be a local: model, not ${e.visionModel}`});if(e.modelRuntimeUrl)return;let r=[...ge(e.model)==="local"?[e.model]:[],...[e.answerModel,e.visionModel].filter((i)=>i!==void 0&&ge(i)==="local"),...e.imageModel&&Tn(e.imageModel).provider==="local"?[e.imageModel]:[],...Or(e.embeddingModel)?.provider==="local"?[e.embeddingModel]:[]];for(let i of r)t.addIssue({code:"custom",path:["modelRuntimeUrl"],message:`${i} needs modelRuntime.url`})}),embedding:c.object({enabled:c.boolean().default(!0)}),logging:c.object({level:xe.default("info"),format:c.enum(["text","json"]).default("text"),file:c.string().optional(),context:c.string().default("shell")}).prefault({level:"info",context:"shell"}),features:c.object({}).default({}),plugins:c.array(ft).default([]),dataDir:c.string().default("./brain-data"),gitBrokerSocket:c.string().min(1).optional(),gitBrokerCheckout:c.string().min(1).optional(),spaces:c.array(c.string()).default([]),siteBaseUrl:c.string().optional(),localSiteUrl:c.string().optional(),preferLocalUrls:c.boolean().default(!1),production:c.boolean().default(!1),themeCSS:c.string().default(""),entityDisplay:c.record(c.string(),Lu).optional(),profileKind:c.string().trim().min(1).optional(),http:Dr.prefault({})});function gt(e={}){let{plugins:t=[],permissions:r={},identity:i,profile:n,agentInstructions:o,evalHandlerRegistry:s,ai:a,logging:l,embedding:d,jobQueue:u,...p}=e,{entityDisplay:m,...f}=Lr.parse({...Mr(),...F(p),ai:F({...a}),logging:F({...l}),embedding:F({...d}),jobQueue:F({...u}),plugins:[]});return{...f,plugins:t,permissions:r,...F({entityDisplay:m,identity:i,profile:n,agentInstructions:o,evalHandlerRegistry:s})}}var L={NOTE:"note",BRAIN_CHARACTER:"brain-character",ANCHOR_PROFILE:"anchor-profile"},qe={KNOWLEDGE_QUERY:"shell:knowledge-query",BASE_ENTITY_DISPLAY:"shell:base-entity-display",CONTENT_GENERATION:"shell:content-generation"},Ur={ENTITIES:"shell:entities"};var Uu=kn.extend({templateName:c.string()}),Bu=c.object({slug:c.string()}),$u="The style guide governs voice, tone, wording and form: paragraphing, sentence rhythm, hooks, rhetorical questions and calls to action. The instructions below and any additional instructions in the request govern the task, required content, length limits, platform constraints and output format. When either conflicts with the style guide on voice or form, follow the style guide.",_u="Generate the content described in your instructions.";function Fu(e){return e instanceof c.ZodType}function Nu(e){if(!e)return;return e.replace(/^https?:\/\//,"").replace(/\/$/,"")}class yt{aiService;entityService;templateRegistry;getIdentityContent;getProfileContent;entityUrls;id="ai-content";name="AI Content Generator";description="Generates content using AI based on templates and prompts";constructor(e,t,r,i,n,o,s){this.aiService=e,this.entityService=t,this.templateRegistry=r,this.getIdentityContent=i,this.getProfileContent=n,this.entityUrls=o,this.siteBaseUrl=Nu(s)}siteBaseUrl;async generate(e,t,r){return this.generateWithContext(e,t,r)}async generateScoped(e,t,r){return this.generateWithContext(e,t,r.signal,r)}async generateWithContext(e,t,r,i){r?.throwIfAborted();let n=Uu.parse(e),o=this.templateRegistry.get(n.templateName);if(!o)throw Error(`Template not found: ${n.templateName}`);if(!o.basePrompt)throw Error(`Template ${n.templateName} must have basePrompt for content generation`);let s=i?await jn((v,y)=>i.getEntity(v,y),n.templateName,o.basePrompt):await ht(this.entityService,n.templateName,o.basePrompt);r?.throwIfAborted();let a=[s,n.prompt].filter(Boolean).join(" "),l=a.length>0&&o.useKnowledgeContext===!0,d=this.entityService.getWeightMap(),u=Object.keys(d).length>0,p=l?i?await i.search(a,{limit:5,...u&&{weight:d}}):await this.entityService.search({query:a,options:{limit:5,...u&&{weight:d},...r&&{signal:r}}}):[];r?.throwIfAborted();let m=this.buildPrompt(n,p),f=i?await this.readIdentities(i,n.representedIdentity):void 0,g=this.buildSystemPrompt(s,n,f);if(!Fu(o.schema))throw Error(`Template ${o.name} cannot be used for AI generation: schema is not an AI generation schema`);r?.throwIfAborted();let h=await this.aiService.generateObject(g,m,o.schema,r);return r?.throwIfAborted(),t.parse(h.object)}async readIdentities(e,t){let r=async(o)=>(await e.getEntity(o,o))?.content??"",[i,n]=await Promise.all([t!=="none"?r(L.BRAIN_CHARACTER):"",t===void 0||t==="anchor"?r(L.ANCHOR_PROFILE):""]);return{brain:i,anchor:n}}buildSystemPrompt(e,t,r){let i=[];if(t.representedIdentity===void 0||t.representedIdentity==="brain"||t.representedIdentity==="anchor")i.push("# Brain Identity",r?.brain??this.getIdentityContent(),"");if(t.representedIdentity===void 0||t.representedIdentity==="anchor")i.push("# Represented Anchor",r?.anchor??this.getProfileContent(),"");let n=this.selectStyleGuidance(t);if(n)i.push("# Style Guide",n,"","# Precedence",$u,"");return i.push("# Instructions",e),i.join(`
3
3
  `)}selectStyleGuidance(e){if(!e.styleGuide)return"";let t=[];if(e.styleGuide.voice)t.push("## Voice",e.styleGuide.voice);if(e.styleGuide.visual)t.push("## Visual",e.styleGuide.visual);return t.join(`
4
4
  `)}buildPrompt(e,t=[]){let r=[];if(e.conversationHistory)r.push(`Recent conversation context:
5
5
  ${e.conversationHistory}`);if(t.length>0){let i=t.map((n)=>this.formatRelevantEntity(n,this.entityUrls)).join(`
@@ -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 (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: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(`
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=E45F3738710E4E8C64756E2164756E21
117
- //# sourceMappingURL=index-68ge01gj.js.map
116
+ //# debugId=81E3B6DAA7E8C9F964756E2164756E21
117
+ //# sourceMappingURL=index-y57zfnpa.js.map