@rizom/brain 0.2.0-alpha.665 → 0.2.0-alpha.666
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/brain.js +305 -305
- package/dist/chunks/{app-r38g5v72.js → app-5ya65mn4.js} +2 -2
- package/dist/chunks/{index-nkfky4wq.js → index-4vfkkqqd.js} +3 -3
- package/dist/chunks/{index-nkfky4wq.js.map → index-4vfkkqqd.js.map} +1 -1
- package/dist/chunks/{index-kpvg8384.js → index-d8qy5tp9.js} +3 -3
- package/dist/chunks/{index-kpvg8384.js.map → index-d8qy5tp9.js.map} +1 -1
- package/dist/chunks/{index-8rkqenh0.js → index-k67qs6ef.js} +2 -2
- package/dist/chunks/{index-a7hp97k8.js → index-swfqashf.js} +3 -3
- package/dist/chunks/{index-a7hp97k8.js.map → index-swfqashf.js.map} +3 -3
- package/dist/model.js +34 -34
- package/dist/model.js.map +1 -1
- package/dist/testing.js +1 -1
- package/package.json +1 -1
- /package/dist/chunks/{app-r38g5v72.js.map → app-5ya65mn4.js.map} +0 -0
- /package/dist/chunks/{index-8rkqenh0.js.map → index-k67qs6ef.js.map} +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{T as a}from"./index-
|
|
2
|
+
import{T as a}from"./index-k67qs6ef.js";import"./index-d4cwts1m.js";import"./index-swfqashf.js";import"./index-9q28hw2n.js";import"./index-ghgmrnah.js";import"./index-vnmhrs37.js";import"./index-8x0kwwhw.js";import"./index-tmnreybm.js";import"./index-cgp1833q.js";import"./index-fn5rgey6.js";export{a as App};
|
|
3
3
|
|
|
4
4
|
//# debugId=E39D22419280CB1064756E2164756E21
|
|
5
|
-
//# sourceMappingURL=app-
|
|
5
|
+
//# sourceMappingURL=app-5ya65mn4.js.map
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{a as z,b as f}from"./index-xjpmcykr.js";import{d as c,e as l}from"./index-pv0fr3wz.js";import{U as D}from"./index-d4cwts1m.js";import{$i as M,Ai as B,Lh as x,fi as I,gi as A,hi as P,ii as T,ji as R,ki as S,ni as L,ui as w}from"./index-9q28hw2n.js";import"./index-ghgmrnah.js";import{ct as k}from"./index-vnmhrs37.js";import{jv as d}from"./index-8x0kwwhw.js";import"./index-tmnreybm.js";import"./index-cgp1833q.js";import{vv as h}from"./index-fn5rgey6.js";var m=d.object({theme:d.object({primaryColor:d.string().describe("Primary color for the CLI theme").default("#0066cc"),accentColor:d.string().describe("Accent color for the CLI theme").default("#ff6600")}).describe("Theme configuration for the CLI interface").default({primaryColor:"#0066cc",accentColor:"#ff6600"})});var b={name:"@brains/chat-repl",license:"AGPL-3.0-only",version:"0.2.0-alpha.
|
|
2
|
+
import{a as z,b as f}from"./index-xjpmcykr.js";import{d as c,e as l}from"./index-pv0fr3wz.js";import{U as D}from"./index-d4cwts1m.js";import{$i as M,Ai as B,Lh as x,fi as I,gi as A,hi as P,ii as T,ji as R,ki as S,ni as L,ui as w}from"./index-9q28hw2n.js";import"./index-ghgmrnah.js";import{ct as k}from"./index-vnmhrs37.js";import{jv as d}from"./index-8x0kwwhw.js";import"./index-tmnreybm.js";import"./index-cgp1833q.js";import{vv as h}from"./index-fn5rgey6.js";var m=d.object({theme:d.object({primaryColor:d.string().describe("Primary color for the CLI theme").default("#0066cc"),accentColor:d.string().describe("Accent color for the CLI theme").default("#ff6600")}).describe("Theme configuration for the CLI interface").default({primaryColor:"#0066cc",accentColor:"#ff6600"})});var b={name:"@brains/chat-repl",license:"AGPL-3.0-only",version:"0.2.0-alpha.666",dependencies:{"@brains/plugins":"workspace:*","@brains/utils":"workspace:*",chalk:"^5.4.1",ink:"^7.0.6","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0",marked:"^18.0.5",react:"^19.2.7"},devDependencies:{"@brains/eslint-config":"workspace:*","@brains/typescript-config":"workspace:*","@types/bun":"^1.4.0","@types/react":"^19.2.17",typescript:"^7.0.2"},files:["src"],main:"./src/index.ts",module:"./src/index.ts",private:!0,scripts:{dev:"tsc --watch",lint:"eslint . --max-warnings 0","lint:fix":"eslint . --max-warnings 0 --fix",test:"bun test",typecheck:"tsc --noEmit"},type:"module",types:"./src/index.ts"};var Z={completed:"\u2713",declined:"\u25CB",failed:"\u2717"},F={deniedCardIds:void 0,resolveUrl:(e)=>e,isHiddenUrl:()=>!1,eventActionUnavailableLabel:void 0};class E extends x{inkApp=null;responseCallback;systemMessageCallback;agentService;removeSignalHandlers;approvalTracker;constructor(e={}){super("cli",b,e,m)}getAgentService(){if(!this.agentService)throw Error("AgentService not initialized - plugin not registered");return this.agentService}async onRegister(e){await super.onRegister(e),this.agentService=e.agent,this.logger.debug("CLI interface registered with AgentService")}sendMessageToChannel({message:e}){let s=typeof e==="string"?e:e.fallbackText??"";if(!s)return;(this.systemMessageCallback??this.responseCallback)?.(s)}sendReply(e){this.responseCallback?.(e)}registerResponseCallback(e){this.responseCallback=e}registerSystemMessageCallback(e){this.systemMessageCallback=e}unregisterMessageCallbacks(){this.responseCallback=void 0,this.systemMessageCallback=void 0}async onProgressUpdate(e){this.logger.debug("CLI progress update",{eventId:e.id,status:e.status,progress:e.progress,message:e.message})}createDaemon(){return{start:async()=>{if(!this.context)throw new M(this.id,"Initialization failed: Plugin context not initialized");this.logger.debug("Starting CLI interface");try{let[e,s,n]=await Promise.all([import("./index-ca4njxdv.js"),import("react"),import("./EnhancedApp-geqtkejd.js")]),{render:r}=e,t=s.default,o=n.default,g=t.createElement(o,{interface:this,registerProgressCallback:(i)=>this.registerProgressCallback(i),unregisterProgressCallback:()=>this.unregisterProgressCallback(),registerResponseCallback:(i)=>this.registerResponseCallback(i),registerSystemMessageCallback:(i)=>this.registerSystemMessageCallback(i),unregisterMessageCallbacks:()=>this.unregisterMessageCallbacks()});this.inkApp=r(g),this.registerSignalHandlers()}catch(e){throw this.logger.error("Failed to start CLI interface",{error:e}),e}},stop:async()=>{this.logger.debug("Stopping CLI interface"),await this.cleanup()},healthCheck:async()=>{let e=this.inkApp!==null;return{status:e?"healthy":"error",message:e?"CLI interface is running":"CLI interface not running",lastCheck:new Date,details:{hasInkApp:this.inkApp!==null,hasCallbacks:this.hasProgressCallback()}}}}}getApprovalTracker(){return this.approvalTracker??=new L({loadMessages:async(e)=>await this.context?.conversations.getMessages(e,{limit:50})??[],onRestoreError:(e,s)=>{this.logger.debug("Failed to restore pending CLI approvals",{error:e,conversationId:s})}}),this.approvalTracker}async getPendingApprovalIds(e){return[...await this.getApprovalTracker().getApprovalIds(e)]}async processInput(e){this.startProcessingInput();try{let n=await this.getPendingApprovalIds("cli");if(n.length>0){if(await this.handleConfirmationResponse(e,"cli",n))return}let r=await this.getAgentService().chat(e,"cli",{userPermissionLevel:"admin",isAnchor:this.getContext().permissions.isAnchor("cli","local"),interfaceType:"cli",channelId:"cli",channelName:"CLI Terminal"}),t=I(r.cards),o=t.length>0?t.map((i)=>i.id):r.pendingConfirmations?.map((i)=>i.id)??[];this.getApprovalTracker().replaceApprovals("cli",o);let g=this.renderAgentResponse(r);this.logger.debug("Agent response received",{textLength:r.text.length,toolResultsCount:r.toolResults?.length??0,toolResults:r.toolResults?.map((i)=>({toolName:i.toolName,hasData:i.data!==void 0}))}),this.sendReply(g)}catch(n){this.logger.error("Error processing input",{error:n,input:e});let r=k(n,"An unknown error occurred");this.sendReply(`**Error:** ${r}`)}finally{this.endProcessingInput()}}renderAgentResponse(e){let s=w(e,{deniedCardIds:void 0}),n=[],r=[],t="";for(let o of s.directives)switch(o.kind){case"text":t=o.text;break;case"approvals":n.push(...o.cards);break;default:if(o.card.kind==="tool-approval"&&o.card.state==="approval-requested"){n.push(o.card);break}r.push(B(o.card,F))}return[this.formatAgentResponseText(t,n),...r].filter((o)=>o.trim().length>0).join(`
|
|
3
3
|
|
|
4
4
|
`)}formatAgentResponseText(e,s){if(s.length===0)return e;let n=P(e,s);if(s.length===1){let t=s[0];if(!t)return e;let o=t.preview?`
|
|
5
5
|
|
|
@@ -15,5 +15,5 @@ _Please reply with **yes 1** / **no 1** for the matching action._`}formatApprova
|
|
|
15
15
|
|
|
16
16
|
${r.error}`:`${t} ${r.summary}`}resolveApprovalIndexSugar(e,s){let n=/^(.*?)\s+#?(\d+)$/.exec(e.trim());if(!n?.[1]||!n[2])return e;let r=s[Number(n[2])-1];return r?`${n[1]} ${r}`:e}async handleConfirmationResponse(e,s,n){let r=new Set(n);if(!S(e,r))return!1;let t=R({message:this.resolveApprovalIndexSugar(e,n),approvalIds:r});if(t.kind==="not-confirmation")return!1;if(t.kind==="notice")return this.sendReply(`_${t.message}_`),!0;this.getApprovalTracker().removeApproval(s,t.approvalId);let o=await this.getAgentService().confirmPendingAction(s,t.confirmed,t.approvalId,{userPermissionLevel:"admin",isAnchor:this.getContext().permissions.isAnchor("cli","local"),interfaceType:"cli"});return this.getApprovalTracker().syncFromResponse(s,o,t.approvalId),this.sendReply(this.formatApprovalResultText(o.text,o.cards)),!0}registerSignalHandlers(){let e=()=>{this.logger.debug("Received termination signal, stopping CLI"),this.cleanup()};this.removeSignalHandlers=D(["SIGINT","SIGTERM"],e)}async cleanup(){if(this.unregisterProgressCallback(),this.unregisterMessageCallbacks(),this.removeSignalHandlers?.(),this.removeSignalHandlers=void 0,this.inkApp)this.inkApp.unmount(),this.inkApp=null}}import{jsx as a,jsxs as p}from"react/jsx-runtime";function j({batchStatus:e,showDetails:s=!0}){let{batchId:n,totalOperations:r,completedOperations:t,failedOperations:o,currentOperation:g,errors:i,status:u}=e,O=u==="processing",v=u==="completed",C=u==="failed",y=t-o;return p(c,{flexDirection:"column",marginY:1,children:[a(c,{marginBottom:1,children:p(l,{bold:!0,color:"cyan",children:["Batch Operation: ",n.slice(0,8),"..."]})}),a(c,{marginBottom:1,children:a(f,{current:t,total:r,message:"Overall Progress:",color:C?"red":v?"green":"yellow"})}),O&&g&&p(c,{marginBottom:1,children:[a(l,{color:"green",children:a(z,{type:"dots"})}),p(l,{color:"gray",children:[" ",g]})]}),s&&p(c,{flexDirection:"column",marginLeft:2,children:[y>0&&p(c,{children:[a(l,{color:"green",children:"\u2713 "}),p(l,{color:"gray",children:[y," successful"]})]}),o>0&&p(c,{children:[a(l,{color:"red",children:"\u2717 "}),p(l,{color:"gray",children:[o," failed"]})]}),i.length>0&&p(c,{flexDirection:"column",marginTop:1,children:[a(l,{color:"red",bold:!0,children:"Errors:"}),i.slice(0,3).map((H,_)=>p(c,{marginLeft:2,children:[a(l,{color:"red",children:"\u2022 "}),a(l,{color:"gray",children:H})]},_)),i.length>3&&a(c,{marginLeft:2,children:p(l,{color:"gray",children:["... and ",i.length-3," more"]})})]})]}),v&&a(c,{marginTop:1,children:a(l,{color:"green",bold:!0,children:"\u2713 Batch completed successfully"})}),C&&a(c,{marginTop:1,children:a(l,{color:"red",bold:!0,children:"\u2717 Batch failed"})})]})}export{j as BatchProgress,E as CLIInterface,f as ProgressBar,m as cliConfigSchema};
|
|
17
17
|
|
|
18
|
-
//# debugId=
|
|
19
|
-
//# sourceMappingURL=index-
|
|
18
|
+
//# debugId=1E0062BD71ADF2B064756E2164756E21
|
|
19
|
+
//# sourceMappingURL=index-4vfkkqqd.js.map
|
|
@@ -7,6 +7,6 @@
|
|
|
7
7
|
"/** @jsxImportSource react */\nimport React from \"react\";\nimport { Box, Text } from \"ink\";\nimport Spinner from \"ink-spinner\";\nimport type { BatchJobStatus } from \"@brains/plugins\";\nimport { ProgressBar } from \"./ProgressBar\";\n\ninterface BatchProgressProps {\n batchStatus: BatchJobStatus;\n showDetails?: boolean;\n}\n\nexport function BatchProgress({\n batchStatus,\n showDetails = true,\n}: BatchProgressProps): React.ReactElement {\n const {\n batchId,\n totalOperations,\n completedOperations,\n failedOperations,\n currentOperation,\n errors,\n status,\n } = batchStatus;\n\n const inProgress = status === \"processing\";\n const isCompleted = status === \"completed\";\n const isFailed = status === \"failed\";\n\n // Calculate successful operations\n const successfulOperations = completedOperations - failedOperations;\n\n return (\n <Box flexDirection=\"column\" marginY={1}>\n {/* Header */}\n <Box marginBottom={1}>\n <Text bold color=\"cyan\">\n Batch Operation: {batchId.slice(0, 8)}...\n </Text>\n </Box>\n\n {/* Main progress bar */}\n <Box marginBottom={1}>\n <ProgressBar\n current={completedOperations}\n total={totalOperations}\n message=\"Overall Progress:\"\n color={isFailed ? \"red\" : isCompleted ? \"green\" : \"yellow\"}\n />\n </Box>\n\n {/* Current operation */}\n {inProgress && currentOperation && (\n <Box marginBottom={1}>\n <Text color=\"green\">\n <Spinner type=\"dots\" />\n </Text>\n <Text color=\"gray\"> {currentOperation}</Text>\n </Box>\n )}\n\n {/* Details section */}\n {showDetails && (\n <Box flexDirection=\"column\" marginLeft={2}>\n {/* Success count */}\n {successfulOperations > 0 && (\n <Box>\n <Text color=\"green\">✓ </Text>\n <Text color=\"gray\">{successfulOperations} successful</Text>\n </Box>\n )}\n\n {/* Failure count */}\n {failedOperations > 0 && (\n <Box>\n <Text color=\"red\">✗ </Text>\n <Text color=\"gray\">{failedOperations} failed</Text>\n </Box>\n )}\n\n {/* Errors */}\n {errors.length > 0 && (\n <Box flexDirection=\"column\" marginTop={1}>\n <Text color=\"red\" bold>\n Errors:\n </Text>\n {errors.slice(0, 3).map((error, index) => (\n <Box key={index} marginLeft={2}>\n <Text color=\"red\">• </Text>\n <Text color=\"gray\">{error}</Text>\n </Box>\n ))}\n {errors.length > 3 && (\n <Box marginLeft={2}>\n <Text color=\"gray\">... and {errors.length - 3} more</Text>\n </Box>\n )}\n </Box>\n )}\n </Box>\n )}\n\n {/* Final status */}\n {isCompleted && (\n <Box marginTop={1}>\n <Text color=\"green\" bold>\n ✓ Batch completed successfully\n </Text>\n </Box>\n )}\n\n {isFailed && (\n <Box marginTop={1}>\n <Text color=\"red\" bold>\n ✗ Batch failed\n </Text>\n </Box>\n )}\n </Box>\n );\n}\n"
|
|
8
8
|
],
|
|
9
9
|
"mappings": ";8cAcO,IAAM,EAAmC,EAAE,OAAO,CACvD,MAAO,EACJ,OAAO,CACN,aAAc,EACX,OAAO,EACP,S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AAY,EAA7B,SAGE,CAFA,EAAsB,EAAtB,CAAM,MAAM,MAAZ,mBAAsB,EACtB,EAA4B,EAA5B,CAAM,MAAM,OAAZ,SAAoB,EAAQ,IAFpB,CAGR,CACH,EACA,EAAO,OAAS,GACf,EAEE,EAFF,CAAK,WAAY,EAAjB,SACE,EAAqD,EAArD,CAAM,MAAM,OAAZ,SAAqD,CAArD,WAA4B,EAAO,OAAS,EAA5C,SAAqD,EACrD,GAEJ,GAEJ,EAIH,GACC,EAIE,EAJF,CAAK,UAAW,EAAhB,SACE,EAEE,EAFF,CAAM,MAAM,QAAQ,KAAI,GAAxB,+CAEE,EACF,EAGH,GACC,EAIE,EAJF,CAAK,UAAW,EAAhB,SACE,EAEE,EAFF,CAAM,MAAM,MAAM,KAAI,GAAtB,+BAEE,EACF,GAEJ",
|
|
10
|
-
"debugId": "
|
|
10
|
+
"debugId": "1E0062BD71ADF2B064756E2164756E21",
|
|
11
11
|
"names": []
|
|
12
12
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{jv as n}from"./index-8x0kwwhw.js";var w={name:"@rizom/brain",version:"0.2.0-alpha.
|
|
2
|
+
import{jv as n}from"./index-8x0kwwhw.js";var w={name:"@rizom/brain",version:"0.2.0-alpha.666",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/admin":"workspace:*","@brains/agent-discovery":"workspace:*","@brains/ai-evaluation":"workspace:*","@brains/ai-service":"workspace:*","@brains/analytics":"workspace:*","@brains/app":"workspace:*","@brains/ask-content":"workspace:*","@brains/assessment":"workspace:*","@brains/atproto":"workspace:*","@brains/atproto-registry":"workspace:*","@brains/auth-service":"workspace:*","@brains/blog":"workspace:*","@brains/book":"workspace:*","@brains/build-tools":"workspace:*","@brains/chat":"workspace:*","@brains/contact":"workspace:*","@brains/content-formatters":"workspace:*","@brains/content-pipeline":"workspace:*","@brains/contracts":"workspace:*","@brains/conversation-memory":"workspace:*","@brains/core":"workspace:*","@brains/dashboard":"workspace:*","@brains/decks":"workspace:*","@brains/deploy-support":"workspace:*","@brains/directory-sync":"workspace:*","@brains/doc":"workspace:*","@brains/document-plugin":"workspace:*","@brains/email":"workspace:*","@brains/email-workflows":"workspace:*","@brains/entity-service":"workspace:*","@brains/eslint-config":"workspace:*","@brains/faq":"workspace:*","@brains/guide":"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/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/webserver":"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:"brain-eval","eval:headless":"brain-eval --suite headless","eval:personal":"brain-eval --suite personal","eval:professional":"brain-eval --suite professional","eval:team":"brain-eval --suite team",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,canonical-eval-suites,public-plugin-api,public-authoring-golden,public-authoring-docs,public-chat-contract,package-metadata,studio-groupings-plugin,studio-groupings-runtime,studio-groupings-processes}.test.{ts,tsx}'","test:boot-smoke":"bun run build && bun run test:boot-smoke:prebuilt","test:boot-smoke:prebuilt":"bun test test/boot-smoke.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 l,readFileSync as b}from"fs";import{dirname as u,join as o}from"path";var m=n.looseObject({name:n.string().min(1),version:n.string().min(1),dependencies:n.record(n.string(),n.string()).optional(),peerDependencies:n.record(n.string(),n.string()).optional()});class c 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 p(e){let s=u(e);return s===e?[e]:[e,...p(s)]}function g(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=p(e).find((a)=>l(o(a,"package.json")));if(s===void 0)throw Error(`No package.json at or above "${e}"; run from the package's own directory`);let i=o(s,"package.json"),r=JSON.parse(b(i,"utf8")),t=m.safeParse(r);if(!t.success)throw Error(`"${i}" must declare non-empty name and version fields`);return g(t.data,s)}function R(e,s){let i=e.peerDependencies["@rizom/brain"];if(!i||!Bun.semver.satisfies(s,i))throw new c(e,s,i)}function P(e,s,i){let r=e.filter((t)=>t.kind==="handler"&&t.method===s);return r.find((t)=>t.match==="exact"&&t.fullPath===i)??r.filter((t)=>t.match==="prefix"&&(i===t.fullPath||i.startsWith(`${t.fullPath.replace(/\/$/,"")}/`))).sort((t,a)=>a.fullPath.length-t.fullPath.length)[0]}
|
|
3
3
|
export{v as V,R as W,P as X,w as Y};
|
|
4
4
|
|
|
5
|
-
//# debugId=
|
|
6
|
-
//# sourceMappingURL=index-
|
|
5
|
+
//# debugId=AC73BFD7966232BD64756E2164756E21
|
|
6
|
+
//# sourceMappingURL=index-d8qy5tp9.js.map
|
|
@@ -6,6 +6,6 @@
|
|
|
6
6
|
"import type { ApiRouteDefinition } from \"./api-routes\";\nimport type {\n WebRouteHandler,\n WebRouteMatch,\n WebRouteMethod,\n} from \"./web-routes\";\n\nexport type SharedHostAdmission = \"admit\" | \"deny\";\n\ninterface RegisteredHttpRouteBase {\n ownerPluginId: string;\n fullPath: string;\n method: WebRouteMethod;\n match: WebRouteMatch;\n sharedHostAdmission: SharedHostAdmission;\n}\n\nexport interface RegisteredHandlerHttpRoute extends RegisteredHttpRouteBase {\n kind: \"handler\";\n /** Explicit preview reachability, independent of shared-host admission. */\n preview?: boolean;\n handler: WebRouteHandler;\n}\n\nexport interface RegisteredToolHttpRoute extends RegisteredHttpRouteBase {\n kind: \"tool\";\n match: \"exact\";\n definition: ApiRouteDefinition;\n}\n\nexport type RegisteredHttpRoute =\n RegisteredHandlerHttpRoute | RegisteredToolHttpRoute;\n\nexport interface HttpRouteManifestEntry {\n ownerPluginId: string;\n kind: RegisteredHttpRoute[\"kind\"];\n method: WebRouteMethod;\n fullPath: string;\n match: WebRouteMatch;\n sharedHostAdmission: SharedHostAdmission;\n}\n\n/**\n * The handler route a request reaches: the route declared for exactly its\n * path, else the longest prefix route that contains the path by segment.\n * The web server and the test brain both serve through this.\n */\nexport function findHandlerRoute(\n routes: readonly RegisteredHttpRoute[],\n method: string,\n path: string,\n): RegisteredHandlerHttpRoute | undefined {\n const handlerRoutes = routes.filter(\n (route): route is RegisteredHandlerHttpRoute =>\n route.kind === \"handler\" && route.method === method,\n );\n return (\n handlerRoutes.find(\n (route) => route.match === \"exact\" && route.fullPath === path,\n ) ??\n handlerRoutes\n .filter(\n (route) =>\n route.match === \"prefix\" &&\n (path === route.fullPath ||\n path.startsWith(`${route.fullPath.replace(/\\/$/, \"\")}/`)),\n )\n .sort((left, right) => right.fullPath.length - left.fullPath.length)[0]\n );\n}\n"
|
|
7
7
|
],
|
|
8
8
|
"mappings": ";itMAAA,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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un
|
|
2
|
-
import{U as c}from"./index-d4cwts1m.js";import{Fa as g,Ka as u,Na as f,Oa as d}from"./index-
|
|
2
|
+
import{U as c}from"./index-d4cwts1m.js";import{Fa as g,Ka as u,Na as f,Oa as d}from"./index-swfqashf.js";import{Bn as h,Pq as n,Qn as a}from"./index-ghgmrnah.js";import{kv as t,lv as r}from"./index-tmnreybm.js";import{vv as m}from"./index-fn5rgey6.js";class p{shell=null;config;signalScope=null;signalShutdownFiber=null;stopPromise=null;hasCLI=!1;static create(e,i){return new p(f(e),i)}constructor(e,i){if(this.config=e,this.hasCLI=process.argv.slice(2).includes("--cli"),i)this.shell=i}async migrate(){let e=r.getInstance();await new u(e).runAllMigrations({database:this.config.shellConfig?.database?.url??this.config.database,jobQueueDatabase:this.config.shellConfig?.jobQueueDatabase?.url,conversationDatabase:this.config.shellConfig?.conversationDatabase?.url,runtimeStateDatabase:this.config.shellConfig?.runtimeStateDatabase?.url})}createShell(e,i){this.shell=g.createFresh(d(this.config,e),void 0,{...i?.processRole&&{processRole:i.processRole},...i?.peerChannel&&{peerChannel:i.peerChannel}})}async registerCLIInterface(){if(!this.hasCLI)return;let e=this.getShell().getPluginManager(),{CLIInterface:i}=await import("./index-4vfkkqqd.js"),s=new i(this.config.cliConfig);e.registerPlugin(s)}async initialize(e,i){if(!this.shell){if(!i?.migrationsCompleted)await this.migrate();this.createShell(e,i)}await this.registerCLIInterface(),await this.getShell().initialize(e)}async start(){if(this.stopPromise)return;this.setupSignalHandlers()}stop(){return this.stopPromise??=this.stopApp(),this.stopPromise}async stopApp(){await this.closeSignalScope(),await this.shell?.shutdown()}async run(e){let s={debug:t.DEBUG,info:t.INFO,warn:t.WARN,error:t.ERROR}[this.config.logLevel??"info"]??t.INFO,o=r.createFresh({level:s,context:this.config.name,useStderr:this.hasCLI});if(this.hasCLI)r.getInstance().setUseStderr(!0);try{await this.initialize(void 0,e),await this.start(),e?.onRuntimeReady?.(),o.info(`\u2705 ${this.config.name} v${this.config.version} ready`),process.stdin.resume()}catch(l){o.error(`\u274C Failed to start ${this.config.name}:`,l),process.exit(1)}}static async run(e,i,s){await p.create(e,i).run(s)}setupSignalHandlers(){if(this.signalScope)return;let e=n.runSync(a.make()),i=()=>{this.requestGracefulShutdown("SIGINT")},s=()=>{this.requestGracefulShutdown("SIGTERM")},o=c(["SIGINT"],i),l=c(["SIGTERM"],s);n.runSync(a.addFinalizer(e,n.sync(()=>{l(),o()}))),this.signalScope=e}requestGracefulShutdown(e){if(this.signalShutdownFiber)return;let i=r.getInstance();i.info(`
|
|
3
3
|
Received ${e}, shutting down gracefully...`);let s=n.tryPromise({try:()=>this.stop(),catch:(o)=>o}).pipe(n.match({onFailure:(o)=>{i.error("Error during shutdown:",o),process.exit(1)},onSuccess:()=>{process.exit(0)}}));this.signalShutdownFiber=n.runFork(s)}async closeSignalScope(){let e=this.signalScope;if(this.signalScope=null,e)await n.runPromise(a.close(e,h.void))}getShell(){if(!this.shell)throw Error("Shell not initialized. Call initialize() first.");return this.shell}}
|
|
4
4
|
export{p as T};
|
|
5
5
|
|
|
6
6
|
//# debugId=7A4B53CC16571B0264756E2164756E21
|
|
7
|
-
//# sourceMappingURL=index-
|
|
7
|
+
//# sourceMappingURL=index-k67qs6ef.js.map
|
|
@@ -30,10 +30,10 @@ ${Et(d)}`}:u,g=t.buildArgs((y)=>({operation:a,confirmed:!0,confirmationToken:y})
|
|
|
30
30
|
|
|
31
31
|
\u2026
|
|
32
32
|
|
|
33
|
-
`}${c.text}`}).join("")}var Gu=0.5;function ga(e,t,r){let i=Ar(e.entity,r);if(i!==e.entity)return{...e,entity:i,excerpt:i.content};let n=Ur(i.content);if(n.length<=pa)return{...e,entity:i};let{content:o,...a}=i;return{...e,entity:a,excerpt:ma(n,t),excerpted:!0}}var Jt=(e)=>e==="public"?{publishedOnly:!0}:{};function Qu(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 fa(e){let{entityService:t,logger:r}=e;return[ie("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. Search results include each matched entity's content; a long one's is excerpted to its best-matching sections, which system_get reads whole. When relevant results already contain the complete evidence needed, answer from those results instead of redundantly listing or getting the same entities. Search results are candidates; do not present weak or unrelated candidates as exact matches. For each new user question about what they have written, mentioned, discussed, or saved, run a fresh search for that turn instead of answering from prior-turn results or memory, including analysis phrasing such as 'How do I discuss X in my writing?'.",Go,async(i,n)=>{Nt(n);let o=x(n.userPermissionLevel);if(i.scope.kind==="type"&&e.entityRegistry.getEntityTypeConfig(i.scope.entityType).embeddable===!1){let{entityType:p}=i.scope;return{success:!0,data:{results:(await t.listEntities({entityType:p,options:{limit:i.limit??e.searchLimit,filter:{visibilityScope:o},...Jt(o)}})).map((m)=>ga({entity:m},i.query,e.entityRegistry)),notSearchable:{entityType:p,hint:`${p} is not in the search index, so the results are its entries, unranked.`}}}}let a=i.minScore??Gu,c=await t.search({query:i.query,options:{limit:i.limit??e.searchLimit,...i.scope.kind==="type"&&{types:[i.scope.entityType]},...i.includeUngenerated!==void 0&&{includeUngenerated:i.includeUngenerated},visibilityScope:o,...Jt(o)}}),l=c.filter((p)=>p.score>=a),d=l.length===0?Qu(c,a):void 0;return{success:!0,data:{results:l.map((p)=>ga(p,i.query,e.entityRegistry)),...d&&{belowThreshold:d}}}},{visibility:"public",sideEffects:"none",cli:{name:"search"}}),ie("system","get","Retrieve a specific entity by type and identifier (ID, slug, or title). If retrieval fails, report the entity as not found rather than describing related generation work as pending.",Qo,async(i,n)=>{if(Nt(n),!t.getEntityTypes().includes(i.entityType))return{success:!1,error:`Unknown entity type: ${i.entityType}. Available: ${t.getEntityTypes().join(", ")}`};let o=x(n.userPermissionLevel),a=await M(t,i.entityType,i.id,r,void 0,o,{...Jt(o),source:!0});if(!a.ok)return{success:!1,error:a.error};let c=Ar(a.entity,e.entityRegistry);return{success:!0,data:{entity:i.part==="body"?{...c,content:Ur(c.content)}:c}}},{visibility:"public",sideEffects:"none",cli:{name:"get"}}),ie("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.",Ko,async(i,n)=>{if(Nt(n),!t.getEntityTypes().includes(i.entityType))return{success:!1,error:`Unknown entity type: ${i.entityType}. Available: ${t.getEntityTypes().join(", ")}`};let o=x(n.userPermissionLevel),a={visibilityScope:o};if(i.status&&i.status!=="any")a.metadata={status:i.status};let{defaultSort:c}=e.entityRegistry.getEntityTypeConfig(i.entityType),d=(await t.listEntities({entityType:i.entityType,options:{limit:i.limit??20,filter:a,...Jt(o),...c?{sortFields:c}:{}}})).map(({content:p,contentHash:u,...m})=>m);return{success:!0,data:{entities:d,count:d.length}}},{visibility:"public",sideEffects:"none",cli:{name:"list"}})]}function Ku(e){let t=Object.fromEntries(Object.entries(e.params.shape).map(([r,i])=>{let n=i instanceof s.ZodDefault?i.unwrap():i,o=i.description?n.describe(i.description):n;return[r,o.optional()]}));return s.looseObject(t).describe(`Params for ${e.type}`)}function Vu(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(Ku),n=s.union([...i,s.looseObject({})]);return s.object({type:s.enum([t,...r]).describe("The report to run"),params:n.optional().describe("The report's params; each report lists its own")})}function ya(e){let{entityService:t,analytics:r}=e,i=r.getDefinitions(),n=i.map((o)=>`${o.type} (${o.description})`).join("; ");return[ie("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}.`,Vu(i),async(o,a)=>({success:!0,data:await r.run({type:o.type,params:o.params,entityService:t,permission:a.userPermissionLevel??"public"})}),{visibility:"public",sideEffects:"none"})]}function ha(e){let{jobs:t}=e;return[_("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.",ns,async(r,i)=>{let n=e.permissionService.hasPermission(i.userPermissionLevel??"public","trusted");if(r.batchId){let c=await t.getBatchStatus(r.batchId);if(!c)return{success:!1,error:`No batch found with ID: ${r.batchId}`};let l=c.totalOperations>0?Math.round(c.completedOperations/c.totalOperations*100):0;return{success:!0,data:{batchId:r.batchId,status:c.status,progress:{total:c.totalOperations,completed:c.completedOperations,failed:c.failedOperations,percentComplete:l},currentOperation:c.currentOperation,...n&&{errors:c.errors}}}}let o=await t.getActiveJobs(r.jobTypes),a=await t.getActiveBatches();return{success:!0,data:{summary:{activeJobs:o.length,activeBatches:a.length},jobs:o.map((c)=>({id:c.id,type:c.type,status:c.status,priority:c.priority,retryCount:c.retryCount,createdAt:new Date(c.createdAt).toISOString(),startedAt:c.startedAt?new Date(c.startedAt).toISOString():null})),batches:a.map((c)=>({batchId:c.batchId,status:c.status.status,totalOperations:c.status.totalOperations,completedOperations:c.status.completedOperations,failedOperations:c.status.failedOperations,currentOperation:c.status.currentOperation,pluginId:c.metadata.metadata.pluginId,...n&&{errors:c.status.errors}}))}}},{visibility:"public",sideEffects:"none"})]}function Yu(e,t){let{entityCounts:r,daemons:i,endpoints:n,interactions:o,...a}=e,c=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:c};return{...a,endpoints:c}}function va(e){return[ie("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",s.object({}),async(t,r)=>({success:!0,data:Yu(await e.getAppInfo(),(i)=>e.permissionService.hasPermission(r.userPermissionLevel??"public",i))}),{visibility:"public",sideEffects:"none",cli:{name:"status"}})]}function ba(e){return[...fa(e),...ha(e),...va(e),...ca(e),...ya(e)]}function Sa(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(`
|
|
33
|
+
`}${c.text}`}).join("")}var Gu=0.5;function ga(e,t,r){let i=Ar(e.entity,r);if(i!==e.entity)return{...e,entity:i,excerpt:i.content};let n=Ur(i.content);if(n.length<=pa)return{...e,entity:i};let{content:o,...a}=i;return{...e,entity:a,excerpt:ma(n,t),excerpted:!0}}var Jt=(e)=>e==="public"?{publishedOnly:!0}:{};function Qu(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 fa(e){let{entityService:t,logger:r}=e;return[ie("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. Search results include each matched entity's content; a long one's is excerpted to its best-matching sections, which system_get reads whole. When relevant results already contain the complete evidence needed, answer from those results instead of redundantly listing or getting the same entities. Search results are candidates; do not present weak or unrelated candidates as exact matches. For each new user question about what they have written, mentioned, discussed, or saved, run a fresh search for that turn instead of answering from prior-turn results or memory, including analysis phrasing such as 'How do I discuss X in my writing?'.",Go,async(i,n)=>{Nt(n);let o=x(n.userPermissionLevel);if(i.scope.kind==="type"&&e.entityRegistry.getEntityTypeConfig(i.scope.entityType).embeddable===!1){let{entityType:p}=i.scope;return{success:!0,data:{results:(await t.listEntities({entityType:p,options:{limit:i.limit??e.searchLimit,filter:{visibilityScope:o},...Jt(o)}})).map((m)=>ga({entity:m},i.query,e.entityRegistry)),notSearchable:{entityType:p,hint:`${p} is not in the search index, so the results are its entries, unranked.`}}}}let a=i.minScore??Gu,c=await t.search({query:i.query,options:{limit:i.limit??e.searchLimit,...i.scope.kind==="type"&&{types:[i.scope.entityType]},...i.includeUngenerated!==void 0&&{includeUngenerated:i.includeUngenerated},visibilityScope:o,...Jt(o)}}),l=c.filter((p)=>p.score>=a),d=l.length===0?Qu(c,a):void 0;return{success:!0,data:{results:l.map((p)=>ga(p,i.query,e.entityRegistry)),...d&&{belowThreshold:d}}}},{visibility:"public",sideEffects:"none",cli:{name:"search"}}),ie("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.",Qo,async(i,n)=>{if(Nt(n),!t.getEntityTypes().includes(i.entityType))return{success:!1,error:`Unknown entity type: ${i.entityType}. Available: ${t.getEntityTypes().join(", ")}`};let o=x(n.userPermissionLevel),a=await M(t,i.entityType,i.id,r,void 0,o,{...Jt(o),source:!0});if(!a.ok)return{success:!1,error:a.error};let c=Ar(a.entity,e.entityRegistry);return{success:!0,data:{entity:i.part==="body"?{...c,content:Ur(c.content)}:c}}},{visibility:"public",sideEffects:"none",cli:{name:"get"}}),ie("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.",Ko,async(i,n)=>{if(Nt(n),!t.getEntityTypes().includes(i.entityType))return{success:!1,error:`Unknown entity type: ${i.entityType}. Available: ${t.getEntityTypes().join(", ")}`};let o=x(n.userPermissionLevel),a={visibilityScope:o};if(i.status&&i.status!=="any")a.metadata={status:i.status};let{defaultSort:c}=e.entityRegistry.getEntityTypeConfig(i.entityType),d=(await t.listEntities({entityType:i.entityType,options:{limit:i.limit??20,filter:a,...Jt(o),...c?{sortFields:c}:{}}})).map(({content:p,contentHash:u,...m})=>m);return{success:!0,data:{entities:d,count:d.length}}},{visibility:"public",sideEffects:"none",cli:{name:"list"}})]}function Ku(e){let t=Object.fromEntries(Object.entries(e.params.shape).map(([r,i])=>{let n=i instanceof s.ZodDefault?i.unwrap():i,o=i.description?n.describe(i.description):n;return[r,o.optional()]}));return s.looseObject(t).describe(`Params for ${e.type}`)}function Vu(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(Ku),n=s.union([...i,s.looseObject({})]);return s.object({type:s.enum([t,...r]).describe("The report to run"),params:n.optional().describe("The report's params; each report lists its own")})}function ya(e){let{entityService:t,analytics:r}=e,i=r.getDefinitions(),n=i.map((o)=>`${o.type} (${o.description})`).join("; ");return[ie("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}.`,Vu(i),async(o,a)=>({success:!0,data:await r.run({type:o.type,params:o.params,entityService:t,permission:a.userPermissionLevel??"public"})}),{visibility:"public",sideEffects:"none"})]}function ha(e){let{jobs:t}=e;return[_("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.",ns,async(r,i)=>{let n=e.permissionService.hasPermission(i.userPermissionLevel??"public","trusted");if(r.batchId){let c=await t.getBatchStatus(r.batchId);if(!c)return{success:!1,error:`No batch found with ID: ${r.batchId}`};let l=c.totalOperations>0?Math.round(c.completedOperations/c.totalOperations*100):0;return{success:!0,data:{batchId:r.batchId,status:c.status,progress:{total:c.totalOperations,completed:c.completedOperations,failed:c.failedOperations,percentComplete:l},currentOperation:c.currentOperation,...n&&{errors:c.errors}}}}let o=await t.getActiveJobs(r.jobTypes),a=await t.getActiveBatches();return{success:!0,data:{summary:{activeJobs:o.length,activeBatches:a.length},jobs:o.map((c)=>({id:c.id,type:c.type,status:c.status,priority:c.priority,retryCount:c.retryCount,createdAt:new Date(c.createdAt).toISOString(),startedAt:c.startedAt?new Date(c.startedAt).toISOString():null})),batches:a.map((c)=>({batchId:c.batchId,status:c.status.status,totalOperations:c.status.totalOperations,completedOperations:c.status.completedOperations,failedOperations:c.status.failedOperations,currentOperation:c.status.currentOperation,pluginId:c.metadata.metadata.pluginId,...n&&{errors:c.status.errors}}))}}},{visibility:"public",sideEffects:"none"})]}function Yu(e,t){let{entityCounts:r,daemons:i,endpoints:n,interactions:o,...a}=e,c=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:c};return{...a,endpoints:c}}function va(e){return[ie("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",s.object({}),async(t,r)=>({success:!0,data:Yu(await e.getAppInfo(),(i)=>e.permissionService.hasPermission(r.userPermissionLevel??"public",i))}),{visibility:"public",sideEffects:"none",cli:{name:"status"}})]}function ba(e){return[...fa(e),...ha(e),...va(e),...ca(e),...ya(e)]}function Sa(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(`
|
|
34
34
|
`)}]})},{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 Ra(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((a)=>({id:a.id,entityType:a.entityType,...a.metadata,updated:a.updated}));return{contents:[{uri:`entity://${r}`,mimeType:"application/json",text:JSON.stringify(o,null,2)}]}}},{name:"entity-detail",uriTemplate:"entity://{type}/{id}",description:"Read a single entity by type and ID",mimeType:"text/markdown",complete:{type:async(r)=>{let i=t.getEntityTypes();return r?i.filter((n)=>n.startsWith(r)):i},id:async()=>[]},handler:async({type:r,id:i})=>{let n=await t.getEntity({entityType:r,id:i});if(!n)throw Error(`Entity not found: ${r}/${i}`);return{contents:[{uri:`entity://${r}/${i}`,mimeType:"text/markdown",text:n.content}]}}}]}function wa(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 Ia(e){return["## Entity CRUD","","Use the system tools for ALL entity operations; each tool's description is its contract.","","Treat explicit verbs such as save, create, capture, remember, import, add/connect an agent, approve/archive an agent, update, delete, generate, publish, or sync as mutation requests. Entity-specific instructions may require proactively recording the user's request itself for demand or workflow tracking; follow those instructions even when the user did not use a separate save/create verb. Ordinary status questions like 'what is the status', 'is it ready', 'did that finish', or 'what happened' are not capture requests; answer them by using the relevant status/read tool for the prior operation. Never call system_create for a status follow-up.","","Do not ask for prose confirmation instead of calling the applicable mutating tool; for create, update, delete, generate, publish, sync, and similar state-changing requests, the initial tool call without `confirmed` is how you create the pending confirmation. Never pass `confirmed: true` on the initial user request. Deletion is Admin-only: if system_delete is not available in the current tool surface, say deletion requires Admin access; do not imply a confirmation flow is available. Never claim a durable create/update/delete change was saved, created, done, or completed unless the relevant tool call succeeded or returned a pending confirmation. If a create/update/delete tool is unavailable, unauthorized, or intentionally not called, say you can't make that durable change from the current context; never say saved/created/done. For an explicit write request from an unauthorized/currently unwritable context, refuse directly; do not call system_status or system_search to check permission or look up related content. Entity type descriptions may mark projection-owned or system-maintained types read-only; refuse mutation requests for those types directly without calling read or write tools, searching for a target, or asking which record to mutate.","","Entity types \u2014 select `entityType` by what the type is for:",...e.entityService.getEntityTypes().map((i)=>`- ${i}: ${e.entityRegistry.getAdapter(i).purpose}`)].join(`
|
|
35
35
|
`)}var Ce="system",Xu=s.object({toolName:s.string(),args:s.unknown(),...Ca.partial().shape});function qt(e,t,r,i,n){for(let o of e)try{t(o)}catch{n.debug(`System ${i} ${r(o)} already registered, skipping`)}}function Ta(e,t,r,i){let n=ba(e);qt(n,(p)=>t.registerTool(Ce,p),(p)=>p.name,"tool",i);let o=r.subscribe(Pa.toolExecute(Ce),async(p)=>{let u=Xu.safeParse(p.payload);if(!u.success)return{success:!1,error:"Invalid system tool execute payload"};let{toolName:m,args:g,interfaceType:y,actor:f,conversationId:b,channelId:h,userPermissionLevel:I}=u.data,S=n.find((E)=>E.name===m);if(!S)return{success:!1,error:`System tool not found: ${m}`};let R={interfaceType:y??"system",actor:f??{kind:"service",serviceId:"system"}};if(b)R.conversationId=b;if(h)R.channelId=h;if(I)R.userPermissionLevel=I;return{success:!0,data:await S.handler(g,R)}});i.debug(`Registered ${n.length} system tools`);let a=Sa(e);qt(a,(p)=>t.registerResource(Ce,p),(p)=>p.uri,"resource",i),i.debug(`Registered ${a.length} system resources`);let c=Ra(e);qt(c,(p)=>t.registerResourceTemplate(Ce,p),(p)=>p.uriTemplate,"resource template",i),i.debug(`Registered ${c.length} system resource templates`);let l=wa(e);qt(l,(p)=>t.registerPrompt(Ce,p),(p)=>p.name,"prompt",i),i.debug(`Registered ${l.length} system prompts`);let d=Ia(e);try{t.registerInstructions(Ce,d)}catch{i.debug("System instructions already registered, skipping")}return i.debug("Registered system instructions"),o}function ja(e){let{services:t,jobs:r,analytics:i,query:n,getAppInfo:o}=e,a=t.jobQueueService,c=t.logger.child("system"),l=Ta({entityService:t.entityService,entityRegistry:t.entityRegistry,jobs:{...r,enqueue:xa(a,"system",!1),enqueueBatch:Ea(r,"system"),registerHandler:Aa(a,"system"),has:ka(a)},conversationService:t.conversationService,runtimeUploads:t.runtimeUploadRegistry,attachments:Ht(t.attachmentRegistry),logger:c,query:n,getIdentity:()=>t.identityService.getCharacter(),getProfile:()=>t.profileService.getProfile(),getAppInfo:o,searchLimit:10,analytics:i,permissionService:t.permissionService},t.mcpService,t.messageBus,c);t.disposables.push(l)}class Fr{scope;closePromise=null;closed=!1;constructor(){this.scope=v.runSync(j.make())}buildLayer(e){this.assertOpen();let t=v.runSyncExit(H.buildWithScope(e,this.scope));if(k.isFailure(t))throw te.squash(t.cause);return t.value}addFinalizer(e){this.assertOpen(),v.runSync(j.addFinalizer(this.scope,v.promise(async()=>{await e()})))}addSyncFinalizer(e){this.assertOpen(),v.runSync(j.addFinalizer(this.scope,v.sync(()=>{e()})))}async fork(e){if(this.closed)throw Error("Cannot start background work after shell shutdown");await v.runPromise(v.forkIn(e,this.scope))}close(e=k.void){if(this.closePromise)return this.closePromise;if(this.closed)return Promise.resolve();return this.closed=!0,this.closePromise=v.runPromise(j.close(this.scope,e)),this.closePromise}closeSync(e){if(this.closed)return;this.closed=!0,v.runSync(j.close(this.scope,e))}assertOpen(){if(this.closed)throw Error("Cannot register cleanup after shell shutdown")}}class Wr{config;services;lifecycle;bootloader;initialized=!1;lifecycleState="constructed";bootMode;bootPromise=null;shutdownPromise=null;analyticsRegistry;bootTime=Date.now();endpointRegistry=new Pr;interactionRegistry=new Cr;httpRouteRegistry=Rt.createFresh();jobs;static createFresh(e,t,r){return new Wr(He(e),t,r)}constructor(e,t,r){this.config=e,this.lifecycle=new Fr,Ma(this,()=>this.httpRouteRegistry.getSnapshot());let i=t?.logger??ve.getInstance(),n=ht.createFresh(i,this.config,r?.processRole,r?.peerChannel);try{this.services=n.initializeServices(this.lifecycle,t),this.jobs=_o(this.services.batchJobManager,this.services.jobQueueService),this.analyticsRegistry=Lo(this.services.entityRegistry),this.bootloader=new wr(this.config,this.services,this.lifecycle,n,r?.processRole,{registerCoreDataSources:()=>oi(this.services,this.config),finalizeHttpRoutes:()=>{this.httpRouteRegistry.finalize(No(this.services.pluginManager))},registerSystemCapabilities:()=>ja({services:this.services,jobs:this.jobs,analytics:this.analyticsRegistry,query:(o,a)=>this.query(o,a),getAppInfo:()=>this.getAppInfo()}),createProjectionInputContext:()=>({entities:this.services.entityService,resolvePrompt:(o,a)=>Ge(this.services.entityService,o,a),appInfo:()=>this.getAppInfo(),identityInput:()=>{let o=this.getIdentity(),a=this.getProfile();return Da.parse({brainName:o.name,role:o.role,purpose:o.purpose,values:o.values,profileName:a.name,...a.description!==void 0?{profileDescription:a.description}:{},...a.organization!==void 0?{profileOrganization:a.organization}:{}})}}),createProjectionExecutionContext:()=>({ai:Oa(this),logger:this.services.logger.child("ProjectionRuntime")}),...t?.projectionRuntime&&{projectionRuntime:t.projectionRuntime}}),n.wireShell(this.services,this),qo(this.lifecycle,this.services)}catch(o){try{this.lifecycle.closeSync(k.fail(o))}catch(a){i.error("Failed to roll back Shell service construction",a)}throw 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 this.services.messageBus.send({type:q.shellReady,payload:{timestamp:new Date().toISOString()},sender:"shell",broadcast:!0}),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(k.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"),si(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 za.parse(await this.generateContent({prompt:e,templateName:ke.KNOWLEDGE_QUERY,...n&&{conversationHistory:n},data:o,interfacePermissionGrant:"public"}))}registerPlugin(e){this.requireInitialized("Plugin registration"),this.services.pluginManager.registerPlugin(e)}isInitialized(){return this.initialized}requireInitialized(e){if(!this.initialized)throw Error(`${e} attempted before initialization`)}getEntityService(){return this.services.entityService}getConversationService(){return this.services.conversationService}getEntityRegistry(){return this.services.entityRegistry}async generateObject(e,t,r){this.requireInitialized("Shell generateObject");let{object:i}=await this.services.aiService.generateObject("You are a helpful assistant. Respond with the requested structured data.",e,t,r);return{object:i}}async judge(e){return this.requireInitialized("Shell judge"),this.services.aiService.judge(e)}getAIService(){return this.services.aiService}generateImage(e,t){return this.services.aiService.generateImage(e,t)}canGenerateImages(){return this.services.aiService.canGenerateImages()}getPluginManager(){return this.services.pluginManager}getContentService(){return this.services.contentService}getCallerAuthorizer(){return this.services.callerAuthorizer}getRenderService(){return this.services.renderService}getAttachmentRegistry(){return Ht(this.services.attachmentRegistry)}getRuntimeUploadRegistry(){return La(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}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 Yr({config:this.config,services:this.services,bootTime:this.bootTime,endpoints:()=>this.listEndpoints(),interactions:()=>this.listInteractions()})}getRuntimeReadiness(){return ti(this.services)}}async function Ha(e,t){await ne({label:"entity",config:e,schema:{assets:Ua,entities:$a,entityMutationReceipts:Ba,projectionDirtyInputs:Za,projectionWaves:_a,projectionIncidents:Fa,projectionWaveInputs:Wa,projectionWaveRules:Na,projectionRuleMemos:Ja},migrationsFolder:oe(import.meta.url,"entity-service"),authTokenEnv:"DATABASE_AUTH_TOKEN",logger:t,afterMigrate:qa})}async function Ka(e,t){await ne({label:"job-queue",config:e,schema:{jobQueue:Ga,jobWorkerSessions:Qa},migrationsFolder:oe(import.meta.url,"job-queue"),authTokenEnv:"JOB_QUEUE_DATABASE_AUTH_TOKEN",logger:t})}async function ec(e,t){await ne({label:"conversation",config:e,schema:{conversations:Va,messages:Ya,summaryTracking:Xa},migrationsFolder:oe(import.meta.url,"conversation-service"),authTokenEnv:"CONVERSATION_DATABASE_AUTH_TOKEN",logger:t})}async function tc(e,t){await ne({label:"runtime-state",config:e,schema:{runtimeStateRecords:w},migrationsFolder:oe(import.meta.url,"runtime-state"),authTokenEnv:"RUNTIME_STATE_DATABASE_AUTH_TOKEN",logger:t})}import{mkdir as Nr}from"fs/promises";import{isAbsolute as ep}from"path";function rc(e=process.env){return{dataDir:e.XDG_DATA_HOME??"./data",cacheDir:e.XDG_CACHE_HOME??"./cache",distDir:"./dist"}}function ic(e=process.env){let t=e.BRAIN_GIT_BROKER_CHECKOUT;if(!t)return;if(!ep(t))throw Error(`Git broker checkout path must be absolute: ${t}`);return t}function nc(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 oc(e=process.env){return se(rc(e))}async function sc(e=process.env){let t=rc(e);try{await Nr(t.dataDir,{recursive:!0}),await Nr(t.cacheDir,{recursive:!0}),await Nr(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: ${C(r)}`;throw Error(i,{cause:r})}return se(t)}class tp{logger;migrations;constructor(e,t){this.logger=e,this.migrations=t??{getStandardConfigWithDirectories:()=>sc(),migrateEntities:Ha,migrateJobQueue:Ka,migrateConversations:ec,migrateRuntimeState:tc}}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 Jr={kind:"service",serviceId:"brain-cli"},qr=`${Jr.kind}:${Jr.serviceId}`;function PR(e="admin"){return{interfaceType:"cli",actor:Jr,userPermissionLevel:e}}var xR=s.enum(["eval"]),kR=s.enum(["person","team","organization"]),Hr=s.object({provider:s.enum(["hetzner","docker"]).default("hetzner"),serverSize:s.string().default("cx33"),location:s.string().default("fsn1"),domain:s.string().optional(),docker:s.object({enabled:s.boolean().default(!0),image:s.string().optional()}).prefault({}),ports:s.object({default:s.number().default(3333),preview:s.number().default(4321),production:s.number().default(8080)}).prefault({}),cdn:s.object({enabled:s.boolean().default(!1),provider:s.enum(["bunny","none"]).default("none")}).prefault({}),dns:s.object({enabled:s.boolean().default(!1),provider:s.enum(["bunny","none"]).default("none")}).prefault({}),paths:s.object({install:s.string().optional(),data:s.string().optional()}).prefault({})});var cc=s.object({name:s.string().default("brain-app"),version:s.string().default("1.0.0"),database:s.string().optional(),aiApiKey:s.string().optional(),aiImageKey:s.string().optional(),aiModel:s.string().optional(),aiReasoningEffort:Y.optional(),logLevel:ye.optional(),logFile:s.string().optional(),profileKind:s.string().trim().min(1).optional(),plugins:s.array(qe).default([]),spaces:s.array(s.string()).default([]),identity:ac.optional(),agentInstructions:s.array(s.string()).optional(),deployment:Hr.prefault({})});var rp="NODE_ENV";function ip(){return process.env[rp]}function Gr(){return ip()==="production"}function lc(){return!Gr()}var np="startup-check";function WR(e){let r={...cc.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 NR(e,t){let r={plugins:e.plugins??[],...e.shellConfig};return op(r),sp(e,r),ap(e,r,t),cp(e,r),lp(e,r),dp(e,r),up(e,r),pp(e,r),mp(e,r),r}function op(e){let t=oc();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??=nc(),e.gitBrokerCheckout??=ic()}function sp(e,t){if(e.database)t.database={url:e.database};if(e.profileKind)t.profileKind=e.profileKind;t.features={}}function ap(e,t,r){let i=r?.mode==="startup-check";if(!e.aiApiKey&&!e.aiImageKey&&!e.aiModel&&!e.aiReasoningEffort&&!i)return;t.ai={...t.ai,...i&&!t.ai?.apiKey&&{apiKey:np},...e.aiApiKey&&{apiKey:e.aiApiKey},...e.aiImageKey&&{imageApiKey:e.aiImageKey},...e.aiModel&&{model:e.aiModel},...e.aiReasoningEffort&&{reasoningEffort:e.aiReasoningEffort}}}function cp(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 lp(e,t){let r=e.permissions?.rules??[];t.permissions={...e.permissions,rules:r.some((i)=>i.pattern===qr)?r:[{pattern:qr,level:"admin"},...r]}}function dp(e,t){if(e.spaces)t.spaces=e.spaces}function up(e,t){if(e.identity)t.identity=e.identity}function pp(e,t){if(e.agentInstructions)t.agentInstructions=e.agentInstructions}function mp(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=lc(),t.production=Gr()}
|
|
36
36
|
export{se as Z,ye as _,He as $,A as aa,Yc as ba,Xc as ca,el as da,sl as ea,xi as fa,cl as ga,ll as ha,dl as ia,ul as ja,pl as ka,ml as la,gl as ma,fl as na,yr as oa,Ds as pa,Os as qa,Ls as ra,Ut as sa,Ru as ta,Or as ua,Iu as va,Bt as wa,Pu as xa,Cu as ya,Lv as za,Ns as Aa,ku as Ba,Eu as Ca,Au as Da,ju as Ea,Wr as Fa,Ha as Ga,Ka as Ha,ec as Ia,tc as Ja,tp as Ka,PR as La,kR as Ma,WR as Na,NR as Oa};
|
|
37
37
|
|
|
38
|
-
//# debugId=
|
|
39
|
-
//# sourceMappingURL=index-
|
|
38
|
+
//# debugId=DCE27B8247D4441864756E2164756E21
|
|
39
|
+
//# sourceMappingURL=index-swfqashf.js.map
|